-// handle logs the replies of response and runs its tool calls. It returns the
-// input of the next request: input, the output items, the tool results, and
-// the user messages that came in the meantime. After the final answer it
-// returns no input.
-func (l *loop) handle(ctx context.Context, input []any, response Response) ([]any, error) {
- var outputs []any
- for _, raw := range response.Output {
- item, err := inputItem(raw)
- if err != nil {
- return nil, err
- }
-
- input = append(input, item)
-
- var call functionCall
- err = json.Unmarshal(raw, &call)
- if err != nil {
- return nil, fmt.Errorf("decode output item: %w", err)
- }
-
- switch call.Type {
- case "message":
- text, err := outputText([]json.RawMessage{raw})
- if err != nil {
- return nil, err
- }
-
- text = strings.TrimSpace(text)
- if text == "" {
- continue
- }
-
- _, err = l.Append("reply", text)
- if err != nil {
- return nil, fmt.Errorf("%w: %w", errLogWrite, err)
- }
- case "function_call":
- output, err := l.tools.Call(ctx, call.Name, call.Arguments)
- if err != nil {
- return nil, fmt.Errorf("%w: %w", errLogWrite, err)
- }