|
| 1 | +--- |
| 2 | +title: "Agent Builder API" |
| 3 | +permalink: /api/agent-builder/ |
| 4 | +sidebar: |
| 5 | + nav: "docs" |
| 6 | +toc: true |
| 7 | +toc_sticky: true |
| 8 | +--- |
| 9 | + |
| 10 | +The agent builder provides a fluent API for constructing fully-wired agents. |
| 11 | + |
| 12 | +## Constructor |
| 13 | + |
| 14 | +```go |
| 15 | +agent.New(id string, name string) *Builder |
| 16 | +``` |
| 17 | + |
| 18 | +Creates a new builder with defaults: empty tool registry, empty skill registry, guardrails engine, and `MaxConcurrentSubAgents` set to 5. |
| 19 | + |
| 20 | +## Builder Methods |
| 21 | + |
| 22 | +All builder methods return `*Builder` for chaining. |
| 23 | + |
| 24 | +### Identity |
| 25 | + |
| 26 | +| Method | Description | |
| 27 | +|--------|-------------| |
| 28 | +| `Description(d string)` | Set agent description | |
| 29 | +| `WithUserID(id string)` | Set the user ID for memory scoping | |
| 30 | + |
| 31 | +### Core Components |
| 32 | + |
| 33 | +| Method | Description | |
| 34 | +|--------|-------------| |
| 35 | +| `WithModel(p model.Provider)` | Set the LLM provider | |
| 36 | +| `WithStorage(s storage.Storage)` | Set the persistence backend | |
| 37 | +| `WithMemory(m *memory.Store)` | Set the memory store | |
| 38 | +| `WithKnowledge(k knowledge.Knowledge)` | Set the RAG knowledge base | |
| 39 | +| `WithMemoryManager(m *memory.Manager)` | Set the LLM-powered memory manager | |
| 40 | +| `WithGraph(g *graph.StateGraph)` | Set the execution graph | |
| 41 | + |
| 42 | +### Configuration |
| 43 | + |
| 44 | +| Method | Description | |
| 45 | +|--------|-------------| |
| 46 | +| `WithSystemPrompt(prompt string)` | Set the system prompt | |
| 47 | +| `AddInstruction(instruction string)` | Append an instruction to system context | |
| 48 | +| `WithOutputSchema(s map[string]any)` | Set JSON Schema for structured output | |
| 49 | +| `WithHistoryRuns(n int)` | Number of past runs to inject into context | |
| 50 | +| `WithContextConfig(cfg ContextConfig)` | Configure context window management | |
| 51 | + |
| 52 | +### ContextConfig |
| 53 | + |
| 54 | +```go |
| 55 | +type ContextConfig struct { |
| 56 | + MaxContextTokens int // override model default; 0 = use model default |
| 57 | + SummarizeThreshold float64 // fraction of context to trigger summarization (default 0.8) |
| 58 | + PreserveRecentTurns int // recent user/assistant pairs to keep (default 5) |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +### Tools and Skills |
| 63 | + |
| 64 | +| Method | Description | |
| 65 | +|--------|-------------| |
| 66 | +| `AddTool(def *tool.Definition)` | Register a tool the model can call | |
| 67 | +| `AddSkill(s *skill.Skill)` | Register a skill | |
| 68 | +| `AddCapability(capability string)` | Advertise a capability for the protocol bus | |
| 69 | + |
| 70 | +### Middleware |
| 71 | + |
| 72 | +| Method | Description | |
| 73 | +|--------|-------------| |
| 74 | +| `AddHook(h hooks.Hook)` | Append a middleware hook | |
| 75 | +| `AddInputGuardrail(name string, g guardrails.Guardrail)` | Add input validation | |
| 76 | +| `AddOutputGuardrail(name string, g guardrails.Guardrail)` | Add output validation | |
| 77 | + |
| 78 | +### Multi-Agent |
| 79 | + |
| 80 | +| Method | Description | |
| 81 | +|--------|-------------| |
| 82 | +| `AddSubAgent(sub *Agent)` | Register a sub-agent | |
| 83 | + |
| 84 | +### Build |
| 85 | + |
| 86 | +```go |
| 87 | +func (b *Builder) Build() (*Agent, error) |
| 88 | +``` |
| 89 | + |
| 90 | +Compiles the graph (if set) and returns the configured agent. Returns an error if graph compilation fails. |
| 91 | + |
| 92 | +## Agent Methods |
| 93 | + |
| 94 | +### Chat (Single-Turn) |
| 95 | + |
| 96 | +```go |
| 97 | +func (a *Agent) Chat(ctx context.Context, userMessage string) (*model.ChatResponse, error) |
| 98 | +``` |
| 99 | + |
| 100 | +Sends a single user message to the model. Stateless -- no conversation history is maintained between calls. |
| 101 | + |
| 102 | +**Flow:** |
| 103 | +1. Build messages: system prompt, instructions, memories, knowledge, user message |
| 104 | +2. Check input guardrails |
| 105 | +3. Fire `model_call.before` hooks |
| 106 | +4. Call `model.Provider.Chat` |
| 107 | +5. Fire `model_call.after` hooks |
| 108 | +6. Handle tool calls (if any) |
| 109 | +7. Check output guardrails |
| 110 | +8. Extract memories |
| 111 | + |
| 112 | +### ChatWithSession (Multi-Turn) |
| 113 | + |
| 114 | +```go |
| 115 | +func (a *Agent) ChatWithSession(ctx context.Context, sessionID, userMessage string) (*model.ChatResponse, error) |
| 116 | +``` |
| 117 | + |
| 118 | +Sends a message within a persistent, multi-turn session. Messages are stored in the event ledger. When the conversation approaches the model's context window limit, older messages are automatically summarized. |
| 119 | + |
| 120 | +**Requires:** `Storage` must be set on the agent. |
| 121 | + |
| 122 | +**Flow:** |
| 123 | +1. Load or create session |
| 124 | +2. Reconstruct conversation from events |
| 125 | +3. Append user message |
| 126 | +4. Check if summarization is needed |
| 127 | +5. Summarize older messages (if threshold exceeded) |
| 128 | +6. Build messages with system context + summary + recent history |
| 129 | +7. Call model, handle tool calls, check guardrails |
| 130 | +8. Persist assistant response |
| 131 | + |
| 132 | +### Run (Graph Execution) |
| 133 | + |
| 134 | +```go |
| 135 | +func (a *Agent) Run(ctx context.Context, input map[string]any) (*graph.RunState, error) |
| 136 | +``` |
| 137 | + |
| 138 | +Starts a new execution session using the agent's StateGraph. State is checkpointed after every node. |
| 139 | + |
| 140 | +**Requires:** `Graph` and `Storage` must be set. |
| 141 | + |
| 142 | +### Resume |
| 143 | + |
| 144 | +```go |
| 145 | +func (a *Agent) Resume(ctx context.Context, sessionID string) (*graph.RunState, error) |
| 146 | +``` |
| 147 | + |
| 148 | +Continues a paused session from the latest checkpoint. |
| 149 | + |
| 150 | +## YAML Configuration |
| 151 | + |
| 152 | +Agents can also be built from YAML config: |
| 153 | + |
| 154 | +```go |
| 155 | +fc, _ := agent.LoadFile("") |
| 156 | +cfg, _ := fc.FindAgent("dev") |
| 157 | +a, _ := agent.BuildAgent(ctx, cfg) |
| 158 | +``` |
| 159 | + |
| 160 | +See the [Configuration guide]({{ '/getting-started/configuration/' | relative_url }}) for full YAML reference. |
| 161 | + |
| 162 | +## Complete Example |
| 163 | + |
| 164 | +```go |
| 165 | +store, _ := sqlite.New("app.db") |
| 166 | +store.Migrate(ctx) |
| 167 | +
|
| 168 | +tracker := hooks.NewCostTracker(nil) |
| 169 | +
|
| 170 | +a, _ := agent.New("assistant", "AI Assistant"). |
| 171 | + WithModel(model.NewOpenAI(os.Getenv("OPENAI_API_KEY"))). |
| 172 | + WithStorage(store). |
| 173 | + WithSystemPrompt("You are a helpful coding assistant."). |
| 174 | + AddInstruction("Always include code examples."). |
| 175 | + WithContextConfig(agent.ContextConfig{ |
| 176 | + SummarizeThreshold: 0.8, |
| 177 | + PreserveRecentTurns: 5, |
| 178 | + }). |
| 179 | + AddTool(&tool.Definition{ |
| 180 | + Name: "search_docs", |
| 181 | + Description: "Search project documentation", |
| 182 | + Parameters: map[string]any{"type": "object", "properties": map[string]any{ |
| 183 | + "query": map[string]string{"type": "string"}, |
| 184 | + }}, |
| 185 | + Permission: tool.PermAllow, |
| 186 | + Handler: searchHandler, |
| 187 | + }). |
| 188 | + AddHook(hooks.NewRetryHook(3)). |
| 189 | + AddHook(tracker). |
| 190 | + AddInputGuardrail("blocklist", &guardrails.BlocklistGuardrail{ |
| 191 | + Blocklist: []string{"password", "secret"}, |
| 192 | + }). |
| 193 | + Build() |
| 194 | +
|
| 195 | +// Multi-turn session with automatic summarization |
| 196 | +resp, _ := a.ChatWithSession(ctx, "session-001", "How do I implement auth?") |
| 197 | +fmt.Println(resp.Content) |
| 198 | +fmt.Printf("Cost: $%.6f\n", tracker.GetGlobalCost().TotalCost) |
| 199 | +``` |
0 commit comments