Pi Agent Framework Configuration Guide
Architecture Overview
pi-agent has 4 layers:
| Package | Function |
|---|---|
| `pi-ai` | Multi-LLM provider communication (OpenAI/Anthropic/Ollama) |
| `pi-agent-core` | Agent loop + tool calling + state management |
| `pi-coding-agent` | Full coding agent CLI (built-in file tools) |
| `pi-tui` | Terminal UI layer |
Install command:
npm install @earendil-works/pi-ai @earendil-works/pi-agent-core @earendil-works/pi-coding-agent
Node.js >= 18.0.0 required (pi-agent-core depends on fetch API).
Pitfall 1: pi-ai Multi-Provider API Key Loading Failure
Symptom: Configured both OpenAI and Anthropic providers, but model always calls the wrong one.
Error:
Error: No valid API key found for provider: anthropic
Root cause: pi-ai reads provider config from environment variables in order. OPENAI_API_KEY and ANTHROPIC_API_KEY weren't properly exported.
**Fix**: Create .env file in project root:
# .env
OPENAI_API_KEY=sk-xxx
ANTHROPIC_API_KEY=sk-ant-xxx
OLLAMA_BASE_URL=http://localhost:11434
Then load in code:
import { config } from 'dotenv';
config();
// Or manually set
import { setGlobalConfig } from '@earendil-works/pi-ai';
setGlobalConfig({
providers: {
openai: { apiKey: process.env.OPENAI_API_KEY },
anthropic: { apiKey: process.env.ANTHROPIC_API_KEY }
}
});
Verify provider config:
import { listProviders } from '@earendil-works/pi-ai';
console.log(listProviders());
// Output: ['openai', 'anthropic', 'ollama']
Pitfall 2: pi-agent-core Session Restore Not Working
Symptom: Manually saved Session, restarted, state restored but tool call history entirely lost.
**Root cause**: pi-agent-core only saves state snapshot by default, not complete tool call history. You need to configure SessionPersistence to record full history.
Fix: Create persistence config:
import { FileSessionStore } from '@earendil-works/pi-agent-core';
const sessionStore = new FileSessionStore({
sessionDir: './sessions', // Storage directory
maxSessions: 50, // Max 50 sessions
compactionThreshold: 0.7 // Trigger compaction at 70%
});
Inject when starting Agent:
import { Agent } from '@earendil-works/pi-agent-core';
const agent = new Agent({
store: sessionStore,
model: {
provider: 'anthropic',
name: 'claude-sonnet-4-20250514'
}
});
Auto-saves after each interaction. Manual save:
await agent.saveSession('my-session-id');
Restore session:
const agent = await Agent.restore('my-session-id', { store: sessionStore });
Pitfall 3: pi-coding-agent Tool Name Conflicts with Built-ins
**Symptom**: Registered custom file-search tool, got error on run:
Error:
Error: Tool 'file-search' conflicts with built-in tool of the same name
Root cause: pi-coding-agent has 6 built-in tools (read/write/edit/search/bash/task). Registering a tool with the same name causes conflict.
Fix: Two options:
Option A: Disable built-in tools in config
import { CodingAgentConfig } from '@earendil-works/pi-coding-agent';
const config: CodingAgentConfig = {
disableBuiltInTools: ['search'], // Disable search tool
tools: [myCustomFileSearchTool] // Replace with custom tool
};
Option B: Use different tool name
const customSearchTool = {
name: 'custom-file-search', // Non-conflicting name
description: 'Search files with custom logic',
handler: async (query) => { /* ... */ }
};
Recommendation: Use Option B. Keep the built-in search tool as backup.
Pitfall 4: Context Window Overflow After Session Restore
**Symptom**: Restored a session with heavy history. Model responses slow, eventually context_length_exceeded error.
Root cause: Full session history loads into context. Old sessions with long history blow up token count.
Fix: Configure context compaction.
import { Agent } from '@earendil-works/pi-agent-core';
const agent = new Agent({
store: sessionStore,
model: { provider: 'anthropic', name: 'claude-sonnet-4-20250514' },
compaction: {
enabled: true,
threshold: 0.75, // Trigger compaction at 75% context usage
preserveRecent: 10, // Keep last 10 rounds intact
summarizeOlder: true // Compress older对话 into summary
}
});
Manual compaction trigger:
await agent.compactContext();
// Check current token usage
console.log(agent.getContextUsage());
// Output: { used: 160000, limit: 200000, percentage: 80% }
Compaction strategy explanation:
| Strategy | Effect |
|---|---|
| `preserveRecent: 10` | Keep last 10 rounds of dialogue intact |
| `summarizeOlder: true` | Compress content before 10 rounds into summary |
| Custom `filter` | Can filter out certain tool calls (e.g., read-only logs) |
Complete Configuration Example
import dotenv from 'dotenv';
dotenv.config();
import { Agent } from '@earendil-works/pi-agent-core';
import { CodingAgentConfig } from '@earendil-works/pi-coding-agent';
import { FileSessionStore } from '@earendil-works/pi-agent-core';
const sessionStore = new FileSessionStore({
sessionDir: './sessions',
maxSessions: 50
});
const config: CodingAgentConfig = {
model: {
provider: 'anthropic',
name: 'claude-sonnet-4-20250514'
},
store: sessionStore,
compaction: {
enabled: true,
threshold: 0.75,
preserveRecent: 10,
summarizeOlder: true
},
tools: [customTool1, customTool2],
disableBuiltInTools: []
};
const agent = new Agent(config);
Verify Installation
After installation, verify all packages:
node -e "
const piAi = require('@earendil-works/pi-ai');
const piAgent = require('@earendil-works/pi-agent-core');
const piCoding = require('@earendil-works/pi-coding-agent');
console.log('pi-ai:', piAi.listProviders ? 'OK' : 'FAIL');
console.log('pi-agent-core:', piAgent.Agent ? 'OK' : 'FAIL');
console.log('pi-coding-agent:', piCoding.CodingAgent ? 'OK' : 'FAIL');
"
Three lines of OK means installation succeeded.
Summary
pi-agent is a well-designed modular framework. The 4 pitfalls I hit were all configuration-related:
1. **Multi-provider switching**: Ensure .env file exists and API keys are properly exported
2. **Session persistence**: Use FileSessionStore and configure compaction
3. Tool conflicts: Don't name custom tools the same as built-in tools
4. **Context exhaustion**: Configure compaction.threshold for automatic history compression
In practice, session compaction is the most commonly overlooked configuration. Once you have more than 10 historical sessions, compaction strategy is essential — otherwise your context window will blow up at the worst possible moment.
---
Related resources:
📌 This article was AI-assisted generated and human-reviewed | TechPassive — An AI-driven content testing site focused on real tool reviews
🔗 Recommended Tools
These are carefully selected tools. Using our affiliate links supports us to keep producing quality content: