Documentation
¶
Overview ¶
Package agent is the tool-calling loop: ask the model, run the tools it calls, feed the results back, until it answers without a tool call or the step budget ends. It knows nothing of persistence, event transports or approvals; a caller observes the loop through the Config hooks and keeps whatever it needs from the returned transcript.
Index ¶
- Constants
- Variables
- func CapOutput(s string, max int) string
- func Loop(ctx context.Context, maxSteps int, p Policy) (int, error)
- func Parallel(n, limit int, fn func(k int))
- func SafeInvoke(ctx context.Context, t ai.InvokableTool, arguments string) (out string, err error)
- func Schedule(ctx context.Context, calls []ai.ToolCall, ...) error
- func Truncate(s string, n int) string
- type Action
- type Attempt
- type Base
- func (Base) BeginStep(context.Context, *Step) error
- func (Base) EndStep(context.Context, *Step)
- func (Base) Next(_ context.Context, s *Step, reply *ai.Message) (Action, error)
- func (Base) Recover(context.Context, *Step, error) (bool, error)
- func (Base) Replied(context.Context, *Step, *ai.Message, error) error
- type CallError
- type Caller
- type Config
- type Policy
- type ReadOnly
- type Result
- type Step
- type Stream
Examples ¶
Constants ¶
const ( DefaultFirstChunk = 300 * time.Second DefaultIdle = 90 * time.Second DefaultCeiling = 20 * time.Minute )
Budgets of a Caller whose fields are not set.
const DefaultMaxSteps = 20
DefaultMaxSteps bounds a loop whose Config.MaxSteps is not set.
Variables ¶
var ErrNoModel = errors.New("agent: no model")
ErrNoModel is returned when Config.Model is nil.
var ErrStalled = errors.New("the model stream was silent for too long")
ErrStalled is the cause of a call cut by the watchdog.
var ErrStepLimit = errors.New("agent: step limit reached")
ErrStepLimit is returned by Loop when the step budget ended without a policy finishing the run.
Functions ¶
func CapOutput ¶
CapOutput keeps the head (two thirds) and the tail of s within max characters, with a marker between them saying how much was cut. max <= 0 or a shorter s: s unchanged.
Example ¶
CapOutput bounds a tool result before the model reads it, keeping the head and the tail and saying how much was cut.
package main
import (
"fmt"
"strings"
"github.com/7ar-chat/harness/ai/agent"
)
func main() {
long := strings.Repeat("a", 500) + strings.Repeat("z", 500)
out := agent.CapOutput(long, 200)
fmt.Println(len([]rune(out)), strings.HasPrefix(out, "aaa"), strings.HasSuffix(out, "zzz"), strings.Contains(out, "800 characters truncated"))
fmt.Println(agent.CapOutput("short", 200))
}
Output: 200 true true true short
func Loop ¶
Loop runs the policy for at most maxSteps steps (at least one) and returns the number of steps it began. It returns nil when a step finished the run, ErrStepLimit when the budget ended first, ctx.Err() when the context ended between steps, or the error a phase returned.
func Parallel ¶
Parallel calls fn(k) for k in [0, n) with at most limit running at once (limit < 1: all at once) and returns when every call has returned.
func SafeInvoke ¶
SafeInvoke runs a tool and turns a panic in it into an error, so one broken tool cannot take the agent down.
func Schedule ¶
func Schedule(ctx context.Context, calls []ai.ToolCall, parallel func(ctx context.Context, call ai.ToolCall) bool, single func(ctx context.Context, call ai.ToolCall) error, batch func(ctx context.Context, calls []ai.ToolCall) error) error
Schedule runs the tool calls of one step in the model's order. A run of two or more consecutive calls for which parallel reports true is handed to batch as a whole (it decides how to run them, typically with Parallel); every other call goes to single, alone. parallel is asked about a call only after the calls before it have run, so it may look at state they changed (an interrupt, a gate). The context is checked before each run; an error from batch or single stops the schedule and is returned.
Example ¶
Schedule runs a step's tool calls in the model's order and hands consecutive parallel-safe calls to a batch.
package main
import (
"context"
"fmt"
"github.com/7ar-chat/harness/ai"
"github.com/7ar-chat/harness/ai/agent"
)
func main() {
calls := []ai.ToolCall{{ID: "read_a"}, {ID: "read_b"}, {ID: "write_c"}, {ID: "read_d"}}
readOnly := func(_ context.Context, c ai.ToolCall) bool { return c.ID[:4] == "read" }
_ = agent.Schedule(context.Background(), calls, readOnly,
func(_ context.Context, c ai.ToolCall) error { fmt.Println("alone:", c.ID); return nil },
func(_ context.Context, b []ai.ToolCall) error {
ids := make([]string, len(b))
for i, c := range b {
ids[i] = c.ID
}
fmt.Println("together:", ids)
return nil
})
}
Output: together: [read_a read_b] alone: write_c alone: read_d
Types ¶
type Action ¶
type Action int
Action says what the loop does after a model answer.
const ( // Finish ends the loop: the run is complete. Finish Action = iota // Continue starts another step. The policy has already changed whatever the next request is built from. Continue // RunTools runs the answer's tool calls through Policy.Tools, then continues (or finishes, when Tools says stop). RunTools )
type Attempt ¶
type Attempt interface {
// Chunk receives each chunk in order. An error ends the whole call at once and is returned unchanged.
Chunk(ctx context.Context, chunk *ai.Message) error
// Settle is called when the stream is over: complete, or broken because ctx was cancelled mid-stream. An
// error ends the call like one from Chunk.
Settle(ctx context.Context, broken bool) error
// Abort is called when the attempt failed; retry says another attempt follows. An error ends the call.
Abort(ctx context.Context, retry bool) error
}
Attempt is the caller's view of one streamed call. A new one is made for every attempt that got as far as a stream, so a retried call starts from a clean state.
type Base ¶
type Base struct{}
Base implements the phases a policy often leaves alone. Embed it and write the rest.
func (Base) Next ¶
Next finishes on an answer without tool calls and on the last step (whatever it asked for), else runs the tools.
type CallError ¶
type CallError struct {
Err error
Class llm.ErrorClass
}
CallError is a model call that failed and will not be retried (or ran out of retries). Class says how the failure was sorted; Err is the provider's error.
type Caller ¶
type Caller struct {
// FirstChunk, Idle and Ceiling are the budgets (0: the Default values).
FirstChunk, Idle, Ceiling time.Duration
// Retries is how often a failed call is re-issued (0: never).
Retries int
// Backoff is the first retry delay (llm.Backoff doubles it, with jitter, and never goes below Retry-After).
Backoff time.Duration
// Sleep waits between retries (nil: a timer).
Sleep func(ctx context.Context, d time.Duration) error
// OnRetry is called after a failed attempt was aborted and before the wait, with the number of the attempt
// that failed. An error ends the call.
OnRetry func(ctx context.Context, attempt int, class llm.ErrorClass, err error) error
}
Caller makes one model call as a stream under a watchdog and re-issues it when it fails in a way worth retrying. The watchdog cancels an attempt whose first chunk takes longer than FirstChunk, whose chunks come further apart than Idle, or that lasts longer than Ceiling; an event the provider sends that is not a chunk restarts the current budget (a model reasoning silently is not stalled), a keep-alive comment does not.
Example ¶
A Caller streams each model call under a watchdog and retries the ones worth retrying. Give it to Run as Config.Caller, or use it directly in your own loop. Here the first attempt fails with a transient error and the second succeeds.
package main
import (
"context"
"fmt"
"time"
"github.com/7ar-chat/harness/ai"
"github.com/7ar-chat/harness/ai/agent"
"github.com/7ar-chat/harness/ai/llm"
"github.com/7ar-chat/harness/ai/llm/llmtest"
)
func main() {
script := llmtest.New(
llmtest.Turn{Err: fmt.Errorf("status code: 503, overloaded")},
llmtest.Turn{Chunks: llmtest.Text("hello")},
)
caller := &agent.Caller{
Retries: 2,
Sleep: func(context.Context, time.Duration) error { return nil }, // no real waiting in an example
OnRetry: func(_ context.Context, attempt int, class llm.ErrorClass, _ error) error {
fmt.Printf("attempt %d failed (%s), retrying\n", attempt, class)
return nil
},
}
stream, err := caller.Call(context.Background(), script, []*ai.Message{ai.UserMessage("hi")}, nil,
func() agent.Attempt { return observer{} })
reply, _ := ai.ConcatMessages(stream.Chunks)
fmt.Println(reply.Content, "| err:", err)
}
// observer is an Attempt that has nothing to do per chunk. A real one turns chunks into events and undoes them in Abort.
type observer struct{}
func (observer) Chunk(context.Context, *ai.Message) error { return nil }
func (observer) Settle(context.Context, bool) error { return nil }
func (observer) Abort(context.Context, bool) error { return nil }
Output: attempt 1 failed (transient), retrying hello | err: <nil>
func (*Caller) Call ¶
func (c *Caller) Call(ctx context.Context, m ai.ChatModel, msgs []*ai.Message, opts []ai.Option, newAttempt func() Attempt) (*Stream, error)
Call streams m's answer to msgs. A failure that is retryable and within Retries is aborted (Attempt.Abort) and re-issued; any other is returned as *CallError. A cancelled ctx returns ctx.Err() with the part of the stream received (nil when none). newAttempt is called once per attempt that obtained a stream.
type Config ¶
type Config struct {
// Model answers each step; it must already offer the tools of the loop (ai.Model.WithTools).
Model ai.Model
// Tools are the tools the loop may run, by the name in their ToolInfo.
Tools []ai.InvokableTool
// MaxSteps is the number of model calls allowed (0: DefaultMaxSteps). The last one is made with
// tool calls forbidden and, when LimitNudge is set, after that message was appended.
MaxSteps int
// LimitNudge is the user message added before the last step.
LimitNudge string
// Options are passed to every model call.
Options []ai.Option
// Parallel runs consecutive calls of ReadOnly tools at the same time; by default every call runs alone, in
// call order. MaxParallel bounds how many run at once (0: all of them).
Parallel bool
MaxParallel int
// Caller, when set, makes each model call as a stream under its watchdog and retry policy instead of one
// Generate call; chunks are passed to OnChunk as they arrive and merged into the reply with ai.ConcatMessages.
// A retried attempt delivers its chunks again: Caller.OnRetry tells the observer to discard the failed one.
Caller *Caller
// OnChunk receives the chunks of a streamed call (Caller set).
OnChunk func(step int, chunk *ai.Message)
// OnStep is called before each model call with the step number (from 1).
OnStep func(step int)
// OnReply is called with every answer of the model, also one that fails the loop's next stage.
OnReply func(step int, reply *ai.Message)
// OnTool is called after each tool call with its result text.
OnTool func(call ai.ToolCall, result string)
// Invoke runs one tool call and returns the text the model gets. Nil: the default runs the tool of that
// name and reports failures as "error: ..." text, an unknown tool by name.
Invoke func(ctx context.Context, call ai.ToolCall) string
// Steer returns messages to add to the conversation before a model call (nil: none).
Steer func(ctx context.Context, step int) []*ai.Message
}
Config describes one loop.
type Policy ¶
type Policy interface {
// BeginStep prepares the step: steering, compaction, notes. An error ends the run.
BeginStep(ctx context.Context, s *Step) error
// Request builds the model call for the step from the policy's conversation.
Request(ctx context.Context, s *Step) ([]*ai.Message, []ai.Option)
// Call makes the model call of s (s.Messages, s.Options) and returns the assembled answer. A cancelled call
// returns the part it has with ctx.Err(); a call that failed returns a nil message.
Call(ctx context.Context, s *Step) (*ai.Message, error)
// Recover is asked once per step when Call failed with no answer and ctx is alive: it may change the conversation
// so that the same step can be tried again (compact after a context overflow). retry reports whether it did.
Recover(ctx context.Context, s *Step, err error) (retry bool, rerr error)
// Replied records the outcome of Call: the usage, the answer in the conversation, persistence. reply is nil when
// the call produced nothing; callErr is Call's error. A non-nil result ends the run (and wins over callErr).
Replied(ctx context.Context, s *Step, reply *ai.Message, callErr error) error
// Next decides what follows an answer. It is only asked when the call succeeded.
Next(ctx context.Context, s *Step, reply *ai.Message) (Action, error)
// Tools runs the tool calls of the answer after Next returned RunTools. stop ends the run once they ran (a tool
// asked for the user).
Tools(ctx context.Context, s *Step, calls []ai.ToolCall) (stop bool, err error)
// EndStep closes the step: end events, flushing. It must not fail the run.
EndStep(ctx context.Context, s *Step)
}
Policy is everything that varies between agents. The loop owns the shape of a run (steps, the budget, the order of the phases, a retry after a context overflow, stopping on cancellation); a policy owns what a step means: where the conversation lives, how a request is built, what is recorded, which answers end the run and how tools run.
The phases of a step, in order:
BeginStep -> Request -> Call [-> Recover -> Request -> Call] -> Replied -> Next [-> Tools] -> EndStep
EndStep runs for every step whose BeginStep ran, also when a later phase failed.
type ReadOnly ¶
type ReadOnly interface{ ReadOnly() bool }
ReadOnly marks a tool that has no side effects, so several calls of one step may run at the same time (Config.Parallel).
type Result ¶
type Result struct {
// Messages is the whole conversation: the input, every answer and every tool result.
Messages []*ai.Message
// Reply is the last answer of the model (no tool calls unless the step budget ended the loop).
Reply *ai.Message
// Steps is the number of model calls made.
Steps int
}
Result is a finished loop.
func Run ¶
Run executes the loop over the conversation msgs (not modified): the Loop with the policy Config describes. A failed model call returns the conversation so far with the error; a cancelled context returns ctx.Err().
Example ¶
Run asks the model, runs the tools it calls, feeds the results back, and stops when the model answers in plain text. The model here is scripted; with a real one, pass the result of openai.New(...).WithTools(...).
package main
import (
"context"
"fmt"
"github.com/7ar-chat/harness/ai"
"github.com/7ar-chat/harness/ai/agent"
"github.com/7ar-chat/harness/ai/llm/llmtest"
)
type cityArgs struct {
City string `json:"city"`
}
func main() {
weather, _ := ai.InferTool("weather", "Current weather of a city.",
func(_ context.Context, in cityArgs) (string, error) { return in.City + ": 18C, clear", nil })
info, _ := weather.Info(context.Background())
script := llmtest.New(
llmtest.Turn{Chunks: []*ai.Message{llmtest.Finish(llmtest.ToolCall(0, "call_1", "weather", `{"city":"Lyon"}`), "tool_calls")}},
llmtest.Turn{Chunks: llmtest.Text("It is 18C and clear in Lyon.")},
)
model, _ := script.WithTools([]*ai.ToolInfo{info})
res, err := agent.Run(context.Background(), agent.Config{
Model: model,
Tools: []ai.InvokableTool{weather},
OnTool: func(c ai.ToolCall, result string) {
fmt.Printf("%s(%s) -> %s\n", c.Function.Name, c.Function.Arguments, result)
},
}, []*ai.Message{ai.UserMessage("Weather in Lyon?")})
fmt.Println(res.Reply.Content, "| steps:", res.Steps, "| err:", err)
}
Output: weather({"city":"Lyon"}) -> Lyon: 18C, clear It is 18C and clear in Lyon. | steps: 2 | err: <nil>
type Step ¶
type Step struct {
// N is the step number, from 1. Last is set on the final step the budget allows.
N int
Last bool
// Messages and Options are the request of the model call, as returned by Policy.Request.
Messages []*ai.Message
Options []ai.Option
}
Step is one iteration of the loop, shared by the loop and its policy.