14 // modelClient sends model calls.
15 type modelClient interface {
16 Create(ctx context.Context, request Request) (Response, error)
19 // Event tells the clients what the agent does as it happens. Kind is the kind
20 // of a logged message (user, reply, tool, echo), or one of ready, busy, idle,
21 // and error. ID is the ID of a logged message. Source names the client that
22 // sent a user message, such as terminal or telegram, so that each client can
23 // show the messages of the others.
25 Kind string `json:"kind"`
26 ID int `json:"id,omitempty"`
27 Text string `json:"text,omitempty"`
28 Source string `json:"source,omitempty"`
31 // loop runs the turns of one agent. A user message goes to the log when it
32 // comes, and it wakes the loop. A turn waits until every message before it is
33 // summarized. Then its first request holds the prompt, the tools, and the
34 // input of turnInput. The loop runs the tool calls of each response and sends
35 // their results back, until a response has no tool call: the final answer.
37 // The view goes out as the messages of a viewLayout, so the first request of
38 // a turn reads the view of the turn before from the prompt cache.
40 // Each later request of a turn begins with the whole input of the request
41 // before it, then its output items, then the tool results. The output items
42 // hold the reasoning with its encrypted content, because the calls do not
43 // store it. So each request begins with all of the previous one and reads it
44 // from the prompt cache. User messages that come during a turn join the next
45 // request after the tool results. The replies, the tool calls, and the results
46 // go to the log as they happen. The thoughts never do.
53 clock func() time.Time
59 cancel context.CancelFunc
62 // functionCall holds the fields of a function call output item.
63 type functionCall struct {
64 Type string `json:"type"`
65 Name string `json:"name"`
66 Arguments string `json:"arguments"`
67 CallID string `json:"call_id"`
70 // functionCallOutput is the input item with the result of a function call.
71 type functionCallOutput struct {
72 Type string `json:"type"`
73 CallID string `json:"call_id"`
74 Output string `json:"output"`
77 // newLoop returns the loop of agent with its memory. Its calls go through
78 // client, and notify gets each event. The clock gives the date of a turn.
79 func newLoop(agent *Agent, memory *Memory, client modelClient, clock func() time.Time, notify func(Event)) (*loop, error) {
80 layout, err := loadLayout(filepath.Join(agent.dir, layoutFileName))
92 wake: make(chan struct{}, 1),
98 workdir: agent.config.Workdir,
104 // Submit logs a user message from the client source and wakes the loop. The
105 // message joins the next request: the first one of a new turn, or the next one
106 // of a running turn.
107 func (l *loop) Submit(source, text string) (Message, error) {
108 message, err := l.record("user", source, text)
110 return Message{}, err
114 l.pending = append(l.pending, message)
118 case l.wake <- struct{}{}:
125 // Interrupt ends the running turn. A running tool is killed, and the turn sends
126 // no further request.
127 func (l *loop) Interrupt() bool {
129 defer l.mutex.Unlock()
140 // Busy tells if a turn runs.
141 func (l *loop) Busy() bool {
143 defer l.mutex.Unlock()
145 return l.cancel != nil
148 // Append logs a message and tells the clients. The toolbox logs its calls and
149 // results through it.
150 func (l *loop) Append(kind, text string) (Message, error) {
151 return l.record(kind, "", text)
154 // record logs a message and tells the clients, with the client source of a user
156 func (l *loop) record(kind, source, text string) (Message, error) {
157 message, err := l.memory.Append(kind, text)
159 return Message{}, err
172 // Flush makes the log durable.
173 func (l *loop) Flush(ctx context.Context) error {
174 return l.memory.Flush(ctx)
177 // Run runs a turn each time user messages wait, until ctx ends. It returns the
178 // error of a failed log write, which stops the agent.
179 func (l *loop) Run(ctx context.Context) error {
196 // waiting tells if user messages wait for a request.
197 func (l *loop) waiting() bool {
199 defer l.mutex.Unlock()
201 return len(l.pending) > 0
204 // take returns the user messages that wait for a request, and removes them.
205 func (l *loop) take() []Message {
207 defer l.mutex.Unlock()
209 messages := l.pending
215 // turn runs one turn. A failed or interrupted model call ends the turn and
216 // tells the clients. The messages of the turn stay in the log and the view, and
217 // the next turn starts only with a new message, so a lasting failure such as a
218 // needed login does not repeat. Only a failed log write is an error of turn.
219 func (l *loop) turn(ctx context.Context) error {
220 ctx, cancel := context.WithCancel(ctx)
238 if err != nil && !errors.Is(err, errLogWrite) {
241 Text: turnError(ctx, err),
254 // errLogWrite marks an error of a log write, which ends the loop.
255 var errLogWrite = errors.New("log write failed")
257 // chain runs the request chain of a turn until the final answer.
258 func (l *loop) chain(ctx context.Context) error {
260 if len(messages) == 0 {
264 err := l.memory.Wait(ctx)
269 instructions, err := l.agent.Prompt()
274 skip := make(map[int]bool, len(messages))
275 for _, message := range messages {
276 skip[message.ID] = true
279 view, err := l.layout.Split(l.memory.ViewLines(skip))
284 input := turnInput(view, l.state(), messages)
285 for turn := "first"; ; turn = "next" {
286 response, err := l.client.Create(ctx, Request{
287 Model: l.agent.config.Model,
288 Effort: l.agent.config.Effort,
289 Instructions: instructions,
298 input, err = l.handle(ctx, input, response)
309 // handle logs the replies of response and runs its tool calls. It returns the
310 // input of the next request: input, the output items, the tool results, and
311 // the user messages that came in the meantime. After the final answer it
313 func (l *loop) handle(ctx context.Context, input []any, response Response) ([]any, error) {
315 for _, raw := range response.Output {
316 item, err := inputItem(raw)
321 input = append(input, item)
323 var call functionCall
324 err = json.Unmarshal(raw, &call)
326 return nil, fmt.Errorf("decode output item: %w", err)
331 text, err := outputText([]json.RawMessage{raw})
336 text = strings.TrimSpace(text)
341 _, err = l.Append("reply", text)
343 return nil, fmt.Errorf("%w: %w", errLogWrite, err)
345 case "function_call":
346 output, err := l.tools.Call(ctx, call.Name, call.Arguments)
348 return nil, fmt.Errorf("%w: %w", errLogWrite, err)
351 outputs = append(outputs, functionCallOutput{
352 Type: "function_call_output",
359 if len(outputs) == 0 {
363 input = append(input, outputs...)
364 for _, message := range l.take() {
365 input = append(input, userMessage(message.Text))
371 // state returns the per-turn state: the end of the view, and the date and time
373 func (l *loop) state() string {
374 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
377 // turnInput returns the input of the first request of a turn, stable parts
378 // first: a user message for each view message, one with the per-turn state,
379 // and one for each new message, whole. The view leaves out the leaf lines of
381 func turnInput(view []string, state string, messages []Message) []any {
382 input := make([]any, 0, len(view)+1+len(messages))
383 for _, text := range view {
384 input = append(input, userMessage(text))
387 input = append(input, userMessage(state))
388 for _, message := range messages {
389 input = append(input, userMessage(message.Text))
395 // inputItem returns an output item as an input item for the next request. The
396 // calls do not store their items, so the item goes back whole, without its id.
397 func inputItem(raw json.RawMessage) (map[string]any, error) {
398 var item map[string]any
399 err := json.Unmarshal(raw, &item)
401 return nil, fmt.Errorf("decode output item: %w", err)
409 // turnError returns the text of the error that ended a turn.
410 func turnError(ctx context.Context, err error) string {
411 if ctx.Err() != nil {