♻️ Quality: internal/engine without smells (28 → 0)
- generate(): the turn's state and steps in turn.go — one method per hand-back (loops, broken stream, broken arguments, cut reasoning, failed edit) sharing handBack; wrapTool, onChunk, emit - Explain / turnStruggle: ordered tables; openaiCompat.Explain: one result variable; extracted steps in Summarize, probeOpenAI, pull, unload, xmlTools, the SSE tap, normalizeEdit, expectedArgs - Responses provider: post, input, result and stream in their own files with small steps - engine.go, toolschema.go, xmltools.go and the history counts split by theme Same behaviour and printed texts; go test ./... green; checked live. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5bb7026 parent: e8674a1 modified
.tickets/issues/0283-quality-code-smells-of-the-core-zone-by-zone.yaml +12 -3 | @@ -6,7 +6,7 @@ author: | ||
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-28T10:19:47.000Z |
| 9 | -updatedAt: 2026-11-28T10:19:47.000Z | |
| 9 | +updatedAt: 2026-11-28T10:32:34.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - kind::chore |
| 12 | 12 | milestone: v2.2.0 |
| @@ -17,12 +17,14 @@ body: | | ||
| 17 | 17 | tasks: |
| 18 | 18 | - id: 1 |
| 19 | 19 | title: "internal/engine" |
| 20 | - state: open | |
| 20 | + state: closed | |
| 21 | 21 | priority: medium |
| 22 | 22 | author: |
| 23 | 23 | name: k33g |
| 24 | 24 | email: ph.charriere@gmail.com |
| 25 | 25 | createdAt: 2026-11-28T10:19:47.000Z |
| 26 | + updatedAt: 2026-11-28T10:32:34.000Z | |
| 27 | + closedAt: 2026-11-28T10:32:34.000Z | |
| 26 | 28 | - id: 2 |
| 27 | 29 | title: "internal/config" |
| 28 | 30 | state: open |
| @@ -71,4 +73,11 @@ tasks: | ||
| 71 | 73 | name: k33g |
| 72 | 74 | email: ph.charriere@gmail.com |
| 73 | 75 | createdAt: 2026-11-28T10:19:47.000Z |
| 74 | -comments: [] | |
| 76 | +comments: | |
| 77 | + - id: 1 | |
| 78 | + author: | |
| 79 | + name: k33g | |
| 80 | + email: ph.charriere@gmail.com | |
| 81 | + createdAt: 2026-11-28T10:32:34.000Z | |
| 82 | + body: | | |
| 83 | + internal/engine: 28 → 0 smells (total 210 → 182). generate() split into a `turn` (turn.go: wrapModel with one method per hand-back sharing handBack, wrapTool, onChunk, emit, retryableWithoutStreaming); Explain and turnStruggle as ordered tables; one-variable switches (openaiCompat.Explain); extracted steps in Summarize, probeOpenAI, ensureModel / pullDMR, UnloadAgent / unloadKeepAlive, xmlTools, reasoningTap / sseTap.report, normalizeEdit, expectedArgs, the Responses provider (post, input, result, stream); engine.go, responses.go, toolschema.go, xmltools.go, history.go split by theme. Printed texts unchanged. go test ./... green; live: a read_skill turn, LFM3 plain answer, decisionContext, decisionResult. | |
| @@ -6,7 +6,7 @@ author: | |||
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-28T10:19:47.000Z | 8 | createdAt: 2026-11-28T10:19:47.000Z |
| 9 | -updatedAt: 2026-11-28T10:19:47.000Z | 9 | +updatedAt: 2026-11-28T10:32:34.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - kind::chore | 11 | - kind::chore |
| 12 | milestone: v2.2.0 | 12 | milestone: v2.2.0 |
| @@ -17,12 +17,14 @@ body: | | |||
| 17 | tasks: | 17 | tasks: |
| 18 | - id: 1 | 18 | - id: 1 |
| 19 | title: "internal/engine" | 19 | title: "internal/engine" |
| 20 | - state: open | 20 | + state: closed |
| 21 | priority: medium | 21 | priority: medium |
| 22 | author: | 22 | author: |
| 23 | name: k33g | 23 | name: k33g |
| 24 | email: ph.charriere@gmail.com | 24 | email: ph.charriere@gmail.com |
| 25 | createdAt: 2026-11-28T10:19:47.000Z | 25 | createdAt: 2026-11-28T10:19:47.000Z |
| 26 | + updatedAt: 2026-11-28T10:32:34.000Z | ||
| 27 | + closedAt: 2026-11-28T10:32:34.000Z | ||
| 26 | - id: 2 | 28 | - id: 2 |
| 27 | title: "internal/config" | 29 | title: "internal/config" |
| 28 | state: open | 30 | state: open |
| @@ -71,4 +73,11 @@ tasks: | |||
| 71 | name: k33g | 73 | name: k33g |
| 72 | email: ph.charriere@gmail.com | 74 | email: ph.charriere@gmail.com |
| 73 | createdAt: 2026-11-28T10:19:47.000Z | 75 | createdAt: 2026-11-28T10:19:47.000Z |
| 74 | -comments: [] | 76 | +comments: |
| 77 | + - id: 1 | ||
| 78 | + author: | ||
| 79 | + name: k33g | ||
| 80 | + email: ph.charriere@gmail.com | ||
| 81 | + createdAt: 2026-11-28T10:32:34.000Z | ||
| 82 | + body: | | ||
| 83 | + internal/engine: 28 → 0 smells (total 210 → 182). generate() split into a `turn` (turn.go: wrapModel with one method per hand-back sharing handBack, wrapTool, onChunk, emit, retryableWithoutStreaming); Explain and turnStruggle as ordered tables; one-variable switches (openaiCompat.Explain); extracted steps in Summarize, probeOpenAI, ensureModel / pullDMR, UnloadAgent / unloadKeepAlive, xmlTools, reasoningTap / sseTap.report, normalizeEdit, expectedArgs, the Responses provider (post, input, result, stream); engine.go, responses.go, toolschema.go, xmltools.go, history.go split by theme. Printed texts unchanged. go test ./... green; live: a read_skill turn, LFM3 plain answer, decisionContext, decisionResult. | ||
modified
internal/engine/engine.go +42 -776 | @@ -11,11 +11,7 @@ package engine | ||
| 11 | 11 | |
| 12 | 12 | import ( |
| 13 | 13 | "context" |
| 14 | - "encoding/json" | |
| 15 | - "fmt" | |
| 16 | - "maps" | |
| 17 | 14 | "slices" |
| 18 | - "strings" | |
| 19 | 15 | "sync" |
| 20 | 16 | "sync/atomic" |
| 21 | 17 | |
| @@ -138,112 +134,39 @@ func (e *Engine) ForgetInputTokens() { e.lastInput.Store(0) } | ||
| 138 | 134 | // Explain turns a transport error into the one-line, actionable message the |
| 139 | 135 | // REPL prints between brackets. See Provider.Explain for the rationale. |
| 140 | 136 | func (e *Engine) Explain(err error) string { |
| 141 | - // The loop detector ended the turn: its own sentence is the whole | |
| 142 | - // diagnosis, whatever the provider. | |
| 143 | - if sentence, ok := stuckTurn(err); ok { | |
| 144 | - return sentence | |
| 145 | - } | |
| 146 | - // A tool call with broken arguments: the raw error quotes them whole — | |
| 147 | - // a truncated document, on the day it was seen — so it gets a line of | |
| 148 | - // its own (toolargs.go). | |
| 149 | - if line, ok := badToolArgs(err); ok { | |
| 150 | - return line | |
| 151 | - } | |
| 152 | - // The model looped again after the note (textloop.go, ticket 235): its | |
| 153 | - // own sentence says what it repeated. | |
| 154 | - if le, ok := looped(err); ok { | |
| 155 | - return le.Error() | |
| 156 | - } | |
| 157 | - // The request outgrew the server's window (ctxsize.go, ticket 233): said | |
| 158 | - // with the sizes, before the generic "stream broke" line would blame | |
| 159 | - // the connection. | |
| 160 | - if line, ok := overflowLine(err); ok { | |
| 161 | - return line | |
| 162 | - } | |
| 163 | - // A stream the server broke, even after the retry: the server's own | |
| 164 | - // words when it streamed some (servererr.go), never "unexpected end of | |
| 165 | - // JSON input" alone. | |
| 166 | - if line, ok := badStream(err); ok { | |
| 167 | - return line | |
| 137 | + for _, explain := range turnExplainers { | |
| 138 | + if line, ok := explain(err); ok { | |
| 139 | + return line | |
| 140 | + } | |
| 168 | 141 | } |
| 169 | 142 | return e.Provider.Explain(err, e.Backend) |
| 170 | 143 | } |
| 171 | 144 | |
| 172 | -// blanks is the set of characters the model adds around its text without any of | |
| 173 | -// it showing on screen. | |
| 174 | -const blanks = " \t\r\n" | |
| 175 | - | |
| 176 | -// gap holds back the TRAILING whitespace of the streamed text: it is only | |
| 177 | -// printed if visible text follows. Without that, the line breaks the model puts | |
| 178 | -// after its sentence are printed as-is, and the screen hollows out. | |
| 145 | +// turnExplainers know the failures of a turn that are mm's own, whatever the | |
| 146 | +// provider; the first one that knows the error says it: | |
| 179 | 147 | // |
| 180 | -// The model produces MORE AND MORE of it as the turns go by — it imitates its | |
| 181 | -// own messages, which it re-reads in the history every turn. Measured: 2 blank | |
| 182 | -// lines before the first 🛠️, 4 before the second, 7, then 11. Holding the | |
| 183 | -// whitespace back is enough to remove all of it, since that whitespace is never | |
| 184 | -// followed by text: it is a tool that writes next. | |
| 185 | -type gap struct { | |
| 186 | - // The `bash` tool may call drop() from SEVERAL goroutines — Genkit runs the | |
| 187 | - // calls of a single turn in parallel (see printMu in tools). | |
| 188 | - mu sync.Mutex | |
| 189 | - held string // whitespace waiting to be followed by text | |
| 190 | - started bool // visible text has already been printed | |
| 191 | -} | |
| 192 | - | |
| 193 | -// next returns what should be printed for this chunk, "" when there is nothing | |
| 194 | -// to print right now. | |
| 195 | -func (g *gap) next(text string) string { | |
| 196 | - g.mu.Lock() | |
| 197 | - defer g.mu.Unlock() | |
| 198 | - | |
| 199 | - body := strings.TrimRight(text, blanks) | |
| 200 | - if body == "" { // an all-whitespace chunk: set aside, not printed | |
| 201 | - if g.started { | |
| 202 | - g.held += text | |
| 203 | - } | |
| 204 | - return "" | |
| 205 | - } | |
| 206 | - | |
| 207 | - // The chunk splits in three: leading whitespace, text, trailing whitespace. | |
| 208 | - tail := text[len(body):] | |
| 209 | - visible := strings.TrimLeft(body, blanks) | |
| 210 | - lead := body[:len(body)-len(visible)] | |
| 211 | - | |
| 212 | - out := "" | |
| 213 | - if g.started { // before the first word, all whitespace is dropped | |
| 214 | - out = squeeze(g.held + lead) | |
| 215 | - } | |
| 216 | - g.held, g.started = tail, true | |
| 217 | - return out + visible | |
| 218 | -} | |
| 219 | - | |
| 220 | -// drop forgets the pending whitespace. Called when someone ELSE is about to | |
| 221 | -// write — a tool announcing its command: that whitespace belonged to the text | |
| 222 | -// before it, and printing it now would reopen the hole we just closed. | |
| 223 | -func (g *gap) drop() { | |
| 224 | - g.mu.Lock() | |
| 225 | - g.held = "" | |
| 226 | - g.mu.Unlock() | |
| 227 | -} | |
| 228 | - | |
| 229 | -// squeeze brings any run of line breaks down to two, that is ONE blank line at | |
| 230 | -// most. Spaces are left alone: they carry the indentation of a code block, and | |
| 231 | -// cutting it would shift the displayed code. | |
| 232 | -func squeeze(s string) string { | |
| 233 | - var b strings.Builder | |
| 234 | - run := 0 | |
| 235 | - for _, r := range s { | |
| 236 | - if r == '\n' { | |
| 237 | - run++ | |
| 238 | - if run > 2 { | |
| 239 | - continue | |
| 240 | - } | |
| 241 | - } else { | |
| 242 | - run = 0 | |
| 243 | - } | |
| 244 | - b.WriteRune(r) | |
| 245 | - } | |
| 246 | - return b.String() | |
| 148 | +// - the loop detector ended the turn: its own sentence is the whole | |
| 149 | +// diagnosis; | |
| 150 | +// - a tool call with broken arguments: the raw error quotes them whole — a | |
| 151 | +// truncated document, on the day it was seen — so it gets a line of its | |
| 152 | +// own (toolargs.go); | |
| 153 | +// - the model looped again after the note (textloop.go, ticket 235): its | |
| 154 | +// own sentence says what it repeated; | |
| 155 | +// - the request outgrew the server's window (ctxsize.go, ticket 233): said | |
| 156 | +// with the sizes, before the generic "stream broke" line would blame the | |
| 157 | +// connection; | |
| 158 | +// - a stream the server broke, even after the retry: the server's own words | |
| 159 | +// when it streamed some (servererr.go), never "unexpected end of JSON | |
| 160 | +// input" alone. | |
| 161 | +var turnExplainers = []func(error) (string, bool){stuckTurn, badToolArgs, loopedLine, overflowLine, badStream} | |
| 162 | + | |
| 163 | +// loopedLine is looped's sentence. | |
| 164 | +func loopedLine(err error) (string, bool) { | |
| 165 | + le, ok := looped(err) | |
| 166 | + if !ok { | |
| 167 | + return "", false | |
| 168 | + } | |
| 169 | + return le.Error(), true | |
| 247 | 170 | } |
| 248 | 171 | |
| 249 | 172 | // Generate queries the model, printing the answer as it comes (streaming). Some |
| @@ -316,7 +239,8 @@ func runTurnEnd() { | ||
| 316 | 239 | } |
| 317 | 240 | |
| 318 | 241 | // generate is Generate without the generation hooks (hooks.go): the turn |
| 319 | -// itself. The tool hooks run inside it, in the WrapTool middleware. | |
| 242 | +// itself. The tool hooks run inside it, in the WrapTool middleware. The | |
| 243 | +// turn's state and its steps live in turn.go. | |
| 320 | 244 | func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []ai.ToolRef) (*ai.ModelResponse, []*ai.Message, error) { |
| 321 | 245 | // Tool routing (ticket 127) runs here, after the preGeneration hooks: a |
| 322 | 246 | // question a hook stopped never reaches the decider, and the one routed |
| @@ -329,330 +253,13 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | ||
| 329 | 253 | // neither reads it as part of the question. |
| 330 | 254 | messages = withReminder(messages, config.Cfg.TurnReminder) |
| 331 | 255 | ctx = WithConversation(ctx, messages) |
| 332 | - // Genkit only hands us back the LAST message. The intermediate turns — "I | |
| 333 | - // am calling bash", "here is the output" — exist only in the request it | |
| 334 | - // builds for the next turn. This middleware captures that request on its way | |
| 335 | - // through: the last turn seen therefore holds the whole conversation. | |
| 336 | - // | |
| 337 | - // The `WrapModel` hook wraps every call to the model — one per turn — so the | |
| 338 | - // last request seen is the most complete one. `MiddlewareFunc` adapts a | |
| 339 | - // closure to the `ai.Middleware` contract without going through a plugin: | |
| 340 | - // `New` is called once per `Generate`, which keeps `full` captured at the | |
| 341 | - // right level. | |
| 342 | - var full []*ai.Message | |
| 343 | - // speed measures the generation speed of each call and of the turn | |
| 344 | - // (speed.go, ticket 254); nil with showSpeed off. | |
| 345 | - speed := turnSpeedMeter() | |
| 346 | - defer func() { | |
| 347 | - if speed != nil { | |
| 348 | - speed.finish() | |
| 349 | - } | |
| 350 | - }() | |
| 351 | - // reply is the model's latest message — for a tool, the one that called | |
| 352 | - // it (reply.go). | |
| 353 | - var reply *ai.Message | |
| 354 | - // pl is the watchdog's pulse, set below; every model call restarts the | |
| 355 | - // wait for a first token (progress.go). | |
| 356 | - var pl *pulse | |
| 357 | - // argRetries counts the broken tool calls handed back to the model in | |
| 358 | - // this generation (toolargs.go). | |
| 359 | - argRetries := 0 | |
| 360 | - // cutRetries counts the replies cut mid-reasoning handed back (ticket 232). | |
| 361 | - cutRetries := 0 | |
| 362 | - // loops watches each model call's stream for a sentence repeated over and | |
| 363 | - // over (textloop.go, ticket 235); loopRetries counts the calls handed back. | |
| 364 | - var loops loopWatch | |
| 365 | - loopRetries := 0 | |
| 366 | - // editRetries counts the answers handed back because the last file change | |
| 367 | - // of the turn had failed (toolargs.go, ticket 242). | |
| 368 | - editRetries := 0 | |
| 369 | - var gaps gap | |
| 370 | - // invalid counts the tool calls of this generation that failed the schema | |
| 371 | - // (toolschema.go): the same invalid call repeated ends the turn. | |
| 372 | - var invalid invalidCalls | |
| 373 | - // think is the turn's thought block: see reasoning.go and thoughts below. | |
| 374 | - // Declared here because emit, defined further down, closes over it. | |
| 375 | - think := &thoughts{} | |
| 376 | - capture := ai.MiddlewareFunc(func(context.Context) (*ai.Hooks, error) { | |
| 377 | - return &ai.Hooks{ | |
| 378 | - WrapModel: func(ctx context.Context, params *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) { | |
| 379 | - // Same tools, same order, on every call: the server's prompt | |
| 380 | - // cache depends on it (tooldefs.go, ticket 53). | |
| 381 | - params.Request.Tools = stableTools(params.Request.Tools) | |
| 382 | - // From the turn's second call on — tools have run — a history | |
| 383 | - // past the threshold is made smaller first (inturn.go, ticket | |
| 384 | - // 251). The wait counts as the call's: the summary is no beat. | |
| 385 | - if config.Cfg.Context.CompressInTurn && len(params.Request.Messages) > len(messages) { | |
| 386 | - pl.expect() | |
| 387 | - e.compactInTurn(ctx, params) | |
| 388 | - } | |
| 389 | - // Messages the user sent during the turn (ticket 265, | |
| 390 | - // steer.go) join the history after the tool results. | |
| 391 | - params.Request.Messages = takeSteer(ctx, params.Request.Messages) | |
| 392 | - full = slices.Clone(params.Request.Messages) | |
| 393 | - // call runs ONE model call under its own context, which the | |
| 394 | - // loop watch cancels when the stream repeats itself — the | |
| 395 | - // call, not the generation. | |
| 396 | - call := func(ctx context.Context) (*ai.ModelResponse, error) { | |
| 397 | - callCtx, cancel := context.WithCancel(ctx) | |
| 398 | - defer cancel() | |
| 399 | - loops.arm(cancel) | |
| 400 | - defer loops.disarm() | |
| 401 | - return next(callCtx, params) | |
| 402 | - } | |
| 403 | - pl.expect() | |
| 404 | - resp, err := call(ctx) | |
| 405 | - err = withServerMessage(ctx, err) | |
| 406 | - // A call cut because the model was repeating itself is handed | |
| 407 | - // back once with a note; looping again ends the turn | |
| 408 | - // (textloop.go, ticket 235). | |
| 409 | - for ctx.Err() == nil { | |
| 410 | - sample, times, cut := loops.take() | |
| 411 | - if !cut { | |
| 412 | - break | |
| 413 | - } | |
| 414 | - think.done() | |
| 415 | - spinner.Stop() | |
| 416 | - if loopRetries >= maxLoopRetries { | |
| 417 | - return nil, loopError{sample: sample, times: times} | |
| 418 | - } | |
| 419 | - loopRetries++ | |
| 420 | - _, _ = fmt.Fprintf(ui.Out, "\n[the model repeated %q %d times in a row — stopped it and asked for the answer, %d/%d]\n", | |
| 421 | - shorten(sample, 60), times, loopRetries, maxLoopRetries) | |
| 422 | - ui.ReportStruggle(ui.Struggle{Label: fmt.Sprintf("looped — handed back %d/%d", loopRetries, maxLoopRetries)}) | |
| 423 | - params.Request.Messages = append(slices.Clone(params.Request.Messages), loopRetryNote(sample, times)) | |
| 424 | - full = slices.Clone(params.Request.Messages) | |
| 425 | - pl.expect() | |
| 426 | - resp, err = call(ctx) | |
| 427 | - err = withServerMessage(ctx, err) | |
| 428 | - } | |
| 429 | - // A stream the server broke — an error event, a cut | |
| 430 | - // connection (servererr.go) — is retried ONCE, this model call | |
| 431 | - // only. The turn-level retry below cannot help once a tool has | |
| 432 | - // run (it would replay the tools); this one replays nothing but | |
| 433 | - // the call that failed. Seen: a turn ended on "unexpected end | |
| 434 | - // of JSON input" after twenty tool calls and a written file. | |
| 435 | - // Text the broken attempt already streamed is not taken back. | |
| 436 | - if streamBroken(err) && !contextOverflow(err) && ctx.Err() == nil { | |
| 437 | - spinner.Stop() | |
| 438 | - _, _ = fmt.Fprintf(ui.Out, "\n[%s — retrying this model call once]\n", streamNotice(err)) | |
| 439 | - ui.ReportStruggle(ui.Struggle{Label: "stream cut — retried"}) | |
| 440 | - pl.expect() | |
| 441 | - resp, err = call(ctx) | |
| 442 | - err = withServerMessage(ctx, err) | |
| 443 | - } | |
| 444 | - // A tool call whose arguments did not parse — cut off by | |
| 445 | - // max_tokens, most of the time — is given back to the model | |
| 446 | - // with a note instead of ending the turn. The note goes into | |
| 447 | - // params.Request itself: Genkit builds the next turn's request | |
| 448 | - // from that same value, so it stays in the conversation — the | |
| 449 | - // model needs it again when it writes the second piece — and | |
| 450 | - // `full` carries it into the history. | |
| 451 | - for argRetries < maxArgRetries && ctx.Err() == nil { | |
| 452 | - truncated, malformed := argsError(err) | |
| 453 | - if !truncated && !malformed { | |
| 454 | - break | |
| 455 | - } | |
| 456 | - argRetries++ | |
| 457 | - what := "invalid JSON" | |
| 458 | - if truncated { | |
| 459 | - what = "cut off" | |
| 460 | - } | |
| 461 | - // ui.Out: stderr in ACP mode, never the JSON-RPC stream. | |
| 462 | - spinner.Stop() | |
| 463 | - _, _ = fmt.Fprintf(ui.Out, "\n[tool call arguments did not parse (%s: …%s) — handing it back to the model, %d/%d]\n", | |
| 464 | - what, lastRunes(err.Error(), 60), argRetries, maxArgRetries) | |
| 465 | - ui.ReportStruggle(ui.Struggle{Label: fmt.Sprintf("broken tool call (%s) %d/%d", what, argRetries, maxArgRetries)}) | |
| 466 | - params.Request.Messages = append(slices.Clone(params.Request.Messages), argsRetryNote(truncated)) | |
| 467 | - full = slices.Clone(params.Request.Messages) | |
| 468 | - pl.expect() | |
| 469 | - resp, err = call(ctx) | |
| 470 | - err = withServerMessage(ctx, err) | |
| 471 | - } | |
| 472 | - // A reply cut by the answer limit while the model was still | |
| 473 | - // reasoning — no text, no tool call — is handed back once with | |
| 474 | - // a note (toolargs.go, ticket 232), the same way. | |
| 475 | - for cutRetries < maxCutRetries && ctx.Err() == nil && reasoningCut(resp, err) { | |
| 476 | - cutRetries++ | |
| 477 | - spinner.Stop() | |
| 478 | - _, _ = fmt.Fprintf(ui.Out, "\n[the model reasoned until the answer limit without answering — asking it to act now, %d/%d]\n", cutRetries, maxCutRetries) | |
| 479 | - ui.ReportStruggle(ui.Struggle{Label: fmt.Sprintf("reasoning cut at the limit %d/%d", cutRetries, maxCutRetries)}) | |
| 480 | - params.Request.Messages = append(slices.Clone(params.Request.Messages), cutRetryNote()) | |
| 481 | - full = slices.Clone(params.Request.Messages) | |
| 482 | - pl.expect() | |
| 483 | - resp, err = call(ctx) | |
| 484 | - err = withServerMessage(ctx, err) | |
| 485 | - } | |
| 486 | - // An ANSWER given while the turn's last file change failed is | |
| 487 | - // handed back once (toolargs.go, ticket 242): the model can | |
| 488 | - // still fix its call, or say it failed. The answer stays in the | |
| 489 | - // conversation, so the note can refer to it. | |
| 490 | - for editRetries < maxEditRetries && ctx.Err() == nil && err == nil && resp != nil && resp.Message != nil && len(resp.ToolRequests()) == 0 { | |
| 491 | - turn := params.Request.Messages[min(len(messages), len(params.Request.Messages)):] | |
| 492 | - tool, failure, failed := lastFailedFileChange(turn) | |
| 493 | - if !failed { | |
| 494 | - break | |
| 495 | - } | |
| 496 | - editRetries++ | |
| 497 | - think.done() | |
| 498 | - spinner.Stop() | |
| 499 | - _, _ = fmt.Fprintf(ui.Out, "\n[the last %s failed — the file was not changed; asking the model to fix the call or say so, %d/%d]\n", tool, editRetries, maxEditRetries) | |
| 500 | - ui.ReportStruggle(ui.Struggle{Label: fmt.Sprintf("answer after a failed %s — handed back %d/%d", tool, editRetries, maxEditRetries)}) | |
| 501 | - params.Request.Messages = append(slices.Clone(params.Request.Messages), ai.NewModelTextMessage(resp.Text()), failedEditNote(tool, failure)) | |
| 502 | - full = slices.Clone(params.Request.Messages) | |
| 503 | - pl.expect() | |
| 504 | - resp, err = call(ctx) | |
| 505 | - err = withServerMessage(ctx, err) | |
| 506 | - } | |
| 507 | - // The server's own count of what it just read: the one exact | |
| 508 | - // measure of the context size, kept for the compression | |
| 509 | - // trigger. Zero means the server reported nothing. | |
| 510 | - if resp != nil && resp.Usage != nil && resp.Usage.InputTokens > 0 { | |
| 511 | - e.lastInput.Store(int64(resp.Usage.InputTokens)) | |
| 512 | - } | |
| 513 | - // An event-consuming front end (ACP) wants the counts of | |
| 514 | - // every call, not just the last input: the client shows the | |
| 515 | - // context meter and the tokens a turn cost. | |
| 516 | - if speed != nil && resp != nil { | |
| 517 | - out := 0 | |
| 518 | - if resp.Usage != nil { | |
| 519 | - out = resp.Usage.OutputTokens | |
| 520 | - } | |
| 521 | - speed.settle(out) | |
| 522 | - } | |
| 523 | - if resp != nil && resp.Usage != nil { | |
| 524 | - if s, ok := ui.ActiveSink().(ui.UsageSink); ok { | |
| 525 | - s.Usage(ui.Usage{ | |
| 526 | - InputTokens: resp.Usage.InputTokens, | |
| 527 | - OutputTokens: resp.Usage.OutputTokens, | |
| 528 | - ThoughtTokens: resp.Usage.ThoughtsTokens, | |
| 529 | - CachedReadTokens: resp.Usage.CachedContentTokens, | |
| 530 | - }) | |
| 531 | - } | |
| 532 | - } | |
| 533 | - dropReasoning(resp) | |
| 534 | - if resp != nil { | |
| 535 | - reply = resp.Message | |
| 536 | - } | |
| 537 | - return resp, err | |
| 538 | - }, | |
| 539 | - // The tool is about to write to the screen: we forget the | |
| 540 | - // whitespace the previous text left pending. The hook lands at | |
| 541 | - // exactly the right moment — just before the tool prints its 🛠️ | |
| 542 | - // line. | |
| 543 | - // The tool hooks run here too (hooks.go): one place sees every | |
| 544 | - // call, built-in and MCP, before the tool asks for consent. | |
| 545 | - // schemaGuard (toolschema.go, ticket 225) wraps the whole chain: it | |
| 546 | - // repairs the file tools' arguments before the hooks see them, and | |
| 547 | - // turns a schema error left after them into a result the model reads. | |
| 548 | - WrapTool: func(ctx context.Context, params *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error) { | |
| 549 | - gaps.drop() | |
| 550 | - ctx = withReply(ctx, reply) | |
| 551 | - return schemaGuard(ctx, params, &invalid, func(ctx context.Context, params *ai.ToolParams) (*ai.MultipartToolResponse, error) { | |
| 552 | - if !e.hooks.Enabled() && toolJudge == nil && resultJudge == nil { | |
| 553 | - return next(ctx, params) | |
| 554 | - } | |
| 555 | - return e.runToolHooks(ctx, params, next) | |
| 556 | - }) | |
| 557 | - }, | |
| 558 | - }, nil | |
| 559 | - }) | |
| 560 | - | |
| 561 | - opts := []ai.GenerateOption{ | |
| 562 | - ai.WithModelName(e.Model), | |
| 563 | - ai.WithMessages(messages...), | |
| 564 | - ai.WithTools(tools...), | |
| 565 | - ai.WithMaxTurns(config.Cfg.MaxTurns), // max model ↔ tools round trips | |
| 566 | - ai.WithConfig(config.Cfg.Sampling), | |
| 567 | - ai.WithUse(capture), | |
| 568 | - } | |
| 569 | - // structuredOutput (ticket 80): the server constrains the answer to the | |
| 570 | - // schema, and Genkit checks it against the schema before handing it back. | |
| 571 | - if config.Cfg.OutputSchema != nil { | |
| 572 | - opts = append(opts, ai.WithOutputSchema(config.Cfg.OutputSchema)) | |
| 573 | - } | |
| 574 | 256 | |
| 575 | - // The prefix is printed by the first token rather than up front, so the | |
| 576 | - // spinner has a line to itself and vanishes without taking anything with it. | |
| 577 | - printed := false | |
| 578 | - emit := func(text string) { | |
| 579 | - // An event-consuming front end (ACP) takes the chunk raw: the editor | |
| 580 | - // renders Markdown and owns the layout, so the gap/squeeze machinery — | |
| 581 | - // which fights the terminal screen, not the text — stays out of the | |
| 582 | - // way. `printed` is still maintained: the no-streaming retry below must | |
| 583 | - // know whether the client already saw part of an answer. | |
| 584 | - if s := ui.ActiveSink(); s != nil { | |
| 585 | - if text == "" { | |
| 586 | - return | |
| 587 | - } | |
| 588 | - think.done() | |
| 589 | - printed = true | |
| 590 | - s.Text(text) | |
| 591 | - return | |
| 592 | - } | |
| 593 | - // The answer has started: the thinking that led to it is over. | |
| 594 | - think.done() | |
| 595 | - // Trailing whitespace is held back, not printed: see the gap type. | |
| 596 | - out := gaps.next(text) | |
| 597 | - if out == "" { | |
| 598 | - return | |
| 599 | - } | |
| 600 | - // Stop BEFORE every print, not only the first one. | |
| 601 | - // | |
| 602 | - // A question can take several turns, and the tool restarts the spinner | |
| 603 | - // on its way back to the model. The text of the next turn then landed on | |
| 604 | - // the spinner's line, which erased it on the following frame | |
| 605 | - // (`\r\033[2K`): "Hello 👋 to Sam" became "⠦ Thinking… 0s 👋 to Sam". | |
| 606 | - // Worse, the last sentence of an answer vanished entirely, erased by the | |
| 607 | - // final Stop(). | |
| 608 | - // | |
| 609 | - // Stop() is idempotent and returns immediately when nothing is running, | |
| 610 | - // so calling it on every chunk costs nothing. | |
| 611 | - spinner.Stop() | |
| 612 | - if !printed { | |
| 613 | - fmt.Print("🤖 ") | |
| 614 | - printed = true | |
| 615 | - } | |
| 616 | - fmt.Print(out) | |
| 617 | - } | |
| 257 | + t := newTurn(e, messages) | |
| 258 | + defer t.finishSpeed() | |
| 259 | + opts := t.options(tools) | |
| 618 | 260 | |
| 619 | - // --- Watchdog --- | |
| 620 | - // A sub-context the watchdog cancels when the server has been silent too | |
| 621 | - // long: firstTokenTimeout while a model call reads its prompt, | |
| 622 | - // WatchdogTimeout between tokens (progress.go). The streaming callback | |
| 623 | - // beats it on every chunk. | |
| 624 | - genCtx, p, cancelGen := watchdog(ctx, config.Cfg.WatchdogTimeout, | |
| 625 | - firstTokenTimeout(config.Cfg.WatchdogTimeout, config.Cfg.FirstTokenTimeout)) | |
| 261 | + genCtx, cancelGen := t.watch(ctx) | |
| 626 | 262 | defer cancelGen() |
| 627 | - pl = p | |
| 628 | - beat := pl.beat | |
| 629 | - genCtx = withHeartbeat(genCtx, beat) | |
| 630 | - | |
| 631 | - // A thinking model streams its reasoning in a field Genkit drops, so the | |
| 632 | - // streaming callback below never runs while it thinks (reasoning.go). The | |
| 633 | - // beat matters more than the display here: without it the watchdog kills | |
| 634 | - // a turn that is going perfectly well, and a model can reason for a long | |
| 635 | - // time before its first word — 38s measured. The display is a setting; | |
| 636 | - // the heartbeat never is. | |
| 637 | - genCtx = WithReasoning(genCtx, func(text string) { | |
| 638 | - beat() | |
| 639 | - loops.feed(text) | |
| 640 | - if config.Cfg.ShowThinking { | |
| 641 | - think.emit(text) | |
| 642 | - } | |
| 643 | - }) | |
| 644 | - // The error events a server streams, for the model calls to report | |
| 645 | - // (servererr.go; read back in WrapModel through the context). | |
| 646 | - genCtx, _ = withServerErrors(genCtx) | |
| 647 | - // While the server reads the prompt it says how far it got: proof of life | |
| 648 | - // for the watchdog, and something to show instead of "Thinking". | |
| 649 | - genCtx = withSpeed(genCtx, speed) | |
| 650 | - genCtx = withPromptProgress(genCtx, func(pp promptProgress) { | |
| 651 | - pl.alive() | |
| 652 | - if pl.waiting.Load() { | |
| 653 | - spinner.Start(progressLabel(pp)) | |
| 654 | - } | |
| 655 | - }) | |
| 656 | 263 | |
| 657 | 264 | spinner.Start("Thinking") |
| 658 | 265 | defer spinner.Stop() |
| @@ -661,35 +268,11 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | ||
| 661 | 268 | // a derailed model repeating itself for minutes is stopped at once, and |
| 662 | 269 | // the spinner says a tool call is being composed rather than nothing. |
| 663 | 270 | guard := &toolCallGuard{} |
| 664 | - resp, err := genkit.Generate(genCtx, e.G, append(opts, | |
| 665 | - ai.WithStreaming(func(_ context.Context, chunk *ai.ModelResponseChunk) error { | |
| 666 | - beat() | |
| 667 | - wasComposing := guard.composing | |
| 668 | - if err := guard.observe(chunk); err != nil { | |
| 669 | - return err | |
| 670 | - } | |
| 671 | - if guard.composing && !wasComposing { | |
| 672 | - spinner.Start("Composing a tool call") | |
| 673 | - } | |
| 674 | - // Since Genkit 1.13 a chunk may carry nothing but reasoning. The | |
| 675 | - // tap has already shown it (reasoning.go); handed to emit, its | |
| 676 | - // empty text would close the thought block after every token. | |
| 677 | - if onlyReasoning(chunk) { | |
| 678 | - return nil | |
| 679 | - } | |
| 680 | - loops.feed(chunk.Text()) | |
| 681 | - emit(chunk.Text()) | |
| 682 | - return nil | |
| 683 | - }), | |
| 684 | - )...) | |
| 271 | + resp, err := genkit.Generate(genCtx, e.G, append(opts, ai.WithStreaming(t.onChunk(guard)))...) | |
| 685 | 272 | if guard.reason != "" { |
| 686 | - return nil, guard.keep(full, resp), runawayError(guard.reason) | |
| 273 | + return nil, guard.keep(t.full, resp), runawayError(guard.reason) | |
| 687 | 274 | } |
| 688 | 275 | |
| 689 | - // `full` grows as soon as a tool turn has happened: it is the witness that | |
| 690 | - // says whether commands ran, and it is used twice below. | |
| 691 | - toolsRan := len(full) > len(messages) | |
| 692 | - | |
| 693 | 276 | // The watchdog cut `genCtx` while the PARENT context is intact: this is a |
| 694 | 277 | // silence of the connection, not a cancellation by the user. |
| 695 | 278 | // |
| @@ -699,343 +282,26 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | ||
| 699 | 282 | // that is, it called the MUTE engine again. Measured: 5 s of watchdog then |
| 700 | 283 | // 20 s of "Retrying without streaming…" against a silent server, and the |
| 701 | 284 | // "stalled" message never shown. |
| 702 | - stalled := genCtx.Err() != nil && ctx.Err() == nil | |
| 703 | - if err != nil && stalled { | |
| 285 | + if err != nil && genCtx.Err() != nil && ctx.Err() == nil { | |
| 704 | 286 | // We return `full` despite the failure: if commands ran before the |
| 705 | 287 | // silence, their work must not be lost. |
| 706 | - return nil, full, errStalled | |
| 288 | + return nil, t.full, errStalled | |
| 707 | 289 | } |
| 708 | 290 | |
| 709 | - // The retry is only worth it for an SSE stream cut before the first byte. | |
| 710 | - // Any other error (maxTurns exceeded, a failing tool, invalid arguments) | |
| 711 | - // happens AFTER commands have run, and replaying the turn would replay them: | |
| 712 | - // measured, an `echo >>` wrote itself twice. `full` grows as soon as a tool | |
| 713 | - // turn has happened, which is enough to tell the two apart. | |
| 714 | - // The loop detector's stop is never retried either: replaying the turn | |
| 715 | - // would run the repeated tool once more before stopping again. | |
| 716 | - // Nor is a tool call whose arguments did not parse: the hook above has | |
| 717 | - // already handed it back, and the same limit would cut the same call. | |
| 718 | - // Nor a request larger than the server's window (ticket 233): it fails | |
| 719 | - // the same way without streaming. | |
| 720 | - _, stuck := stuckTurn(err) | |
| 721 | - truncated, malformed := argsError(err) | |
| 722 | - _, isLoop := looped(err) // ticket 235: the same model would loop again | |
| 723 | - if err != nil && !printed && !toolsRan && !stuck && !truncated && !malformed && !contextOverflow(err) && !isLoop { | |
| 291 | + if t.retryableWithoutStreaming(err) { | |
| 724 | 292 | spinner.Start("Retrying without streaming") |
| 725 | 293 | if resp, err = genkit.Generate(ctx, e.G, opts...); err == nil { |
| 726 | - emit(resp.Text()) | |
| 294 | + t.emit(resp.Text()) | |
| 727 | 295 | } |
| 728 | 296 | } |
| 729 | 297 | |
| 730 | - think.done() | |
| 298 | + t.think.done() | |
| 731 | 299 | err = cutStructuredAnswer(resp, err) |
| 732 | 300 | |
| 733 | 301 | // `full` stops at the last call to the model; its answer is appended after. |
| 302 | + full := t.full | |
| 734 | 303 | if resp != nil && resp.Message != nil { |
| 735 | 304 | full = append(full, resp.Message) |
| 736 | 305 | } |
| 737 | 306 | return resp, full, err |
| 738 | 307 | } |
| 739 | - | |
| 740 | -// Summarize asks the model for a plain-text answer to `messages` — no tools, | |
| 741 | -// no screen output. It exists for the context compression (internal/compact): | |
| 742 | -// the summary must not stream onto the screen as if it were an answer, and a | |
| 743 | -// request that offers tools invites the model to call them instead of writing. | |
| 744 | -// It goes through the same Genkit and the same model reference as Generate, | |
| 745 | -// so it lands on the same provider and the same server. | |
| 746 | -// | |
| 747 | -// The watchdog is kept, with twice the usual patience: this is the longest | |
| 748 | -// prefill of the session (the whole old history at once) and nothing streams | |
| 749 | -// until it is done. Streaming stays on so that the summary's own tokens beat | |
| 750 | -// the watchdog while it is being written. | |
| 751 | -// | |
| 752 | -// A thinking model is asked not to reason (withoutThinking, llama.cpp | |
| 753 | -// providers and Ollama), over what the sampling config says: its reasoning counts against maxTokens and is not in | |
| 754 | -// resp.Text(), so it can spend the whole budget and leave no summary. On the | |
| 755 | -// other providers that can still happen; emptySummary then says so. | |
| 756 | -func (e *Engine) Summarize(ctx context.Context, messages []*ai.Message, maxTokens int) (string, error) { | |
| 757 | - // The agent's sampling, minus what does not apply here: `parallel_tool_calls` | |
| 758 | - // without tools is a 400 on the OpenAI API, and the answer limit is the | |
| 759 | - // summary's budget, not the answer's — under the name the config uses | |
| 760 | - // (max_completion_tokens for the OpenAI models that refuse max_tokens). | |
| 761 | - sampling := maps.Clone(config.Cfg.Sampling) | |
| 762 | - if sampling == nil { | |
| 763 | - sampling = map[string]any{} | |
| 764 | - } | |
| 765 | - delete(sampling, "parallel_tool_calls") | |
| 766 | - sampling[limitKey(sampling)] = maxTokens | |
| 767 | - | |
| 768 | - genCtx, pl, cancel := watchdog(ctx, 2*config.Cfg.WatchdogTimeout, | |
| 769 | - firstTokenTimeout(2*config.Cfg.WatchdogTimeout, config.Cfg.FirstTokenTimeout)) | |
| 770 | - defer cancel() | |
| 771 | - beat := pl.beat | |
| 772 | - // The same heartbeat, and deliberately no display: a summary is written | |
| 773 | - // behind the user's back, and a model that thinks about it must not spill | |
| 774 | - // that onto the screen in the middle of their conversation. The length is | |
| 775 | - // kept for emptySummary. | |
| 776 | - var reasoned atomic.Int64 | |
| 777 | - genCtx = WithReasoning(genCtx, func(s string) { reasoned.Add(int64(len(s))); beat() }) | |
| 778 | - genCtx = withoutThinking(genCtx) | |
| 779 | - genCtx, srvErrs := withServerErrors(genCtx) | |
| 780 | - genCtx = withPromptProgress(genCtx, func(promptProgress) { pl.alive() }) | |
| 781 | - | |
| 782 | - resp, err := genkit.Generate(genCtx, e.G, | |
| 783 | - ai.WithModelName(e.Model), | |
| 784 | - ai.WithMessages(messages...), | |
| 785 | - ai.WithConfig(sampling), | |
| 786 | - ai.WithStreaming(func(_ context.Context, _ *ai.ModelResponseChunk) error { | |
| 787 | - beat() | |
| 788 | - return nil | |
| 789 | - }), | |
| 790 | - ) | |
| 791 | - if err != nil { | |
| 792 | - // Same test as in Generate: the contexts, not the wrapped error. | |
| 793 | - if genCtx.Err() != nil && ctx.Err() == nil { | |
| 794 | - return "", fmt.Errorf("summary timed out (stalled)") | |
| 795 | - } | |
| 796 | - if msg := srvErrs.take(); msg != "" { | |
| 797 | - return "", &serverError{msg: msg, err: err} | |
| 798 | - } | |
| 799 | - return "", err | |
| 800 | - } | |
| 801 | - text := strings.TrimSpace(resp.Text()) | |
| 802 | - if text == "" { | |
| 803 | - return "", emptySummary(resp, maxTokens, int(reasoned.Load())) | |
| 804 | - } | |
| 805 | - return text, nil | |
| 806 | -} | |
| 807 | - | |
| 808 | -// emptySummary is the error of a summary request that came back without | |
| 809 | -// text, with what the response says about why: the line lands in the session | |
| 810 | -// file's `errors`, and "empty summary" alone sent an investigation to replay | |
| 811 | -// an 18k-token request. The usual cause is a thinking model that reasoned | |
| 812 | -// until max_tokens; the line then names the setting to raise. | |
| 813 | -func emptySummary(resp *ai.ModelResponse, maxTokens, reasoned int) error { | |
| 814 | - out := 0 | |
| 815 | - if resp.Usage != nil { | |
| 816 | - out = resp.Usage.OutputTokens | |
| 817 | - } | |
| 818 | - why := fmt.Sprintf("finish: %s, %d output token(s), %d char(s) of reasoning", resp.FinishReason, out, reasoned) | |
| 819 | - if resp.FinishReason == ai.FinishReasonLength && reasoned > 0 { | |
| 820 | - return fmt.Errorf("the model returned an empty summary: it reasoned until the %d-token limit (%s) — raise context.summaryMaxTokens", maxTokens, why) | |
| 821 | - } | |
| 822 | - return fmt.Errorf("the model returned an empty summary (%s)", why) | |
| 823 | -} | |
| 824 | - | |
| 825 | -// Names of the tools whose responses we count. They live here rather than | |
| 826 | -// scattered through the display code: the counter is a measurement, and a | |
| 827 | -// measurement needs a single definition. | |
| 828 | -const ( | |
| 829 | - toolBash = "bash" | |
| 830 | - toolSkill = "read_skill" | |
| 831 | - toolRead = "read_file" | |
| 832 | - toolWrite = "write_file" | |
| 833 | - toolEdit = "edit_file" | |
| 834 | - toolLSP = "lsp" | |
| 835 | -) | |
| 836 | - | |
| 837 | -// executed returns, in order, the text of the calls to a given tool that | |
| 838 | -// ACTUALLY ran. | |
| 839 | -// | |
| 840 | -// We start from the RESPONSES: a call the model asked for but which never ran | |
| 841 | -// (interrupted turn, maxTurns exceeded) produces none. The text of the call, on | |
| 842 | -// the other hand, is ONLY in the request — hence the pairing by Ref, the | |
| 843 | -// identifier the server gives to each call. | |
| 844 | -func executed(history []*ai.Message, name string) []string { | |
| 845 | - // Calls with no Ref (some servers do not set one) are paired in order, BUT | |
| 846 | - // only against the same tool name: a turn mixes `bash` and `read_skill`, and | |
| 847 | - // the first pending call is not necessarily for the right tool. | |
| 848 | - type call struct{ ref, name, text string } | |
| 849 | - var pending []call | |
| 850 | - var out []string | |
| 851 | - | |
| 852 | - for _, m := range history { | |
| 853 | - for _, p := range m.Content { | |
| 854 | - switch { | |
| 855 | - case p.IsToolRequest(): | |
| 856 | - pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name, commandText(p.ToolRequest)}) | |
| 857 | - | |
| 858 | - case p.IsToolResponse() && p.ToolResponse != nil && p.ToolResponse.Name == name: | |
| 859 | - ref := p.ToolResponse.Ref | |
| 860 | - i := slices.IndexFunc(pending, func(c call) bool { | |
| 861 | - if ref != "" { | |
| 862 | - return c.ref == ref | |
| 863 | - } | |
| 864 | - return c.name == name | |
| 865 | - }) | |
| 866 | - if i < 0 { // lost call: the name beats nothing | |
| 867 | - out = append(out, name) | |
| 868 | - continue | |
| 869 | - } | |
| 870 | - out = append(out, pending[i].text) | |
| 871 | - pending = slices.Delete(pending, i, i+1) | |
| 872 | - } | |
| 873 | - } | |
| 874 | - } | |
| 875 | - return out | |
| 876 | -} | |
| 877 | - | |
| 878 | -// commandText describes a tool call in one line. For `bash` it is the command | |
| 879 | -// itself — the rest is only wrapping; for any other tool, its name followed by | |
| 880 | -// its arguments. | |
| 881 | -func commandText(r *ai.ToolRequest) string { | |
| 882 | - if in, ok := r.Input.(map[string]any); ok { | |
| 883 | - if c, ok := in["command"].(string); ok && strings.TrimSpace(c) != "" { | |
| 884 | - return strings.TrimSpace(c) | |
| 885 | - } | |
| 886 | - } | |
| 887 | - args, err := json.Marshal(r.Input) | |
| 888 | - if err != nil || string(args) == "null" { | |
| 889 | - return r.Name | |
| 890 | - } | |
| 891 | - return r.Name + " " + string(args) | |
| 892 | -} | |
| 893 | - | |
| 894 | -// responses counts the responses of a given tool in a history. | |
| 895 | -func responses(history []*ai.Message, name string) int { | |
| 896 | - return len(executed(history, name)) | |
| 897 | -} | |
| 898 | - | |
| 899 | -// Commands counts the commands actually run in a history — one per response of | |
| 900 | -// the `bash` tool. It is the only reliable measure of the work done: a model | |
| 901 | -// that tells stories without acting produces a fine answer and a count of zero. | |
| 902 | -// | |
| 903 | -// The other tools do NOT count. Loading a skill runs nothing, and counting those | |
| 904 | -// reads would make the number say the opposite of what it is for: measured | |
| 905 | -// before the fix, a turn with two reads and a single command displayed | |
| 906 | -// "⚙ 3 command(s)". | |
| 907 | -func Commands(history []*ai.Message) int { | |
| 908 | - return responses(history, toolBash) | |
| 909 | -} | |
| 910 | - | |
| 911 | -// CommandList returns, in order, the text of the commands Commands counts — the | |
| 912 | -// one shown in the recap under the count when `displayCommands` is on. The count | |
| 913 | -// says HOW MANY, the list says WHAT. | |
| 914 | -func CommandList(history []*ai.Message) []string { | |
| 915 | - return executed(history, toolBash) | |
| 916 | -} | |
| 917 | - | |
| 918 | -// FileOps returns, in order, the file-tool calls that ran — read_file, | |
| 919 | -// write_file, edit_file — as one line each ("edit_file hello/main.go (2 edits)"). | |
| 920 | -// | |
| 921 | -// They are counted APART from the commands, not folded into them: this part | |
| 922 | -// compares editing through the `edit` CLI (one bash command per edit) with | |
| 923 | -// editing through built-in tools, and a recap that counted both as "commands" | |
| 924 | -// would hide the very difference being measured. `⚙ 3 command(s) · 📝 2 file | |
| 925 | -// op(s)` keeps the two columns readable side by side. | |
| 926 | -func FileOps(history []*ai.Message) []string { | |
| 927 | - return executedAny(history, toolRead, toolWrite, toolEdit) | |
| 928 | -} | |
| 929 | - | |
| 930 | -// executedAny is executed() across several tool names, keeping the order in | |
| 931 | -// which the responses appear — a per-name pass would lose the interleaving of | |
| 932 | -// a read followed by an edit. | |
| 933 | -func executedAny(history []*ai.Message, names ...string) []string { | |
| 934 | - type call struct{ ref, name, text string } | |
| 935 | - var pending []call | |
| 936 | - var out []string | |
| 937 | - isOurs := func(n string) bool { return slices.Contains(names, n) } | |
| 938 | - | |
| 939 | - for _, m := range history { | |
| 940 | - for _, p := range m.Content { | |
| 941 | - switch { | |
| 942 | - case p.IsToolRequest(): | |
| 943 | - pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name, fileOpText(p.ToolRequest)}) | |
| 944 | - case p.IsToolResponse() && p.ToolResponse != nil && isOurs(p.ToolResponse.Name): | |
| 945 | - ref, name := p.ToolResponse.Ref, p.ToolResponse.Name | |
| 946 | - i := slices.IndexFunc(pending, func(c call) bool { | |
| 947 | - if ref != "" { | |
| 948 | - return c.ref == ref | |
| 949 | - } | |
| 950 | - return c.name == name | |
| 951 | - }) | |
| 952 | - if i < 0 { | |
| 953 | - out = append(out, name) | |
| 954 | - continue | |
| 955 | - } | |
| 956 | - out = append(out, pending[i].text) | |
| 957 | - pending = slices.Delete(pending, i, i+1) | |
| 958 | - } | |
| 959 | - } | |
| 960 | - } | |
| 961 | - return out | |
| 962 | -} | |
| 963 | - | |
| 964 | -// fileOpText describes a file-tool call in one line: the tool, the path, and | |
| 965 | -// for edit_file the number of edits — never the texts themselves, which can | |
| 966 | -// run to dozens of lines and belong in the diff, not in the recap. | |
| 967 | -func fileOpText(r *ai.ToolRequest) string { | |
| 968 | - in, _ := r.Input.(map[string]any) | |
| 969 | - path, _ := in["path"].(string) | |
| 970 | - switch r.Name { | |
| 971 | - case toolEdit: | |
| 972 | - if edits, ok := in["edits"].([]any); ok { | |
| 973 | - return fmt.Sprintf("%s %s (%d edit(s))", r.Name, path, len(edits)) | |
| 974 | - } | |
| 975 | - case toolRead: | |
| 976 | - if s, ok := in["start"].(float64); ok && s > 0 { | |
| 977 | - e, _ := in["end"].(float64) | |
| 978 | - return fmt.Sprintf("%s %s %d-%d", r.Name, path, int(s), int(e)) | |
| 979 | - } | |
| 980 | - } | |
| 981 | - if path == "" { | |
| 982 | - return commandText(r) | |
| 983 | - } | |
| 984 | - return r.Name + " " + path | |
| 985 | -} | |
| 986 | - | |
| 987 | -// Skills counts the skills loaded — one per response of `read_skill`. Shown | |
| 988 | -// next to the command count: seeing which procedure the agent chose to follow is | |
| 989 | -// half the point of this part. | |
| 990 | -func Skills(history []*ai.Message) int { | |
| 991 | - n := 0 | |
| 992 | - for _, m := range history { | |
| 993 | - for _, p := range m.Content { | |
| 994 | - if !p.IsToolResponse() || p.ToolResponse == nil || p.ToolResponse.Name != toolSkill { | |
| 995 | - continue | |
| 996 | - } | |
| 997 | - if !strings.HasPrefix(strings.TrimSpace(responseText(p.ToolResponse)), skillMiss) { | |
| 998 | - n++ | |
| 999 | - } | |
| 1000 | - } | |
| 1001 | - } | |
| 1002 | - return n | |
| 1003 | -} | |
| 1004 | - | |
| 1005 | -// skillMiss is how `read_skill` answers a name that is not in the catalogue. | |
| 1006 | -// Counting those as skills made the number say the opposite of what it is | |
| 1007 | -// for: `📖 2 skill(s)` could mean two failed lookups and nothing loaded. | |
| 1008 | -const skillMiss = "[skill:" | |
| 1009 | - | |
| 1010 | -// responseText is a tool response as text. Every tool here returns a string; | |
| 1011 | -// anything else is formatted rather than dropped, so a change of shape shows | |
| 1012 | -// up as an odd count instead of a silent zero. | |
| 1013 | -func responseText(r *ai.ToolResponse) string { | |
| 1014 | - if s, ok := r.Output.(string); ok { | |
| 1015 | - return s | |
| 1016 | - } | |
| 1017 | - return fmt.Sprintf("%v", r.Output) | |
| 1018 | -} | |
| 1019 | - | |
| 1020 | -// skillsDeclared says this agent has a skills catalogue at all. Set once by | |
| 1021 | -// main, read by the three turn recaps. | |
| 1022 | -// | |
| 1023 | -// Why it exists: `📖 N skill(s)` used to be printed only when N > 0, so | |
| 1024 | -// "no skill applied" and "a skill applied and the model ignored it" looked | |
| 1025 | -// identical — nothing at all. Showing `📖 0 skill(s)` is the whole point; | |
| 1026 | -// showing it in a project that has no skills would be noise. | |
| 1027 | -var skillsDeclared atomic.Bool | |
| 1028 | - | |
| 1029 | -// DeclareSkills records whether the agent was given any skill. | |
| 1030 | -func DeclareSkills(yes bool) { skillsDeclared.Store(yes) } | |
| 1031 | - | |
| 1032 | -// SkillsAvailable reports it, for the turn recaps. | |
| 1033 | -func SkillsAvailable() bool { return skillsDeclared.Load() } | |
| 1034 | - | |
| 1035 | -// LSPCalls counts the `lsp` tool responses in a history — questions put to a | |
| 1036 | -// language server (definition, references, hover, symbols, diagnostics, | |
| 1037 | -// rename). Shown apart from the commands for the same reason as the file | |
| 1038 | -// ops: asking the compiler is not running a command. | |
| 1039 | -func LSPCalls(history []*ai.Message) int { | |
| 1040 | - return responses(history, toolLSP) | |
| 1041 | -} | |
| @@ -11,11 +11,7 @@ package engine | |||
| 11 | 11 | ||
| 12 | import ( | 12 | import ( |
| 13 | "context" | 13 | "context" |
| 14 | - "encoding/json" | ||
| 15 | - "fmt" | ||
| 16 | - "maps" | ||
| 17 | "slices" | 14 | "slices" |
| 18 | - "strings" | ||
| 19 | "sync" | 15 | "sync" |
| 20 | "sync/atomic" | 16 | "sync/atomic" |
| 21 | 17 | ||
| @@ -138,112 +134,39 @@ func (e *Engine) ForgetInputTokens() { e.lastInput.Store(0) } | |||
| 138 | // Explain turns a transport error into the one-line, actionable message the | 134 | // Explain turns a transport error into the one-line, actionable message the |
| 139 | // REPL prints between brackets. See Provider.Explain for the rationale. | 135 | // REPL prints between brackets. See Provider.Explain for the rationale. |
| 140 | func (e *Engine) Explain(err error) string { | 136 | func (e *Engine) Explain(err error) string { |
| 141 | - // The loop detector ended the turn: its own sentence is the whole | 137 | + for _, explain := range turnExplainers { |
| 142 | - // diagnosis, whatever the provider. | 138 | + if line, ok := explain(err); ok { |
| 143 | - if sentence, ok := stuckTurn(err); ok { | 139 | + return line |
| 144 | - return sentence | 140 | + } |
| 145 | - } | ||
| 146 | - // A tool call with broken arguments: the raw error quotes them whole — | ||
| 147 | - // a truncated document, on the day it was seen — so it gets a line of | ||
| 148 | - // its own (toolargs.go). | ||
| 149 | - if line, ok := badToolArgs(err); ok { | ||
| 150 | - return line | ||
| 151 | - } | ||
| 152 | - // The model looped again after the note (textloop.go, ticket 235): its | ||
| 153 | - // own sentence says what it repeated. | ||
| 154 | - if le, ok := looped(err); ok { | ||
| 155 | - return le.Error() | ||
| 156 | - } | ||
| 157 | - // The request outgrew the server's window (ctxsize.go, ticket 233): said | ||
| 158 | - // with the sizes, before the generic "stream broke" line would blame | ||
| 159 | - // the connection. | ||
| 160 | - if line, ok := overflowLine(err); ok { | ||
| 161 | - return line | ||
| 162 | - } | ||
| 163 | - // A stream the server broke, even after the retry: the server's own | ||
| 164 | - // words when it streamed some (servererr.go), never "unexpected end of | ||
| 165 | - // JSON input" alone. | ||
| 166 | - if line, ok := badStream(err); ok { | ||
| 167 | - return line | ||
| 168 | } | 141 | } |
| 169 | return e.Provider.Explain(err, e.Backend) | 142 | return e.Provider.Explain(err, e.Backend) |
| 170 | } | 143 | } |
| 171 | 144 | ||
| 172 | -// blanks is the set of characters the model adds around its text without any of | 145 | +// turnExplainers know the failures of a turn that are mm's own, whatever the |
| 173 | -// it showing on screen. | 146 | +// provider; the first one that knows the error says it: |
| 174 | -const blanks = " \t\r\n" | ||
| 175 | - | ||
| 176 | -// gap holds back the TRAILING whitespace of the streamed text: it is only | ||
| 177 | -// printed if visible text follows. Without that, the line breaks the model puts | ||
| 178 | -// after its sentence are printed as-is, and the screen hollows out. | ||
| 179 | // | 147 | // |
| 180 | -// The model produces MORE AND MORE of it as the turns go by — it imitates its | 148 | +// - the loop detector ended the turn: its own sentence is the whole |
| 181 | -// own messages, which it re-reads in the history every turn. Measured: 2 blank | 149 | +// diagnosis; |
| 182 | -// lines before the first 🛠️, 4 before the second, 7, then 11. Holding the | 150 | +// - a tool call with broken arguments: the raw error quotes them whole — a |
| 183 | -// whitespace back is enough to remove all of it, since that whitespace is never | 151 | +// truncated document, on the day it was seen — so it gets a line of its |
| 184 | -// followed by text: it is a tool that writes next. | 152 | +// own (toolargs.go); |
| 185 | -type gap struct { | 153 | +// - the model looped again after the note (textloop.go, ticket 235): its |
| 186 | - // The `bash` tool may call drop() from SEVERAL goroutines — Genkit runs the | 154 | +// own sentence says what it repeated; |
| 187 | - // calls of a single turn in parallel (see printMu in tools). | 155 | +// - the request outgrew the server's window (ctxsize.go, ticket 233): said |
| 188 | - mu sync.Mutex | 156 | +// with the sizes, before the generic "stream broke" line would blame the |
| 189 | - held string // whitespace waiting to be followed by text | 157 | +// connection; |
| 190 | - started bool // visible text has already been printed | 158 | +// - a stream the server broke, even after the retry: the server's own words |
| 191 | -} | 159 | +// when it streamed some (servererr.go), never "unexpected end of JSON |
| 192 | - | 160 | +// input" alone. |
| 193 | -// next returns what should be printed for this chunk, "" when there is nothing | 161 | +var turnExplainers = []func(error) (string, bool){stuckTurn, badToolArgs, loopedLine, overflowLine, badStream} |
| 194 | -// to print right now. | 162 | + |
| 195 | -func (g *gap) next(text string) string { | 163 | +// loopedLine is looped's sentence. |
| 196 | - g.mu.Lock() | 164 | +func loopedLine(err error) (string, bool) { |
| 197 | - defer g.mu.Unlock() | 165 | + le, ok := looped(err) |
| 198 | - | 166 | + if !ok { |
| 199 | - body := strings.TrimRight(text, blanks) | 167 | + return "", false |
| 200 | - if body == "" { // an all-whitespace chunk: set aside, not printed | 168 | + } |
| 201 | - if g.started { | 169 | + return le.Error(), true |
| 202 | - g.held += text | ||
| 203 | - } | ||
| 204 | - return "" | ||
| 205 | - } | ||
| 206 | - | ||
| 207 | - // The chunk splits in three: leading whitespace, text, trailing whitespace. | ||
| 208 | - tail := text[len(body):] | ||
| 209 | - visible := strings.TrimLeft(body, blanks) | ||
| 210 | - lead := body[:len(body)-len(visible)] | ||
| 211 | - | ||
| 212 | - out := "" | ||
| 213 | - if g.started { // before the first word, all whitespace is dropped | ||
| 214 | - out = squeeze(g.held + lead) | ||
| 215 | - } | ||
| 216 | - g.held, g.started = tail, true | ||
| 217 | - return out + visible | ||
| 218 | -} | ||
| 219 | - | ||
| 220 | -// drop forgets the pending whitespace. Called when someone ELSE is about to | ||
| 221 | -// write — a tool announcing its command: that whitespace belonged to the text | ||
| 222 | -// before it, and printing it now would reopen the hole we just closed. | ||
| 223 | -func (g *gap) drop() { | ||
| 224 | - g.mu.Lock() | ||
| 225 | - g.held = "" | ||
| 226 | - g.mu.Unlock() | ||
| 227 | -} | ||
| 228 | - | ||
| 229 | -// squeeze brings any run of line breaks down to two, that is ONE blank line at | ||
| 230 | -// most. Spaces are left alone: they carry the indentation of a code block, and | ||
| 231 | -// cutting it would shift the displayed code. | ||
| 232 | -func squeeze(s string) string { | ||
| 233 | - var b strings.Builder | ||
| 234 | - run := 0 | ||
| 235 | - for _, r := range s { | ||
| 236 | - if r == '\n' { | ||
| 237 | - run++ | ||
| 238 | - if run > 2 { | ||
| 239 | - continue | ||
| 240 | - } | ||
| 241 | - } else { | ||
| 242 | - run = 0 | ||
| 243 | - } | ||
| 244 | - b.WriteRune(r) | ||
| 245 | - } | ||
| 246 | - return b.String() | ||
| 247 | } | 170 | } |
| 248 | 171 | ||
| 249 | // Generate queries the model, printing the answer as it comes (streaming). Some | 172 | // Generate queries the model, printing the answer as it comes (streaming). Some |
| @@ -316,7 +239,8 @@ func runTurnEnd() { | |||
| 316 | } | 239 | } |
| 317 | 240 | ||
| 318 | // generate is Generate without the generation hooks (hooks.go): the turn | 241 | // generate is Generate without the generation hooks (hooks.go): the turn |
| 319 | -// itself. The tool hooks run inside it, in the WrapTool middleware. | 242 | +// itself. The tool hooks run inside it, in the WrapTool middleware. The |
| 243 | +// turn's state and its steps live in turn.go. | ||
| 320 | func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []ai.ToolRef) (*ai.ModelResponse, []*ai.Message, error) { | 244 | func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []ai.ToolRef) (*ai.ModelResponse, []*ai.Message, error) { |
| 321 | // Tool routing (ticket 127) runs here, after the preGeneration hooks: a | 245 | // Tool routing (ticket 127) runs here, after the preGeneration hooks: a |
| 322 | // question a hook stopped never reaches the decider, and the one routed | 246 | // question a hook stopped never reaches the decider, and the one routed |
| @@ -329,330 +253,13 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | |||
| 329 | // neither reads it as part of the question. | 253 | // neither reads it as part of the question. |
| 330 | messages = withReminder(messages, config.Cfg.TurnReminder) | 254 | messages = withReminder(messages, config.Cfg.TurnReminder) |
| 331 | ctx = WithConversation(ctx, messages) | 255 | ctx = WithConversation(ctx, messages) |
| 332 | - // Genkit only hands us back the LAST message. The intermediate turns — "I | ||
| 333 | - // am calling bash", "here is the output" — exist only in the request it | ||
| 334 | - // builds for the next turn. This middleware captures that request on its way | ||
| 335 | - // through: the last turn seen therefore holds the whole conversation. | ||
| 336 | - // | ||
| 337 | - // The `WrapModel` hook wraps every call to the model — one per turn — so the | ||
| 338 | - // last request seen is the most complete one. `MiddlewareFunc` adapts a | ||
| 339 | - // closure to the `ai.Middleware` contract without going through a plugin: | ||
| 340 | - // `New` is called once per `Generate`, which keeps `full` captured at the | ||
| 341 | - // right level. | ||
| 342 | - var full []*ai.Message | ||
| 343 | - // speed measures the generation speed of each call and of the turn | ||
| 344 | - // (speed.go, ticket 254); nil with showSpeed off. | ||
| 345 | - speed := turnSpeedMeter() | ||
| 346 | - defer func() { | ||
| 347 | - if speed != nil { | ||
| 348 | - speed.finish() | ||
| 349 | - } | ||
| 350 | - }() | ||
| 351 | - // reply is the model's latest message — for a tool, the one that called | ||
| 352 | - // it (reply.go). | ||
| 353 | - var reply *ai.Message | ||
| 354 | - // pl is the watchdog's pulse, set below; every model call restarts the | ||
| 355 | - // wait for a first token (progress.go). | ||
| 356 | - var pl *pulse | ||
| 357 | - // argRetries counts the broken tool calls handed back to the model in | ||
| 358 | - // this generation (toolargs.go). | ||
| 359 | - argRetries := 0 | ||
| 360 | - // cutRetries counts the replies cut mid-reasoning handed back (ticket 232). | ||
| 361 | - cutRetries := 0 | ||
| 362 | - // loops watches each model call's stream for a sentence repeated over and | ||
| 363 | - // over (textloop.go, ticket 235); loopRetries counts the calls handed back. | ||
| 364 | - var loops loopWatch | ||
| 365 | - loopRetries := 0 | ||
| 366 | - // editRetries counts the answers handed back because the last file change | ||
| 367 | - // of the turn had failed (toolargs.go, ticket 242). | ||
| 368 | - editRetries := 0 | ||
| 369 | - var gaps gap | ||
| 370 | - // invalid counts the tool calls of this generation that failed the schema | ||
| 371 | - // (toolschema.go): the same invalid call repeated ends the turn. | ||
| 372 | - var invalid invalidCalls | ||
| 373 | - // think is the turn's thought block: see reasoning.go and thoughts below. | ||
| 374 | - // Declared here because emit, defined further down, closes over it. | ||
| 375 | - think := &thoughts{} | ||
| 376 | - capture := ai.MiddlewareFunc(func(context.Context) (*ai.Hooks, error) { | ||
| 377 | - return &ai.Hooks{ | ||
| 378 | - WrapModel: func(ctx context.Context, params *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) { | ||
| 379 | - // Same tools, same order, on every call: the server's prompt | ||
| 380 | - // cache depends on it (tooldefs.go, ticket 53). | ||
| 381 | - params.Request.Tools = stableTools(params.Request.Tools) | ||
| 382 | - // From the turn's second call on — tools have run — a history | ||
| 383 | - // past the threshold is made smaller first (inturn.go, ticket | ||
| 384 | - // 251). The wait counts as the call's: the summary is no beat. | ||
| 385 | - if config.Cfg.Context.CompressInTurn && len(params.Request.Messages) > len(messages) { | ||
| 386 | - pl.expect() | ||
| 387 | - e.compactInTurn(ctx, params) | ||
| 388 | - } | ||
| 389 | - // Messages the user sent during the turn (ticket 265, | ||
| 390 | - // steer.go) join the history after the tool results. | ||
| 391 | - params.Request.Messages = takeSteer(ctx, params.Request.Messages) | ||
| 392 | - full = slices.Clone(params.Request.Messages) | ||
| 393 | - // call runs ONE model call under its own context, which the | ||
| 394 | - // loop watch cancels when the stream repeats itself — the | ||
| 395 | - // call, not the generation. | ||
| 396 | - call := func(ctx context.Context) (*ai.ModelResponse, error) { | ||
| 397 | - callCtx, cancel := context.WithCancel(ctx) | ||
| 398 | - defer cancel() | ||
| 399 | - loops.arm(cancel) | ||
| 400 | - defer loops.disarm() | ||
| 401 | - return next(callCtx, params) | ||
| 402 | - } | ||
| 403 | - pl.expect() | ||
| 404 | - resp, err := call(ctx) | ||
| 405 | - err = withServerMessage(ctx, err) | ||
| 406 | - // A call cut because the model was repeating itself is handed | ||
| 407 | - // back once with a note; looping again ends the turn | ||
| 408 | - // (textloop.go, ticket 235). | ||
| 409 | - for ctx.Err() == nil { | ||
| 410 | - sample, times, cut := loops.take() | ||
| 411 | - if !cut { | ||
| 412 | - break | ||
| 413 | - } | ||
| 414 | - think.done() | ||
| 415 | - spinner.Stop() | ||
| 416 | - if loopRetries >= maxLoopRetries { | ||
| 417 | - return nil, loopError{sample: sample, times: times} | ||
| 418 | - } | ||
| 419 | - loopRetries++ | ||
| 420 | - _, _ = fmt.Fprintf(ui.Out, "\n[the model repeated %q %d times in a row — stopped it and asked for the answer, %d/%d]\n", | ||
| 421 | - shorten(sample, 60), times, loopRetries, maxLoopRetries) | ||
| 422 | - ui.ReportStruggle(ui.Struggle{Label: fmt.Sprintf("looped — handed back %d/%d", loopRetries, maxLoopRetries)}) | ||
| 423 | - params.Request.Messages = append(slices.Clone(params.Request.Messages), loopRetryNote(sample, times)) | ||
| 424 | - full = slices.Clone(params.Request.Messages) | ||
| 425 | - pl.expect() | ||
| 426 | - resp, err = call(ctx) | ||
| 427 | - err = withServerMessage(ctx, err) | ||
| 428 | - } | ||
| 429 | - // A stream the server broke — an error event, a cut | ||
| 430 | - // connection (servererr.go) — is retried ONCE, this model call | ||
| 431 | - // only. The turn-level retry below cannot help once a tool has | ||
| 432 | - // run (it would replay the tools); this one replays nothing but | ||
| 433 | - // the call that failed. Seen: a turn ended on "unexpected end | ||
| 434 | - // of JSON input" after twenty tool calls and a written file. | ||
| 435 | - // Text the broken attempt already streamed is not taken back. | ||
| 436 | - if streamBroken(err) && !contextOverflow(err) && ctx.Err() == nil { | ||
| 437 | - spinner.Stop() | ||
| 438 | - _, _ = fmt.Fprintf(ui.Out, "\n[%s — retrying this model call once]\n", streamNotice(err)) | ||
| 439 | - ui.ReportStruggle(ui.Struggle{Label: "stream cut — retried"}) | ||
| 440 | - pl.expect() | ||
| 441 | - resp, err = call(ctx) | ||
| 442 | - err = withServerMessage(ctx, err) | ||
| 443 | - } | ||
| 444 | - // A tool call whose arguments did not parse — cut off by | ||
| 445 | - // max_tokens, most of the time — is given back to the model | ||
| 446 | - // with a note instead of ending the turn. The note goes into | ||
| 447 | - // params.Request itself: Genkit builds the next turn's request | ||
| 448 | - // from that same value, so it stays in the conversation — the | ||
| 449 | - // model needs it again when it writes the second piece — and | ||
| 450 | - // `full` carries it into the history. | ||
| 451 | - for argRetries < maxArgRetries && ctx.Err() == nil { | ||
| 452 | - truncated, malformed := argsError(err) | ||
| 453 | - if !truncated && !malformed { | ||
| 454 | - break | ||
| 455 | - } | ||
| 456 | - argRetries++ | ||
| 457 | - what := "invalid JSON" | ||
| 458 | - if truncated { | ||
| 459 | - what = "cut off" | ||
| 460 | - } | ||
| 461 | - // ui.Out: stderr in ACP mode, never the JSON-RPC stream. | ||
| 462 | - spinner.Stop() | ||
| 463 | - _, _ = fmt.Fprintf(ui.Out, "\n[tool call arguments did not parse (%s: …%s) — handing it back to the model, %d/%d]\n", | ||
| 464 | - what, lastRunes(err.Error(), 60), argRetries, maxArgRetries) | ||
| 465 | - ui.ReportStruggle(ui.Struggle{Label: fmt.Sprintf("broken tool call (%s) %d/%d", what, argRetries, maxArgRetries)}) | ||
| 466 | - params.Request.Messages = append(slices.Clone(params.Request.Messages), argsRetryNote(truncated)) | ||
| 467 | - full = slices.Clone(params.Request.Messages) | ||
| 468 | - pl.expect() | ||
| 469 | - resp, err = call(ctx) | ||
| 470 | - err = withServerMessage(ctx, err) | ||
| 471 | - } | ||
| 472 | - // A reply cut by the answer limit while the model was still | ||
| 473 | - // reasoning — no text, no tool call — is handed back once with | ||
| 474 | - // a note (toolargs.go, ticket 232), the same way. | ||
| 475 | - for cutRetries < maxCutRetries && ctx.Err() == nil && reasoningCut(resp, err) { | ||
| 476 | - cutRetries++ | ||
| 477 | - spinner.Stop() | ||
| 478 | - _, _ = fmt.Fprintf(ui.Out, "\n[the model reasoned until the answer limit without answering — asking it to act now, %d/%d]\n", cutRetries, maxCutRetries) | ||
| 479 | - ui.ReportStruggle(ui.Struggle{Label: fmt.Sprintf("reasoning cut at the limit %d/%d", cutRetries, maxCutRetries)}) | ||
| 480 | - params.Request.Messages = append(slices.Clone(params.Request.Messages), cutRetryNote()) | ||
| 481 | - full = slices.Clone(params.Request.Messages) | ||
| 482 | - pl.expect() | ||
| 483 | - resp, err = call(ctx) | ||
| 484 | - err = withServerMessage(ctx, err) | ||
| 485 | - } | ||
| 486 | - // An ANSWER given while the turn's last file change failed is | ||
| 487 | - // handed back once (toolargs.go, ticket 242): the model can | ||
| 488 | - // still fix its call, or say it failed. The answer stays in the | ||
| 489 | - // conversation, so the note can refer to it. | ||
| 490 | - for editRetries < maxEditRetries && ctx.Err() == nil && err == nil && resp != nil && resp.Message != nil && len(resp.ToolRequests()) == 0 { | ||
| 491 | - turn := params.Request.Messages[min(len(messages), len(params.Request.Messages)):] | ||
| 492 | - tool, failure, failed := lastFailedFileChange(turn) | ||
| 493 | - if !failed { | ||
| 494 | - break | ||
| 495 | - } | ||
| 496 | - editRetries++ | ||
| 497 | - think.done() | ||
| 498 | - spinner.Stop() | ||
| 499 | - _, _ = fmt.Fprintf(ui.Out, "\n[the last %s failed — the file was not changed; asking the model to fix the call or say so, %d/%d]\n", tool, editRetries, maxEditRetries) | ||
| 500 | - ui.ReportStruggle(ui.Struggle{Label: fmt.Sprintf("answer after a failed %s — handed back %d/%d", tool, editRetries, maxEditRetries)}) | ||
| 501 | - params.Request.Messages = append(slices.Clone(params.Request.Messages), ai.NewModelTextMessage(resp.Text()), failedEditNote(tool, failure)) | ||
| 502 | - full = slices.Clone(params.Request.Messages) | ||
| 503 | - pl.expect() | ||
| 504 | - resp, err = call(ctx) | ||
| 505 | - err = withServerMessage(ctx, err) | ||
| 506 | - } | ||
| 507 | - // The server's own count of what it just read: the one exact | ||
| 508 | - // measure of the context size, kept for the compression | ||
| 509 | - // trigger. Zero means the server reported nothing. | ||
| 510 | - if resp != nil && resp.Usage != nil && resp.Usage.InputTokens > 0 { | ||
| 511 | - e.lastInput.Store(int64(resp.Usage.InputTokens)) | ||
| 512 | - } | ||
| 513 | - // An event-consuming front end (ACP) wants the counts of | ||
| 514 | - // every call, not just the last input: the client shows the | ||
| 515 | - // context meter and the tokens a turn cost. | ||
| 516 | - if speed != nil && resp != nil { | ||
| 517 | - out := 0 | ||
| 518 | - if resp.Usage != nil { | ||
| 519 | - out = resp.Usage.OutputTokens | ||
| 520 | - } | ||
| 521 | - speed.settle(out) | ||
| 522 | - } | ||
| 523 | - if resp != nil && resp.Usage != nil { | ||
| 524 | - if s, ok := ui.ActiveSink().(ui.UsageSink); ok { | ||
| 525 | - s.Usage(ui.Usage{ | ||
| 526 | - InputTokens: resp.Usage.InputTokens, | ||
| 527 | - OutputTokens: resp.Usage.OutputTokens, | ||
| 528 | - ThoughtTokens: resp.Usage.ThoughtsTokens, | ||
| 529 | - CachedReadTokens: resp.Usage.CachedContentTokens, | ||
| 530 | - }) | ||
| 531 | - } | ||
| 532 | - } | ||
| 533 | - dropReasoning(resp) | ||
| 534 | - if resp != nil { | ||
| 535 | - reply = resp.Message | ||
| 536 | - } | ||
| 537 | - return resp, err | ||
| 538 | - }, | ||
| 539 | - // The tool is about to write to the screen: we forget the | ||
| 540 | - // whitespace the previous text left pending. The hook lands at | ||
| 541 | - // exactly the right moment — just before the tool prints its 🛠️ | ||
| 542 | - // line. | ||
| 543 | - // The tool hooks run here too (hooks.go): one place sees every | ||
| 544 | - // call, built-in and MCP, before the tool asks for consent. | ||
| 545 | - // schemaGuard (toolschema.go, ticket 225) wraps the whole chain: it | ||
| 546 | - // repairs the file tools' arguments before the hooks see them, and | ||
| 547 | - // turns a schema error left after them into a result the model reads. | ||
| 548 | - WrapTool: func(ctx context.Context, params *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error) { | ||
| 549 | - gaps.drop() | ||
| 550 | - ctx = withReply(ctx, reply) | ||
| 551 | - return schemaGuard(ctx, params, &invalid, func(ctx context.Context, params *ai.ToolParams) (*ai.MultipartToolResponse, error) { | ||
| 552 | - if !e.hooks.Enabled() && toolJudge == nil && resultJudge == nil { | ||
| 553 | - return next(ctx, params) | ||
| 554 | - } | ||
| 555 | - return e.runToolHooks(ctx, params, next) | ||
| 556 | - }) | ||
| 557 | - }, | ||
| 558 | - }, nil | ||
| 559 | - }) | ||
| 560 | - | ||
| 561 | - opts := []ai.GenerateOption{ | ||
| 562 | - ai.WithModelName(e.Model), | ||
| 563 | - ai.WithMessages(messages...), | ||
| 564 | - ai.WithTools(tools...), | ||
| 565 | - ai.WithMaxTurns(config.Cfg.MaxTurns), // max model ↔ tools round trips | ||
| 566 | - ai.WithConfig(config.Cfg.Sampling), | ||
| 567 | - ai.WithUse(capture), | ||
| 568 | - } | ||
| 569 | - // structuredOutput (ticket 80): the server constrains the answer to the | ||
| 570 | - // schema, and Genkit checks it against the schema before handing it back. | ||
| 571 | - if config.Cfg.OutputSchema != nil { | ||
| 572 | - opts = append(opts, ai.WithOutputSchema(config.Cfg.OutputSchema)) | ||
| 573 | - } | ||
| 574 | 256 | ||
| 575 | - // The prefix is printed by the first token rather than up front, so the | 257 | + t := newTurn(e, messages) |
| 576 | - // spinner has a line to itself and vanishes without taking anything with it. | 258 | + defer t.finishSpeed() |
| 577 | - printed := false | 259 | + opts := t.options(tools) |
| 578 | - emit := func(text string) { | ||
| 579 | - // An event-consuming front end (ACP) takes the chunk raw: the editor | ||
| 580 | - // renders Markdown and owns the layout, so the gap/squeeze machinery — | ||
| 581 | - // which fights the terminal screen, not the text — stays out of the | ||
| 582 | - // way. `printed` is still maintained: the no-streaming retry below must | ||
| 583 | - // know whether the client already saw part of an answer. | ||
| 584 | - if s := ui.ActiveSink(); s != nil { | ||
| 585 | - if text == "" { | ||
| 586 | - return | ||
| 587 | - } | ||
| 588 | - think.done() | ||
| 589 | - printed = true | ||
| 590 | - s.Text(text) | ||
| 591 | - return | ||
| 592 | - } | ||
| 593 | - // The answer has started: the thinking that led to it is over. | ||
| 594 | - think.done() | ||
| 595 | - // Trailing whitespace is held back, not printed: see the gap type. | ||
| 596 | - out := gaps.next(text) | ||
| 597 | - if out == "" { | ||
| 598 | - return | ||
| 599 | - } | ||
| 600 | - // Stop BEFORE every print, not only the first one. | ||
| 601 | - // | ||
| 602 | - // A question can take several turns, and the tool restarts the spinner | ||
| 603 | - // on its way back to the model. The text of the next turn then landed on | ||
| 604 | - // the spinner's line, which erased it on the following frame | ||
| 605 | - // (`\r\033[2K`): "Hello 👋 to Sam" became "⠦ Thinking… 0s 👋 to Sam". | ||
| 606 | - // Worse, the last sentence of an answer vanished entirely, erased by the | ||
| 607 | - // final Stop(). | ||
| 608 | - // | ||
| 609 | - // Stop() is idempotent and returns immediately when nothing is running, | ||
| 610 | - // so calling it on every chunk costs nothing. | ||
| 611 | - spinner.Stop() | ||
| 612 | - if !printed { | ||
| 613 | - fmt.Print("🤖 ") | ||
| 614 | - printed = true | ||
| 615 | - } | ||
| 616 | - fmt.Print(out) | ||
| 617 | - } | ||
| 618 | 260 | ||
| 619 | - // --- Watchdog --- | 261 | + genCtx, cancelGen := t.watch(ctx) |
| 620 | - // A sub-context the watchdog cancels when the server has been silent too | ||
| 621 | - // long: firstTokenTimeout while a model call reads its prompt, | ||
| 622 | - // WatchdogTimeout between tokens (progress.go). The streaming callback | ||
| 623 | - // beats it on every chunk. | ||
| 624 | - genCtx, p, cancelGen := watchdog(ctx, config.Cfg.WatchdogTimeout, | ||
| 625 | - firstTokenTimeout(config.Cfg.WatchdogTimeout, config.Cfg.FirstTokenTimeout)) | ||
| 626 | defer cancelGen() | 262 | defer cancelGen() |
| 627 | - pl = p | ||
| 628 | - beat := pl.beat | ||
| 629 | - genCtx = withHeartbeat(genCtx, beat) | ||
| 630 | - | ||
| 631 | - // A thinking model streams its reasoning in a field Genkit drops, so the | ||
| 632 | - // streaming callback below never runs while it thinks (reasoning.go). The | ||
| 633 | - // beat matters more than the display here: without it the watchdog kills | ||
| 634 | - // a turn that is going perfectly well, and a model can reason for a long | ||
| 635 | - // time before its first word — 38s measured. The display is a setting; | ||
| 636 | - // the heartbeat never is. | ||
| 637 | - genCtx = WithReasoning(genCtx, func(text string) { | ||
| 638 | - beat() | ||
| 639 | - loops.feed(text) | ||
| 640 | - if config.Cfg.ShowThinking { | ||
| 641 | - think.emit(text) | ||
| 642 | - } | ||
| 643 | - }) | ||
| 644 | - // The error events a server streams, for the model calls to report | ||
| 645 | - // (servererr.go; read back in WrapModel through the context). | ||
| 646 | - genCtx, _ = withServerErrors(genCtx) | ||
| 647 | - // While the server reads the prompt it says how far it got: proof of life | ||
| 648 | - // for the watchdog, and something to show instead of "Thinking". | ||
| 649 | - genCtx = withSpeed(genCtx, speed) | ||
| 650 | - genCtx = withPromptProgress(genCtx, func(pp promptProgress) { | ||
| 651 | - pl.alive() | ||
| 652 | - if pl.waiting.Load() { | ||
| 653 | - spinner.Start(progressLabel(pp)) | ||
| 654 | - } | ||
| 655 | - }) | ||
| 656 | 263 | ||
| 657 | spinner.Start("Thinking") | 264 | spinner.Start("Thinking") |
| 658 | defer spinner.Stop() | 265 | defer spinner.Stop() |
| @@ -661,35 +268,11 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | |||
| 661 | // a derailed model repeating itself for minutes is stopped at once, and | 268 | // a derailed model repeating itself for minutes is stopped at once, and |
| 662 | // the spinner says a tool call is being composed rather than nothing. | 269 | // the spinner says a tool call is being composed rather than nothing. |
| 663 | guard := &toolCallGuard{} | 270 | guard := &toolCallGuard{} |
| 664 | - resp, err := genkit.Generate(genCtx, e.G, append(opts, | 271 | + resp, err := genkit.Generate(genCtx, e.G, append(opts, ai.WithStreaming(t.onChunk(guard)))...) |
| 665 | - ai.WithStreaming(func(_ context.Context, chunk *ai.ModelResponseChunk) error { | ||
| 666 | - beat() | ||
| 667 | - wasComposing := guard.composing | ||
| 668 | - if err := guard.observe(chunk); err != nil { | ||
| 669 | - return err | ||
| 670 | - } | ||
| 671 | - if guard.composing && !wasComposing { | ||
| 672 | - spinner.Start("Composing a tool call") | ||
| 673 | - } | ||
| 674 | - // Since Genkit 1.13 a chunk may carry nothing but reasoning. The | ||
| 675 | - // tap has already shown it (reasoning.go); handed to emit, its | ||
| 676 | - // empty text would close the thought block after every token. | ||
| 677 | - if onlyReasoning(chunk) { | ||
| 678 | - return nil | ||
| 679 | - } | ||
| 680 | - loops.feed(chunk.Text()) | ||
| 681 | - emit(chunk.Text()) | ||
| 682 | - return nil | ||
| 683 | - }), | ||
| 684 | - )...) | ||
| 685 | if guard.reason != "" { | 272 | if guard.reason != "" { |
| 686 | - return nil, guard.keep(full, resp), runawayError(guard.reason) | 273 | + return nil, guard.keep(t.full, resp), runawayError(guard.reason) |
| 687 | } | 274 | } |
| 688 | 275 | ||
| 689 | - // `full` grows as soon as a tool turn has happened: it is the witness that | ||
| 690 | - // says whether commands ran, and it is used twice below. | ||
| 691 | - toolsRan := len(full) > len(messages) | ||
| 692 | - | ||
| 693 | // The watchdog cut `genCtx` while the PARENT context is intact: this is a | 276 | // The watchdog cut `genCtx` while the PARENT context is intact: this is a |
| 694 | // silence of the connection, not a cancellation by the user. | 277 | // silence of the connection, not a cancellation by the user. |
| 695 | // | 278 | // |
| @@ -699,343 +282,26 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | |||
| 699 | // that is, it called the MUTE engine again. Measured: 5 s of watchdog then | 282 | // that is, it called the MUTE engine again. Measured: 5 s of watchdog then |
| 700 | // 20 s of "Retrying without streaming…" against a silent server, and the | 283 | // 20 s of "Retrying without streaming…" against a silent server, and the |
| 701 | // "stalled" message never shown. | 284 | // "stalled" message never shown. |
| 702 | - stalled := genCtx.Err() != nil && ctx.Err() == nil | 285 | + if err != nil && genCtx.Err() != nil && ctx.Err() == nil { |
| 703 | - if err != nil && stalled { | ||
| 704 | // We return `full` despite the failure: if commands ran before the | 286 | // We return `full` despite the failure: if commands ran before the |
| 705 | // silence, their work must not be lost. | 287 | // silence, their work must not be lost. |
| 706 | - return nil, full, errStalled | 288 | + return nil, t.full, errStalled |
| 707 | } | 289 | } |
| 708 | 290 | ||
| 709 | - // The retry is only worth it for an SSE stream cut before the first byte. | 291 | + if t.retryableWithoutStreaming(err) { |
| 710 | - // Any other error (maxTurns exceeded, a failing tool, invalid arguments) | ||
| 711 | - // happens AFTER commands have run, and replaying the turn would replay them: | ||
| 712 | - // measured, an `echo >>` wrote itself twice. `full` grows as soon as a tool | ||
| 713 | - // turn has happened, which is enough to tell the two apart. | ||
| 714 | - // The loop detector's stop is never retried either: replaying the turn | ||
| 715 | - // would run the repeated tool once more before stopping again. | ||
| 716 | - // Nor is a tool call whose arguments did not parse: the hook above has | ||
| 717 | - // already handed it back, and the same limit would cut the same call. | ||
| 718 | - // Nor a request larger than the server's window (ticket 233): it fails | ||
| 719 | - // the same way without streaming. | ||
| 720 | - _, stuck := stuckTurn(err) | ||
| 721 | - truncated, malformed := argsError(err) | ||
| 722 | - _, isLoop := looped(err) // ticket 235: the same model would loop again | ||
| 723 | - if err != nil && !printed && !toolsRan && !stuck && !truncated && !malformed && !contextOverflow(err) && !isLoop { | ||
| 724 | spinner.Start("Retrying without streaming") | 292 | spinner.Start("Retrying without streaming") |
| 725 | if resp, err = genkit.Generate(ctx, e.G, opts...); err == nil { | 293 | if resp, err = genkit.Generate(ctx, e.G, opts...); err == nil { |
| 726 | - emit(resp.Text()) | 294 | + t.emit(resp.Text()) |
| 727 | } | 295 | } |
| 728 | } | 296 | } |
| 729 | 297 | ||
| 730 | - think.done() | 298 | + t.think.done() |
| 731 | err = cutStructuredAnswer(resp, err) | 299 | err = cutStructuredAnswer(resp, err) |
| 732 | 300 | ||
| 733 | // `full` stops at the last call to the model; its answer is appended after. | 301 | // `full` stops at the last call to the model; its answer is appended after. |
| 302 | + full := t.full | ||
| 734 | if resp != nil && resp.Message != nil { | 303 | if resp != nil && resp.Message != nil { |
| 735 | full = append(full, resp.Message) | 304 | full = append(full, resp.Message) |
| 736 | } | 305 | } |
| 737 | return resp, full, err | 306 | return resp, full, err |
| 738 | } | 307 | } |
| 739 | - | ||
| 740 | -// Summarize asks the model for a plain-text answer to `messages` — no tools, | ||
| 741 | -// no screen output. It exists for the context compression (internal/compact): | ||
| 742 | -// the summary must not stream onto the screen as if it were an answer, and a | ||
| 743 | -// request that offers tools invites the model to call them instead of writing. | ||
| 744 | -// It goes through the same Genkit and the same model reference as Generate, | ||
| 745 | -// so it lands on the same provider and the same server. | ||
| 746 | -// | ||
| 747 | -// The watchdog is kept, with twice the usual patience: this is the longest | ||
| 748 | -// prefill of the session (the whole old history at once) and nothing streams | ||
| 749 | -// until it is done. Streaming stays on so that the summary's own tokens beat | ||
| 750 | -// the watchdog while it is being written. | ||
| 751 | -// | ||
| 752 | -// A thinking model is asked not to reason (withoutThinking, llama.cpp | ||
| 753 | -// providers and Ollama), over what the sampling config says: its reasoning counts against maxTokens and is not in | ||
| 754 | -// resp.Text(), so it can spend the whole budget and leave no summary. On the | ||
| 755 | -// other providers that can still happen; emptySummary then says so. | ||
| 756 | -func (e *Engine) Summarize(ctx context.Context, messages []*ai.Message, maxTokens int) (string, error) { | ||
| 757 | - // The agent's sampling, minus what does not apply here: `parallel_tool_calls` | ||
| 758 | - // without tools is a 400 on the OpenAI API, and the answer limit is the | ||
| 759 | - // summary's budget, not the answer's — under the name the config uses | ||
| 760 | - // (max_completion_tokens for the OpenAI models that refuse max_tokens). | ||
| 761 | - sampling := maps.Clone(config.Cfg.Sampling) | ||
| 762 | - if sampling == nil { | ||
| 763 | - sampling = map[string]any{} | ||
| 764 | - } | ||
| 765 | - delete(sampling, "parallel_tool_calls") | ||
| 766 | - sampling[limitKey(sampling)] = maxTokens | ||
| 767 | - | ||
| 768 | - genCtx, pl, cancel := watchdog(ctx, 2*config.Cfg.WatchdogTimeout, | ||
| 769 | - firstTokenTimeout(2*config.Cfg.WatchdogTimeout, config.Cfg.FirstTokenTimeout)) | ||
| 770 | - defer cancel() | ||
| 771 | - beat := pl.beat | ||
| 772 | - // The same heartbeat, and deliberately no display: a summary is written | ||
| 773 | - // behind the user's back, and a model that thinks about it must not spill | ||
| 774 | - // that onto the screen in the middle of their conversation. The length is | ||
| 775 | - // kept for emptySummary. | ||
| 776 | - var reasoned atomic.Int64 | ||
| 777 | - genCtx = WithReasoning(genCtx, func(s string) { reasoned.Add(int64(len(s))); beat() }) | ||
| 778 | - genCtx = withoutThinking(genCtx) | ||
| 779 | - genCtx, srvErrs := withServerErrors(genCtx) | ||
| 780 | - genCtx = withPromptProgress(genCtx, func(promptProgress) { pl.alive() }) | ||
| 781 | - | ||
| 782 | - resp, err := genkit.Generate(genCtx, e.G, | ||
| 783 | - ai.WithModelName(e.Model), | ||
| 784 | - ai.WithMessages(messages...), | ||
| 785 | - ai.WithConfig(sampling), | ||
| 786 | - ai.WithStreaming(func(_ context.Context, _ *ai.ModelResponseChunk) error { | ||
| 787 | - beat() | ||
| 788 | - return nil | ||
| 789 | - }), | ||
| 790 | - ) | ||
| 791 | - if err != nil { | ||
| 792 | - // Same test as in Generate: the contexts, not the wrapped error. | ||
| 793 | - if genCtx.Err() != nil && ctx.Err() == nil { | ||
| 794 | - return "", fmt.Errorf("summary timed out (stalled)") | ||
| 795 | - } | ||
| 796 | - if msg := srvErrs.take(); msg != "" { | ||
| 797 | - return "", &serverError{msg: msg, err: err} | ||
| 798 | - } | ||
| 799 | - return "", err | ||
| 800 | - } | ||
| 801 | - text := strings.TrimSpace(resp.Text()) | ||
| 802 | - if text == "" { | ||
| 803 | - return "", emptySummary(resp, maxTokens, int(reasoned.Load())) | ||
| 804 | - } | ||
| 805 | - return text, nil | ||
| 806 | -} | ||
| 807 | - | ||
| 808 | -// emptySummary is the error of a summary request that came back without | ||
| 809 | -// text, with what the response says about why: the line lands in the session | ||
| 810 | -// file's `errors`, and "empty summary" alone sent an investigation to replay | ||
| 811 | -// an 18k-token request. The usual cause is a thinking model that reasoned | ||
| 812 | -// until max_tokens; the line then names the setting to raise. | ||
| 813 | -func emptySummary(resp *ai.ModelResponse, maxTokens, reasoned int) error { | ||
| 814 | - out := 0 | ||
| 815 | - if resp.Usage != nil { | ||
| 816 | - out = resp.Usage.OutputTokens | ||
| 817 | - } | ||
| 818 | - why := fmt.Sprintf("finish: %s, %d output token(s), %d char(s) of reasoning", resp.FinishReason, out, reasoned) | ||
| 819 | - if resp.FinishReason == ai.FinishReasonLength && reasoned > 0 { | ||
| 820 | - return fmt.Errorf("the model returned an empty summary: it reasoned until the %d-token limit (%s) — raise context.summaryMaxTokens", maxTokens, why) | ||
| 821 | - } | ||
| 822 | - return fmt.Errorf("the model returned an empty summary (%s)", why) | ||
| 823 | -} | ||
| 824 | - | ||
| 825 | -// Names of the tools whose responses we count. They live here rather than | ||
| 826 | -// scattered through the display code: the counter is a measurement, and a | ||
| 827 | -// measurement needs a single definition. | ||
| 828 | -const ( | ||
| 829 | - toolBash = "bash" | ||
| 830 | - toolSkill = "read_skill" | ||
| 831 | - toolRead = "read_file" | ||
| 832 | - toolWrite = "write_file" | ||
| 833 | - toolEdit = "edit_file" | ||
| 834 | - toolLSP = "lsp" | ||
| 835 | -) | ||
| 836 | - | ||
| 837 | -// executed returns, in order, the text of the calls to a given tool that | ||
| 838 | -// ACTUALLY ran. | ||
| 839 | -// | ||
| 840 | -// We start from the RESPONSES: a call the model asked for but which never ran | ||
| 841 | -// (interrupted turn, maxTurns exceeded) produces none. The text of the call, on | ||
| 842 | -// the other hand, is ONLY in the request — hence the pairing by Ref, the | ||
| 843 | -// identifier the server gives to each call. | ||
| 844 | -func executed(history []*ai.Message, name string) []string { | ||
| 845 | - // Calls with no Ref (some servers do not set one) are paired in order, BUT | ||
| 846 | - // only against the same tool name: a turn mixes `bash` and `read_skill`, and | ||
| 847 | - // the first pending call is not necessarily for the right tool. | ||
| 848 | - type call struct{ ref, name, text string } | ||
| 849 | - var pending []call | ||
| 850 | - var out []string | ||
| 851 | - | ||
| 852 | - for _, m := range history { | ||
| 853 | - for _, p := range m.Content { | ||
| 854 | - switch { | ||
| 855 | - case p.IsToolRequest(): | ||
| 856 | - pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name, commandText(p.ToolRequest)}) | ||
| 857 | - | ||
| 858 | - case p.IsToolResponse() && p.ToolResponse != nil && p.ToolResponse.Name == name: | ||
| 859 | - ref := p.ToolResponse.Ref | ||
| 860 | - i := slices.IndexFunc(pending, func(c call) bool { | ||
| 861 | - if ref != "" { | ||
| 862 | - return c.ref == ref | ||
| 863 | - } | ||
| 864 | - return c.name == name | ||
| 865 | - }) | ||
| 866 | - if i < 0 { // lost call: the name beats nothing | ||
| 867 | - out = append(out, name) | ||
| 868 | - continue | ||
| 869 | - } | ||
| 870 | - out = append(out, pending[i].text) | ||
| 871 | - pending = slices.Delete(pending, i, i+1) | ||
| 872 | - } | ||
| 873 | - } | ||
| 874 | - } | ||
| 875 | - return out | ||
| 876 | -} | ||
| 877 | - | ||
| 878 | -// commandText describes a tool call in one line. For `bash` it is the command | ||
| 879 | -// itself — the rest is only wrapping; for any other tool, its name followed by | ||
| 880 | -// its arguments. | ||
| 881 | -func commandText(r *ai.ToolRequest) string { | ||
| 882 | - if in, ok := r.Input.(map[string]any); ok { | ||
| 883 | - if c, ok := in["command"].(string); ok && strings.TrimSpace(c) != "" { | ||
| 884 | - return strings.TrimSpace(c) | ||
| 885 | - } | ||
| 886 | - } | ||
| 887 | - args, err := json.Marshal(r.Input) | ||
| 888 | - if err != nil || string(args) == "null" { | ||
| 889 | - return r.Name | ||
| 890 | - } | ||
| 891 | - return r.Name + " " + string(args) | ||
| 892 | -} | ||
| 893 | - | ||
| 894 | -// responses counts the responses of a given tool in a history. | ||
| 895 | -func responses(history []*ai.Message, name string) int { | ||
| 896 | - return len(executed(history, name)) | ||
| 897 | -} | ||
| 898 | - | ||
| 899 | -// Commands counts the commands actually run in a history — one per response of | ||
| 900 | -// the `bash` tool. It is the only reliable measure of the work done: a model | ||
| 901 | -// that tells stories without acting produces a fine answer and a count of zero. | ||
| 902 | -// | ||
| 903 | -// The other tools do NOT count. Loading a skill runs nothing, and counting those | ||
| 904 | -// reads would make the number say the opposite of what it is for: measured | ||
| 905 | -// before the fix, a turn with two reads and a single command displayed | ||
| 906 | -// "⚙ 3 command(s)". | ||
| 907 | -func Commands(history []*ai.Message) int { | ||
| 908 | - return responses(history, toolBash) | ||
| 909 | -} | ||
| 910 | - | ||
| 911 | -// CommandList returns, in order, the text of the commands Commands counts — the | ||
| 912 | -// one shown in the recap under the count when `displayCommands` is on. The count | ||
| 913 | -// says HOW MANY, the list says WHAT. | ||
| 914 | -func CommandList(history []*ai.Message) []string { | ||
| 915 | - return executed(history, toolBash) | ||
| 916 | -} | ||
| 917 | - | ||
| 918 | -// FileOps returns, in order, the file-tool calls that ran — read_file, | ||
| 919 | -// write_file, edit_file — as one line each ("edit_file hello/main.go (2 edits)"). | ||
| 920 | -// | ||
| 921 | -// They are counted APART from the commands, not folded into them: this part | ||
| 922 | -// compares editing through the `edit` CLI (one bash command per edit) with | ||
| 923 | -// editing through built-in tools, and a recap that counted both as "commands" | ||
| 924 | -// would hide the very difference being measured. `⚙ 3 command(s) · 📝 2 file | ||
| 925 | -// op(s)` keeps the two columns readable side by side. | ||
| 926 | -func FileOps(history []*ai.Message) []string { | ||
| 927 | - return executedAny(history, toolRead, toolWrite, toolEdit) | ||
| 928 | -} | ||
| 929 | - | ||
| 930 | -// executedAny is executed() across several tool names, keeping the order in | ||
| 931 | -// which the responses appear — a per-name pass would lose the interleaving of | ||
| 932 | -// a read followed by an edit. | ||
| 933 | -func executedAny(history []*ai.Message, names ...string) []string { | ||
| 934 | - type call struct{ ref, name, text string } | ||
| 935 | - var pending []call | ||
| 936 | - var out []string | ||
| 937 | - isOurs := func(n string) bool { return slices.Contains(names, n) } | ||
| 938 | - | ||
| 939 | - for _, m := range history { | ||
| 940 | - for _, p := range m.Content { | ||
| 941 | - switch { | ||
| 942 | - case p.IsToolRequest(): | ||
| 943 | - pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name, fileOpText(p.ToolRequest)}) | ||
| 944 | - case p.IsToolResponse() && p.ToolResponse != nil && isOurs(p.ToolResponse.Name): | ||
| 945 | - ref, name := p.ToolResponse.Ref, p.ToolResponse.Name | ||
| 946 | - i := slices.IndexFunc(pending, func(c call) bool { | ||
| 947 | - if ref != "" { | ||
| 948 | - return c.ref == ref | ||
| 949 | - } | ||
| 950 | - return c.name == name | ||
| 951 | - }) | ||
| 952 | - if i < 0 { | ||
| 953 | - out = append(out, name) | ||
| 954 | - continue | ||
| 955 | - } | ||
| 956 | - out = append(out, pending[i].text) | ||
| 957 | - pending = slices.Delete(pending, i, i+1) | ||
| 958 | - } | ||
| 959 | - } | ||
| 960 | - } | ||
| 961 | - return out | ||
| 962 | -} | ||
| 963 | - | ||
| 964 | -// fileOpText describes a file-tool call in one line: the tool, the path, and | ||
| 965 | -// for edit_file the number of edits — never the texts themselves, which can | ||
| 966 | -// run to dozens of lines and belong in the diff, not in the recap. | ||
| 967 | -func fileOpText(r *ai.ToolRequest) string { | ||
| 968 | - in, _ := r.Input.(map[string]any) | ||
| 969 | - path, _ := in["path"].(string) | ||
| 970 | - switch r.Name { | ||
| 971 | - case toolEdit: | ||
| 972 | - if edits, ok := in["edits"].([]any); ok { | ||
| 973 | - return fmt.Sprintf("%s %s (%d edit(s))", r.Name, path, len(edits)) | ||
| 974 | - } | ||
| 975 | - case toolRead: | ||
| 976 | - if s, ok := in["start"].(float64); ok && s > 0 { | ||
| 977 | - e, _ := in["end"].(float64) | ||
| 978 | - return fmt.Sprintf("%s %s %d-%d", r.Name, path, int(s), int(e)) | ||
| 979 | - } | ||
| 980 | - } | ||
| 981 | - if path == "" { | ||
| 982 | - return commandText(r) | ||
| 983 | - } | ||
| 984 | - return r.Name + " " + path | ||
| 985 | -} | ||
| 986 | - | ||
| 987 | -// Skills counts the skills loaded — one per response of `read_skill`. Shown | ||
| 988 | -// next to the command count: seeing which procedure the agent chose to follow is | ||
| 989 | -// half the point of this part. | ||
| 990 | -func Skills(history []*ai.Message) int { | ||
| 991 | - n := 0 | ||
| 992 | - for _, m := range history { | ||
| 993 | - for _, p := range m.Content { | ||
| 994 | - if !p.IsToolResponse() || p.ToolResponse == nil || p.ToolResponse.Name != toolSkill { | ||
| 995 | - continue | ||
| 996 | - } | ||
| 997 | - if !strings.HasPrefix(strings.TrimSpace(responseText(p.ToolResponse)), skillMiss) { | ||
| 998 | - n++ | ||
| 999 | - } | ||
| 1000 | - } | ||
| 1001 | - } | ||
| 1002 | - return n | ||
| 1003 | -} | ||
| 1004 | - | ||
| 1005 | -// skillMiss is how `read_skill` answers a name that is not in the catalogue. | ||
| 1006 | -// Counting those as skills made the number say the opposite of what it is | ||
| 1007 | -// for: `📖 2 skill(s)` could mean two failed lookups and nothing loaded. | ||
| 1008 | -const skillMiss = "[skill:" | ||
| 1009 | - | ||
| 1010 | -// responseText is a tool response as text. Every tool here returns a string; | ||
| 1011 | -// anything else is formatted rather than dropped, so a change of shape shows | ||
| 1012 | -// up as an odd count instead of a silent zero. | ||
| 1013 | -func responseText(r *ai.ToolResponse) string { | ||
| 1014 | - if s, ok := r.Output.(string); ok { | ||
| 1015 | - return s | ||
| 1016 | - } | ||
| 1017 | - return fmt.Sprintf("%v", r.Output) | ||
| 1018 | -} | ||
| 1019 | - | ||
| 1020 | -// skillsDeclared says this agent has a skills catalogue at all. Set once by | ||
| 1021 | -// main, read by the three turn recaps. | ||
| 1022 | -// | ||
| 1023 | -// Why it exists: `📖 N skill(s)` used to be printed only when N > 0, so | ||
| 1024 | -// "no skill applied" and "a skill applied and the model ignored it" looked | ||
| 1025 | -// identical — nothing at all. Showing `📖 0 skill(s)` is the whole point; | ||
| 1026 | -// showing it in a project that has no skills would be noise. | ||
| 1027 | -var skillsDeclared atomic.Bool | ||
| 1028 | - | ||
| 1029 | -// DeclareSkills records whether the agent was given any skill. | ||
| 1030 | -func DeclareSkills(yes bool) { skillsDeclared.Store(yes) } | ||
| 1031 | - | ||
| 1032 | -// SkillsAvailable reports it, for the turn recaps. | ||
| 1033 | -func SkillsAvailable() bool { return skillsDeclared.Load() } | ||
| 1034 | - | ||
| 1035 | -// LSPCalls counts the `lsp` tool responses in a history — questions put to a | ||
| 1036 | -// language server (definition, references, hover, symbols, diagnostics, | ||
| 1037 | -// rename). Shown apart from the commands for the same reason as the file | ||
| 1038 | -// ops: asking the compiler is not running a command. | ||
| 1039 | -func LSPCalls(history []*ai.Message) int { | ||
| 1040 | - return responses(history, toolLSP) | ||
| 1041 | -} | ||
modified
internal/engine/explain.go +34 -22 | @@ -47,44 +47,56 @@ func (p *openaiCompat) Explain(err error, b Backend) string { | ||
| 47 | 47 | return "" |
| 48 | 48 | } |
| 49 | 49 | msg := err.Error() |
| 50 | - | |
| 51 | - status := 0 | |
| 52 | - var apiErr *openai.Error | |
| 53 | - if errors.As(err, &apiErr) && apiErr.Response != nil { | |
| 54 | - status = apiErr.Response.StatusCode | |
| 55 | - } else if m := statusInText.FindStringSubmatch(msg); m != nil { | |
| 56 | - status, _ = strconv.Atoi(m[1]) | |
| 57 | - } | |
| 58 | - | |
| 50 | + status := httpStatus(err, msg) | |
| 51 | + line := msg | |
| 59 | 52 | switch { |
| 60 | 53 | case connectionRefused(err, msg): |
| 61 | - return fmt.Sprintf("%s: nothing answers at %s — %s", p.name, b.BaseURL, p.startHint) | |
| 54 | + line = fmt.Sprintf("%s: nothing answers at %s — %s", p.name, b.BaseURL, p.startHint) | |
| 62 | 55 | |
| 63 | 56 | // llama-server without --jinja refuses `tools` with a message naming the |
| 64 | 57 | // flag. It is the one llama.cpp error a first-time user hits, so it gets |
| 65 | 58 | // its own line rather than the generic "server error". |
| 66 | 59 | case strings.Contains(msg, "jinja"): |
| 67 | - return fmt.Sprintf("%s: tool calls need llama-server started with --jinja", p.name) | |
| 60 | + line = fmt.Sprintf("%s: tool calls need llama-server started with --jinja", p.name) | |
| 68 | 61 | |
| 69 | - // The variable named here is the one Resolve actually read (yaml `apiKeyEnv`, | |
| 70 | - // else the provider's default). When there is none — DMR ignores keys — a | |
| 71 | - // 401 means the URL is not the server we think it is, so that is the hint. | |
| 72 | 62 | case status == 401 || status == 403: |
| 73 | - if b.APIKeyEnv == "" { | |
| 74 | - return fmt.Sprintf("%s: authentication failed at %s — this server should not need a key; check baseUrl", p.name, b.BaseURL) | |
| 75 | - } | |
| 76 | - return fmt.Sprintf("%s: authentication failed at %s — is $%s set and valid?", p.name, b.BaseURL, b.APIKeyEnv) | |
| 63 | + line = p.authLine(b) | |
| 77 | 64 | |
| 78 | 65 | case status == 404: |
| 79 | - return fmt.Sprintf("%s: %q not found at %s — %s", p.name, b.Model, b.BaseURL, fmt.Sprintf(p.notFoundHint, b.Model)) | |
| 66 | + line = fmt.Sprintf("%s: %q not found at %s — %s", p.name, b.Model, b.BaseURL, fmt.Sprintf(p.notFoundHint, b.Model)) | |
| 80 | 67 | |
| 81 | 68 | case status == 429: |
| 82 | - return fmt.Sprintf("%s: rate limited — wait, or lower the pace", p.name) | |
| 69 | + line = fmt.Sprintf("%s: rate limited — wait, or lower the pace", p.name) | |
| 83 | 70 | |
| 84 | 71 | case status >= 500: |
| 85 | - return fmt.Sprintf("%s: server error %d — %s", p.name, status, firstLine(msg)) | |
| 72 | + line = fmt.Sprintf("%s: server error %d — %s", p.name, status, firstLine(msg)) | |
| 73 | + } | |
| 74 | + return line | |
| 75 | +} | |
| 76 | + | |
| 77 | +// httpStatus is the HTTP status of a failed call: the API error's, else one | |
| 78 | +// quoted in the message; 0 when there is none. | |
| 79 | +func httpStatus(err error, msg string) int { | |
| 80 | + var apiErr *openai.Error | |
| 81 | + if errors.As(err, &apiErr) && apiErr.Response != nil { | |
| 82 | + return apiErr.Response.StatusCode | |
| 83 | + } | |
| 84 | + if m := statusInText.FindStringSubmatch(msg); m != nil { | |
| 85 | + status, _ := strconv.Atoi(m[1]) | |
| 86 | + return status | |
| 87 | + } | |
| 88 | + return 0 | |
| 89 | +} | |
| 90 | + | |
| 91 | +// authLine explains a 401 or 403. The variable named is the one Resolve | |
| 92 | +// actually read (yaml `apiKeyEnv`, else the provider's default). When there | |
| 93 | +// is none — DMR ignores keys — a 401 means the URL is not the server we | |
| 94 | +// think it is, so that is the hint. | |
| 95 | +func (p *openaiCompat) authLine(b Backend) string { | |
| 96 | + if b.APIKeyEnv == "" { | |
| 97 | + return fmt.Sprintf("%s: authentication failed at %s — this server should not need a key; check baseUrl", p.name, b.BaseURL) | |
| 86 | 98 | } |
| 87 | - return msg | |
| 99 | + return fmt.Sprintf("%s: authentication failed at %s — is $%s set and valid?", p.name, b.BaseURL, b.APIKeyEnv) | |
| 88 | 100 | } |
| 89 | 101 | |
| 90 | 102 | // connectionRefused: a dial that failed, whatever the wrapping. The typed check |
| @@ -47,44 +47,56 @@ func (p *openaiCompat) Explain(err error, b Backend) string { | |||
| 47 | return "" | 47 | return "" |
| 48 | } | 48 | } |
| 49 | msg := err.Error() | 49 | msg := err.Error() |
| 50 | - | 50 | + status := httpStatus(err, msg) |
| 51 | - status := 0 | 51 | + line := msg |
| 52 | - var apiErr *openai.Error | ||
| 53 | - if errors.As(err, &apiErr) && apiErr.Response != nil { | ||
| 54 | - status = apiErr.Response.StatusCode | ||
| 55 | - } else if m := statusInText.FindStringSubmatch(msg); m != nil { | ||
| 56 | - status, _ = strconv.Atoi(m[1]) | ||
| 57 | - } | ||
| 58 | - | ||
| 59 | switch { | 52 | switch { |
| 60 | case connectionRefused(err, msg): | 53 | case connectionRefused(err, msg): |
| 61 | - return fmt.Sprintf("%s: nothing answers at %s — %s", p.name, b.BaseURL, p.startHint) | 54 | + line = fmt.Sprintf("%s: nothing answers at %s — %s", p.name, b.BaseURL, p.startHint) |
| 62 | 55 | ||
| 63 | // llama-server without --jinja refuses `tools` with a message naming the | 56 | // llama-server without --jinja refuses `tools` with a message naming the |
| 64 | // flag. It is the one llama.cpp error a first-time user hits, so it gets | 57 | // flag. It is the one llama.cpp error a first-time user hits, so it gets |
| 65 | // its own line rather than the generic "server error". | 58 | // its own line rather than the generic "server error". |
| 66 | case strings.Contains(msg, "jinja"): | 59 | case strings.Contains(msg, "jinja"): |
| 67 | - return fmt.Sprintf("%s: tool calls need llama-server started with --jinja", p.name) | 60 | + line = fmt.Sprintf("%s: tool calls need llama-server started with --jinja", p.name) |
| 68 | 61 | ||
| 69 | - // The variable named here is the one Resolve actually read (yaml `apiKeyEnv`, | ||
| 70 | - // else the provider's default). When there is none — DMR ignores keys — a | ||
| 71 | - // 401 means the URL is not the server we think it is, so that is the hint. | ||
| 72 | case status == 401 || status == 403: | 62 | case status == 401 || status == 403: |
| 73 | - if b.APIKeyEnv == "" { | 63 | + line = p.authLine(b) |
| 74 | - return fmt.Sprintf("%s: authentication failed at %s — this server should not need a key; check baseUrl", p.name, b.BaseURL) | ||
| 75 | - } | ||
| 76 | - return fmt.Sprintf("%s: authentication failed at %s — is $%s set and valid?", p.name, b.BaseURL, b.APIKeyEnv) | ||
| 77 | 64 | ||
| 78 | case status == 404: | 65 | case status == 404: |
| 79 | - return fmt.Sprintf("%s: %q not found at %s — %s", p.name, b.Model, b.BaseURL, fmt.Sprintf(p.notFoundHint, b.Model)) | 66 | + line = fmt.Sprintf("%s: %q not found at %s — %s", p.name, b.Model, b.BaseURL, fmt.Sprintf(p.notFoundHint, b.Model)) |
| 80 | 67 | ||
| 81 | case status == 429: | 68 | case status == 429: |
| 82 | - return fmt.Sprintf("%s: rate limited — wait, or lower the pace", p.name) | 69 | + line = fmt.Sprintf("%s: rate limited — wait, or lower the pace", p.name) |
| 83 | 70 | ||
| 84 | case status >= 500: | 71 | case status >= 500: |
| 85 | - return fmt.Sprintf("%s: server error %d — %s", p.name, status, firstLine(msg)) | 72 | + line = fmt.Sprintf("%s: server error %d — %s", p.name, status, firstLine(msg)) |
| 73 | + } | ||
| 74 | + return line | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +// httpStatus is the HTTP status of a failed call: the API error's, else one | ||
| 78 | +// quoted in the message; 0 when there is none. | ||
| 79 | +func httpStatus(err error, msg string) int { | ||
| 80 | + var apiErr *openai.Error | ||
| 81 | + if errors.As(err, &apiErr) && apiErr.Response != nil { | ||
| 82 | + return apiErr.Response.StatusCode | ||
| 83 | + } | ||
| 84 | + if m := statusInText.FindStringSubmatch(msg); m != nil { | ||
| 85 | + status, _ := strconv.Atoi(m[1]) | ||
| 86 | + return status | ||
| 87 | + } | ||
| 88 | + return 0 | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +// authLine explains a 401 or 403. The variable named is the one Resolve | ||
| 92 | +// actually read (yaml `apiKeyEnv`, else the provider's default). When there | ||
| 93 | +// is none — DMR ignores keys — a 401 means the URL is not the server we | ||
| 94 | +// think it is, so that is the hint. | ||
| 95 | +func (p *openaiCompat) authLine(b Backend) string { | ||
| 96 | + if b.APIKeyEnv == "" { | ||
| 97 | + return fmt.Sprintf("%s: authentication failed at %s — this server should not need a key; check baseUrl", p.name, b.BaseURL) | ||
| 86 | } | 98 | } |
| 87 | - return msg | 99 | + return fmt.Sprintf("%s: authentication failed at %s — is $%s set and valid?", p.name, b.BaseURL, b.APIKeyEnv) |
| 88 | } | 100 | } |
| 89 | 101 | ||
| 90 | // connectionRefused: a dial that failed, whatever the wrapping. The typed check | 102 | // connectionRefused: a dial that failed, whatever the wrapping. The typed check |
added
internal/engine/gap.go +83 -0 | new file mode 100644 | ||
| @@ -0,0 +1,83 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strings" | |
| 5 | + "sync" | |
| 6 | +) | |
| 7 | + | |
| 8 | +// blanks is the set of characters the model adds around its text without any of | |
| 9 | +// it showing on screen. | |
| 10 | +const blanks = " \t\r\n" | |
| 11 | + | |
| 12 | +// gap holds back the TRAILING whitespace of the streamed text: it is only | |
| 13 | +// printed if visible text follows. Without that, the line breaks the model puts | |
| 14 | +// after its sentence are printed as-is, and the screen hollows out. | |
| 15 | +// | |
| 16 | +// The model produces MORE AND MORE of it as the turns go by — it imitates its | |
| 17 | +// own messages, which it re-reads in the history every turn. Measured: 2 blank | |
| 18 | +// lines before the first 🛠️, 4 before the second, 7, then 11. Holding the | |
| 19 | +// whitespace back is enough to remove all of it, since that whitespace is never | |
| 20 | +// followed by text: it is a tool that writes next. | |
| 21 | +type gap struct { | |
| 22 | + // The `bash` tool may call drop() from SEVERAL goroutines — Genkit runs the | |
| 23 | + // calls of a single turn in parallel (see printMu in tools). | |
| 24 | + mu sync.Mutex | |
| 25 | + held string // whitespace waiting to be followed by text | |
| 26 | + started bool // visible text has already been printed | |
| 27 | +} | |
| 28 | + | |
| 29 | +// next returns what should be printed for this chunk, "" when there is nothing | |
| 30 | +// to print right now. | |
| 31 | +func (g *gap) next(text string) string { | |
| 32 | + g.mu.Lock() | |
| 33 | + defer g.mu.Unlock() | |
| 34 | + | |
| 35 | + body := strings.TrimRight(text, blanks) | |
| 36 | + if body == "" { // an all-whitespace chunk: set aside, not printed | |
| 37 | + if g.started { | |
| 38 | + g.held += text | |
| 39 | + } | |
| 40 | + return "" | |
| 41 | + } | |
| 42 | + | |
| 43 | + // The chunk splits in three: leading whitespace, text, trailing whitespace. | |
| 44 | + tail := text[len(body):] | |
| 45 | + visible := strings.TrimLeft(body, blanks) | |
| 46 | + lead := body[:len(body)-len(visible)] | |
| 47 | + | |
| 48 | + out := "" | |
| 49 | + if g.started { // before the first word, all whitespace is dropped | |
| 50 | + out = squeeze(g.held + lead) | |
| 51 | + } | |
| 52 | + g.held, g.started = tail, true | |
| 53 | + return out + visible | |
| 54 | +} | |
| 55 | + | |
| 56 | +// drop forgets the pending whitespace. Called when someone ELSE is about to | |
| 57 | +// write — a tool announcing its command: that whitespace belonged to the text | |
| 58 | +// before it, and printing it now would reopen the hole we just closed. | |
| 59 | +func (g *gap) drop() { | |
| 60 | + g.mu.Lock() | |
| 61 | + g.held = "" | |
| 62 | + g.mu.Unlock() | |
| 63 | +} | |
| 64 | + | |
| 65 | +// squeeze brings any run of line breaks down to two, that is ONE blank line at | |
| 66 | +// most. Spaces are left alone: they carry the indentation of a code block, and | |
| 67 | +// cutting it would shift the displayed code. | |
| 68 | +func squeeze(s string) string { | |
| 69 | + var b strings.Builder | |
| 70 | + run := 0 | |
| 71 | + for _, r := range s { | |
| 72 | + if r == '\n' { | |
| 73 | + run++ | |
| 74 | + if run > 2 { | |
| 75 | + continue | |
| 76 | + } | |
| 77 | + } else { | |
| 78 | + run = 0 | |
| 79 | + } | |
| 80 | + b.WriteRune(r) | |
| 81 | + } | |
| 82 | + return b.String() | |
| 83 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,83 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strings" | ||
| 5 | + "sync" | ||
| 6 | +) | ||
| 7 | + | ||
| 8 | +// blanks is the set of characters the model adds around its text without any of | ||
| 9 | +// it showing on screen. | ||
| 10 | +const blanks = " \t\r\n" | ||
| 11 | + | ||
| 12 | +// gap holds back the TRAILING whitespace of the streamed text: it is only | ||
| 13 | +// printed if visible text follows. Without that, the line breaks the model puts | ||
| 14 | +// after its sentence are printed as-is, and the screen hollows out. | ||
| 15 | +// | ||
| 16 | +// The model produces MORE AND MORE of it as the turns go by — it imitates its | ||
| 17 | +// own messages, which it re-reads in the history every turn. Measured: 2 blank | ||
| 18 | +// lines before the first 🛠️, 4 before the second, 7, then 11. Holding the | ||
| 19 | +// whitespace back is enough to remove all of it, since that whitespace is never | ||
| 20 | +// followed by text: it is a tool that writes next. | ||
| 21 | +type gap struct { | ||
| 22 | + // The `bash` tool may call drop() from SEVERAL goroutines — Genkit runs the | ||
| 23 | + // calls of a single turn in parallel (see printMu in tools). | ||
| 24 | + mu sync.Mutex | ||
| 25 | + held string // whitespace waiting to be followed by text | ||
| 26 | + started bool // visible text has already been printed | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +// next returns what should be printed for this chunk, "" when there is nothing | ||
| 30 | +// to print right now. | ||
| 31 | +func (g *gap) next(text string) string { | ||
| 32 | + g.mu.Lock() | ||
| 33 | + defer g.mu.Unlock() | ||
| 34 | + | ||
| 35 | + body := strings.TrimRight(text, blanks) | ||
| 36 | + if body == "" { // an all-whitespace chunk: set aside, not printed | ||
| 37 | + if g.started { | ||
| 38 | + g.held += text | ||
| 39 | + } | ||
| 40 | + return "" | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + // The chunk splits in three: leading whitespace, text, trailing whitespace. | ||
| 44 | + tail := text[len(body):] | ||
| 45 | + visible := strings.TrimLeft(body, blanks) | ||
| 46 | + lead := body[:len(body)-len(visible)] | ||
| 47 | + | ||
| 48 | + out := "" | ||
| 49 | + if g.started { // before the first word, all whitespace is dropped | ||
| 50 | + out = squeeze(g.held + lead) | ||
| 51 | + } | ||
| 52 | + g.held, g.started = tail, true | ||
| 53 | + return out + visible | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +// drop forgets the pending whitespace. Called when someone ELSE is about to | ||
| 57 | +// write — a tool announcing its command: that whitespace belonged to the text | ||
| 58 | +// before it, and printing it now would reopen the hole we just closed. | ||
| 59 | +func (g *gap) drop() { | ||
| 60 | + g.mu.Lock() | ||
| 61 | + g.held = "" | ||
| 62 | + g.mu.Unlock() | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +// squeeze brings any run of line breaks down to two, that is ONE blank line at | ||
| 66 | +// most. Spaces are left alone: they carry the indentation of a code block, and | ||
| 67 | +// cutting it would shift the displayed code. | ||
| 68 | +func squeeze(s string) string { | ||
| 69 | + var b strings.Builder | ||
| 70 | + run := 0 | ||
| 71 | + for _, r := range s { | ||
| 72 | + if r == '\n' { | ||
| 73 | + run++ | ||
| 74 | + if run > 2 { | ||
| 75 | + continue | ||
| 76 | + } | ||
| 77 | + } else { | ||
| 78 | + run = 0 | ||
| 79 | + } | ||
| 80 | + b.WriteRune(r) | ||
| 81 | + } | ||
| 82 | + return b.String() | ||
| 83 | +} | ||
added
internal/engine/history.go +172 -0 | new file mode 100644 | ||
| @@ -0,0 +1,172 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "encoding/json" | |
| 5 | + "fmt" | |
| 6 | + "slices" | |
| 7 | + "strings" | |
| 8 | + | |
| 9 | + "github.com/firebase/genkit/go/ai" | |
| 10 | +) | |
| 11 | + | |
| 12 | +// Names of the tools whose responses we count. They live here rather than | |
| 13 | +// scattered through the display code: the counter is a measurement, and a | |
| 14 | +// measurement needs a single definition. | |
| 15 | +const ( | |
| 16 | + toolBash = "bash" | |
| 17 | + toolSkill = "read_skill" | |
| 18 | + toolRead = "read_file" | |
| 19 | + toolWrite = "write_file" | |
| 20 | + toolEdit = "edit_file" | |
| 21 | + toolLSP = "lsp" | |
| 22 | +) | |
| 23 | + | |
| 24 | +// executed returns, in order, the text of the calls to a given tool that | |
| 25 | +// ACTUALLY ran. | |
| 26 | +// | |
| 27 | +// We start from the RESPONSES: a call the model asked for but which never ran | |
| 28 | +// (interrupted turn, maxTurns exceeded) produces none. The text of the call, on | |
| 29 | +// the other hand, is ONLY in the request — hence the pairing by Ref, the | |
| 30 | +// identifier the server gives to each call. | |
| 31 | +func executed(history []*ai.Message, name string) []string { | |
| 32 | + // Calls with no Ref (some servers do not set one) are paired in order, BUT | |
| 33 | + // only against the same tool name: a turn mixes `bash` and `read_skill`, and | |
| 34 | + // the first pending call is not necessarily for the right tool. | |
| 35 | + type call struct{ ref, name, text string } | |
| 36 | + var pending []call | |
| 37 | + var out []string | |
| 38 | + | |
| 39 | + for _, m := range history { | |
| 40 | + for _, p := range m.Content { | |
| 41 | + switch { | |
| 42 | + case p.IsToolRequest(): | |
| 43 | + pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name, commandText(p.ToolRequest)}) | |
| 44 | + | |
| 45 | + case p.IsToolResponse() && p.ToolResponse != nil && p.ToolResponse.Name == name: | |
| 46 | + ref := p.ToolResponse.Ref | |
| 47 | + i := slices.IndexFunc(pending, func(c call) bool { | |
| 48 | + if ref != "" { | |
| 49 | + return c.ref == ref | |
| 50 | + } | |
| 51 | + return c.name == name | |
| 52 | + }) | |
| 53 | + if i < 0 { // lost call: the name beats nothing | |
| 54 | + out = append(out, name) | |
| 55 | + continue | |
| 56 | + } | |
| 57 | + out = append(out, pending[i].text) | |
| 58 | + pending = slices.Delete(pending, i, i+1) | |
| 59 | + } | |
| 60 | + } | |
| 61 | + } | |
| 62 | + return out | |
| 63 | +} | |
| 64 | + | |
| 65 | +// commandText describes a tool call in one line. For `bash` it is the command | |
| 66 | +// itself — the rest is only wrapping; for any other tool, its name followed by | |
| 67 | +// its arguments. | |
| 68 | +func commandText(r *ai.ToolRequest) string { | |
| 69 | + if in, ok := r.Input.(map[string]any); ok { | |
| 70 | + if c, ok := in["command"].(string); ok && strings.TrimSpace(c) != "" { | |
| 71 | + return strings.TrimSpace(c) | |
| 72 | + } | |
| 73 | + } | |
| 74 | + args, err := json.Marshal(r.Input) | |
| 75 | + if err != nil || string(args) == "null" { | |
| 76 | + return r.Name | |
| 77 | + } | |
| 78 | + return r.Name + " " + string(args) | |
| 79 | +} | |
| 80 | + | |
| 81 | +// responses counts the responses of a given tool in a history. | |
| 82 | +func responses(history []*ai.Message, name string) int { | |
| 83 | + return len(executed(history, name)) | |
| 84 | +} | |
| 85 | + | |
| 86 | +// Commands counts the commands actually run in a history — one per response of | |
| 87 | +// the `bash` tool. It is the only reliable measure of the work done: a model | |
| 88 | +// that tells stories without acting produces a fine answer and a count of zero. | |
| 89 | +// | |
| 90 | +// The other tools do NOT count. Loading a skill runs nothing, and counting those | |
| 91 | +// reads would make the number say the opposite of what it is for: measured | |
| 92 | +// before the fix, a turn with two reads and a single command displayed | |
| 93 | +// "⚙ 3 command(s)". | |
| 94 | +func Commands(history []*ai.Message) int { | |
| 95 | + return responses(history, toolBash) | |
| 96 | +} | |
| 97 | + | |
| 98 | +// CommandList returns, in order, the text of the commands Commands counts — the | |
| 99 | +// one shown in the recap under the count when `displayCommands` is on. The count | |
| 100 | +// says HOW MANY, the list says WHAT. | |
| 101 | +func CommandList(history []*ai.Message) []string { | |
| 102 | + return executed(history, toolBash) | |
| 103 | +} | |
| 104 | + | |
| 105 | +// FileOps returns, in order, the file-tool calls that ran — read_file, | |
| 106 | +// write_file, edit_file — as one line each ("edit_file hello/main.go (2 edits)"). | |
| 107 | +// | |
| 108 | +// They are counted APART from the commands, not folded into them: this part | |
| 109 | +// compares editing through the `edit` CLI (one bash command per edit) with | |
| 110 | +// editing through built-in tools, and a recap that counted both as "commands" | |
| 111 | +// would hide the very difference being measured. `⚙ 3 command(s) · 📝 2 file | |
| 112 | +// op(s)` keeps the two columns readable side by side. | |
| 113 | +func FileOps(history []*ai.Message) []string { | |
| 114 | + return executedAny(history, toolRead, toolWrite, toolEdit) | |
| 115 | +} | |
| 116 | + | |
| 117 | +// executedAny is executed() across several tool names, keeping the order in | |
| 118 | +// which the responses appear — a per-name pass would lose the interleaving of | |
| 119 | +// a read followed by an edit. | |
| 120 | +func executedAny(history []*ai.Message, names ...string) []string { | |
| 121 | + type call struct{ ref, name, text string } | |
| 122 | + var pending []call | |
| 123 | + var out []string | |
| 124 | + isOurs := func(n string) bool { return slices.Contains(names, n) } | |
| 125 | + | |
| 126 | + for _, m := range history { | |
| 127 | + for _, p := range m.Content { | |
| 128 | + switch { | |
| 129 | + case p.IsToolRequest(): | |
| 130 | + pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name, fileOpText(p.ToolRequest)}) | |
| 131 | + case p.IsToolResponse() && p.ToolResponse != nil && isOurs(p.ToolResponse.Name): | |
| 132 | + ref, name := p.ToolResponse.Ref, p.ToolResponse.Name | |
| 133 | + i := slices.IndexFunc(pending, func(c call) bool { | |
| 134 | + if ref != "" { | |
| 135 | + return c.ref == ref | |
| 136 | + } | |
| 137 | + return c.name == name | |
| 138 | + }) | |
| 139 | + if i < 0 { | |
| 140 | + out = append(out, name) | |
| 141 | + continue | |
| 142 | + } | |
| 143 | + out = append(out, pending[i].text) | |
| 144 | + pending = slices.Delete(pending, i, i+1) | |
| 145 | + } | |
| 146 | + } | |
| 147 | + } | |
| 148 | + return out | |
| 149 | +} | |
| 150 | + | |
| 151 | +// fileOpText describes a file-tool call in one line: the tool, the path, and | |
| 152 | +// for edit_file the number of edits — never the texts themselves, which can | |
| 153 | +// run to dozens of lines and belong in the diff, not in the recap. | |
| 154 | +func fileOpText(r *ai.ToolRequest) string { | |
| 155 | + in, _ := r.Input.(map[string]any) | |
| 156 | + path, _ := in["path"].(string) | |
| 157 | + switch r.Name { | |
| 158 | + case toolEdit: | |
| 159 | + if edits, ok := in["edits"].([]any); ok { | |
| 160 | + return fmt.Sprintf("%s %s (%d edit(s))", r.Name, path, len(edits)) | |
| 161 | + } | |
| 162 | + case toolRead: | |
| 163 | + if s, ok := in["start"].(float64); ok && s > 0 { | |
| 164 | + e, _ := in["end"].(float64) | |
| 165 | + return fmt.Sprintf("%s %s %d-%d", r.Name, path, int(s), int(e)) | |
| 166 | + } | |
| 167 | + } | |
| 168 | + if path == "" { | |
| 169 | + return commandText(r) | |
| 170 | + } | |
| 171 | + return r.Name + " " + path | |
| 172 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,172 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "encoding/json" | ||
| 5 | + "fmt" | ||
| 6 | + "slices" | ||
| 7 | + "strings" | ||
| 8 | + | ||
| 9 | + "github.com/firebase/genkit/go/ai" | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | +// Names of the tools whose responses we count. They live here rather than | ||
| 13 | +// scattered through the display code: the counter is a measurement, and a | ||
| 14 | +// measurement needs a single definition. | ||
| 15 | +const ( | ||
| 16 | + toolBash = "bash" | ||
| 17 | + toolSkill = "read_skill" | ||
| 18 | + toolRead = "read_file" | ||
| 19 | + toolWrite = "write_file" | ||
| 20 | + toolEdit = "edit_file" | ||
| 21 | + toolLSP = "lsp" | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | +// executed returns, in order, the text of the calls to a given tool that | ||
| 25 | +// ACTUALLY ran. | ||
| 26 | +// | ||
| 27 | +// We start from the RESPONSES: a call the model asked for but which never ran | ||
| 28 | +// (interrupted turn, maxTurns exceeded) produces none. The text of the call, on | ||
| 29 | +// the other hand, is ONLY in the request — hence the pairing by Ref, the | ||
| 30 | +// identifier the server gives to each call. | ||
| 31 | +func executed(history []*ai.Message, name string) []string { | ||
| 32 | + // Calls with no Ref (some servers do not set one) are paired in order, BUT | ||
| 33 | + // only against the same tool name: a turn mixes `bash` and `read_skill`, and | ||
| 34 | + // the first pending call is not necessarily for the right tool. | ||
| 35 | + type call struct{ ref, name, text string } | ||
| 36 | + var pending []call | ||
| 37 | + var out []string | ||
| 38 | + | ||
| 39 | + for _, m := range history { | ||
| 40 | + for _, p := range m.Content { | ||
| 41 | + switch { | ||
| 42 | + case p.IsToolRequest(): | ||
| 43 | + pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name, commandText(p.ToolRequest)}) | ||
| 44 | + | ||
| 45 | + case p.IsToolResponse() && p.ToolResponse != nil && p.ToolResponse.Name == name: | ||
| 46 | + ref := p.ToolResponse.Ref | ||
| 47 | + i := slices.IndexFunc(pending, func(c call) bool { | ||
| 48 | + if ref != "" { | ||
| 49 | + return c.ref == ref | ||
| 50 | + } | ||
| 51 | + return c.name == name | ||
| 52 | + }) | ||
| 53 | + if i < 0 { // lost call: the name beats nothing | ||
| 54 | + out = append(out, name) | ||
| 55 | + continue | ||
| 56 | + } | ||
| 57 | + out = append(out, pending[i].text) | ||
| 58 | + pending = slices.Delete(pending, i, i+1) | ||
| 59 | + } | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + return out | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +// commandText describes a tool call in one line. For `bash` it is the command | ||
| 66 | +// itself — the rest is only wrapping; for any other tool, its name followed by | ||
| 67 | +// its arguments. | ||
| 68 | +func commandText(r *ai.ToolRequest) string { | ||
| 69 | + if in, ok := r.Input.(map[string]any); ok { | ||
| 70 | + if c, ok := in["command"].(string); ok && strings.TrimSpace(c) != "" { | ||
| 71 | + return strings.TrimSpace(c) | ||
| 72 | + } | ||
| 73 | + } | ||
| 74 | + args, err := json.Marshal(r.Input) | ||
| 75 | + if err != nil || string(args) == "null" { | ||
| 76 | + return r.Name | ||
| 77 | + } | ||
| 78 | + return r.Name + " " + string(args) | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +// responses counts the responses of a given tool in a history. | ||
| 82 | +func responses(history []*ai.Message, name string) int { | ||
| 83 | + return len(executed(history, name)) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +// Commands counts the commands actually run in a history — one per response of | ||
| 87 | +// the `bash` tool. It is the only reliable measure of the work done: a model | ||
| 88 | +// that tells stories without acting produces a fine answer and a count of zero. | ||
| 89 | +// | ||
| 90 | +// The other tools do NOT count. Loading a skill runs nothing, and counting those | ||
| 91 | +// reads would make the number say the opposite of what it is for: measured | ||
| 92 | +// before the fix, a turn with two reads and a single command displayed | ||
| 93 | +// "⚙ 3 command(s)". | ||
| 94 | +func Commands(history []*ai.Message) int { | ||
| 95 | + return responses(history, toolBash) | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +// CommandList returns, in order, the text of the commands Commands counts — the | ||
| 99 | +// one shown in the recap under the count when `displayCommands` is on. The count | ||
| 100 | +// says HOW MANY, the list says WHAT. | ||
| 101 | +func CommandList(history []*ai.Message) []string { | ||
| 102 | + return executed(history, toolBash) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +// FileOps returns, in order, the file-tool calls that ran — read_file, | ||
| 106 | +// write_file, edit_file — as one line each ("edit_file hello/main.go (2 edits)"). | ||
| 107 | +// | ||
| 108 | +// They are counted APART from the commands, not folded into them: this part | ||
| 109 | +// compares editing through the `edit` CLI (one bash command per edit) with | ||
| 110 | +// editing through built-in tools, and a recap that counted both as "commands" | ||
| 111 | +// would hide the very difference being measured. `⚙ 3 command(s) · 📝 2 file | ||
| 112 | +// op(s)` keeps the two columns readable side by side. | ||
| 113 | +func FileOps(history []*ai.Message) []string { | ||
| 114 | + return executedAny(history, toolRead, toolWrite, toolEdit) | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +// executedAny is executed() across several tool names, keeping the order in | ||
| 118 | +// which the responses appear — a per-name pass would lose the interleaving of | ||
| 119 | +// a read followed by an edit. | ||
| 120 | +func executedAny(history []*ai.Message, names ...string) []string { | ||
| 121 | + type call struct{ ref, name, text string } | ||
| 122 | + var pending []call | ||
| 123 | + var out []string | ||
| 124 | + isOurs := func(n string) bool { return slices.Contains(names, n) } | ||
| 125 | + | ||
| 126 | + for _, m := range history { | ||
| 127 | + for _, p := range m.Content { | ||
| 128 | + switch { | ||
| 129 | + case p.IsToolRequest(): | ||
| 130 | + pending = append(pending, call{p.ToolRequest.Ref, p.ToolRequest.Name, fileOpText(p.ToolRequest)}) | ||
| 131 | + case p.IsToolResponse() && p.ToolResponse != nil && isOurs(p.ToolResponse.Name): | ||
| 132 | + ref, name := p.ToolResponse.Ref, p.ToolResponse.Name | ||
| 133 | + i := slices.IndexFunc(pending, func(c call) bool { | ||
| 134 | + if ref != "" { | ||
| 135 | + return c.ref == ref | ||
| 136 | + } | ||
| 137 | + return c.name == name | ||
| 138 | + }) | ||
| 139 | + if i < 0 { | ||
| 140 | + out = append(out, name) | ||
| 141 | + continue | ||
| 142 | + } | ||
| 143 | + out = append(out, pending[i].text) | ||
| 144 | + pending = slices.Delete(pending, i, i+1) | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + } | ||
| 148 | + return out | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +// fileOpText describes a file-tool call in one line: the tool, the path, and | ||
| 152 | +// for edit_file the number of edits — never the texts themselves, which can | ||
| 153 | +// run to dozens of lines and belong in the diff, not in the recap. | ||
| 154 | +func fileOpText(r *ai.ToolRequest) string { | ||
| 155 | + in, _ := r.Input.(map[string]any) | ||
| 156 | + path, _ := in["path"].(string) | ||
| 157 | + switch r.Name { | ||
| 158 | + case toolEdit: | ||
| 159 | + if edits, ok := in["edits"].([]any); ok { | ||
| 160 | + return fmt.Sprintf("%s %s (%d edit(s))", r.Name, path, len(edits)) | ||
| 161 | + } | ||
| 162 | + case toolRead: | ||
| 163 | + if s, ok := in["start"].(float64); ok && s > 0 { | ||
| 164 | + e, _ := in["end"].(float64) | ||
| 165 | + return fmt.Sprintf("%s %s %d-%d", r.Name, path, int(s), int(e)) | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + if path == "" { | ||
| 169 | + return commandText(r) | ||
| 170 | + } | ||
| 171 | + return r.Name + " " + path | ||
| 172 | +} | ||
modified
internal/engine/openai.go +24 -14 | @@ -4,6 +4,7 @@ import ( | ||
| 4 | 4 | "context" |
| 5 | 5 | "encoding/json" |
| 6 | 6 | "fmt" |
| 7 | + "io" | |
| 7 | 8 | "net/http" |
| 8 | 9 | ) |
| 9 | 10 | |
| @@ -47,12 +48,7 @@ func init() { | ||
| 47 | 48 | // "nothing answers". 401 / 403 = the server is there and refused the key; |
| 48 | 49 | // 200 = there, and the model is looked for in its list. |
| 49 | 50 | func probeOpenAI(ctx context.Context, b Backend) Info { |
| 50 | - req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.BaseURL+"/models", nil) | |
| 51 | - if err != nil { | |
| 52 | - return Info{} | |
| 53 | - } | |
| 54 | - req.Header.Set("Authorization", "Bearer "+b.APIKey) | |
| 55 | - resp, err := probeClient.Do(req) | |
| 51 | + resp, err := getModelList(ctx, b) | |
| 56 | 52 | if err != nil { |
| 57 | 53 | return Info{} |
| 58 | 54 | } |
| @@ -61,25 +57,39 @@ func probeOpenAI(ctx context.Context, b Backend) Info { | ||
| 61 | 57 | case http.StatusUnauthorized, http.StatusForbidden: |
| 62 | 58 | return Info{Reachable: true, Warnings: []string{fmt.Sprintf("%s: %s refused the key (HTTP %d) — export %s", b.Provider, b.BaseURL, resp.StatusCode, keyVariable(b))}} |
| 63 | 59 | case http.StatusOK: |
| 64 | - default: | |
| 65 | - return Info{} | |
| 60 | + return Info{Reachable: true, Warnings: unlistedModel(resp.Body, b)} | |
| 61 | + } | |
| 62 | + return Info{} | |
| 63 | +} | |
| 64 | + | |
| 65 | +// getModelList sends GET <base>/models with the key. | |
| 66 | +func getModelList(ctx context.Context, b Backend) (*http.Response, error) { | |
| 67 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.BaseURL+"/models", nil) | |
| 68 | + if err != nil { | |
| 69 | + return nil, err | |
| 66 | 70 | } |
| 71 | + req.Header.Set("Authorization", "Bearer "+b.APIKey) | |
| 72 | + return probeClient.Do(req) | |
| 73 | +} | |
| 74 | + | |
| 75 | +// unlistedModel is the warning for a model the server's list leaves out; | |
| 76 | +// none when the list is unreadable or empty (a server that lists nothing | |
| 77 | +// proves nothing). | |
| 78 | +func unlistedModel(body io.Reader, b Backend) []string { | |
| 67 | 79 | var list struct { |
| 68 | 80 | Data []struct { |
| 69 | 81 | ID string `json:"id"` |
| 70 | 82 | } `json:"data"` |
| 71 | 83 | } |
| 72 | - info := Info{Reachable: true} | |
| 73 | - if json.NewDecoder(resp.Body).Decode(&list) != nil || len(list.Data) == 0 { | |
| 74 | - return info | |
| 84 | + if json.NewDecoder(body).Decode(&list) != nil || len(list.Data) == 0 { | |
| 85 | + return nil | |
| 75 | 86 | } |
| 76 | 87 | for _, m := range list.Data { |
| 77 | 88 | if m.ID == b.Model { |
| 78 | - return info | |
| 89 | + return nil | |
| 79 | 90 | } |
| 80 | 91 | } |
| 81 | - info.Warnings = append(info.Warnings, fmt.Sprintf("%s: model %q is not in the server's list (GET %s/models)", b.Provider, b.Model, b.BaseURL)) | |
| 82 | - return info | |
| 92 | + return []string{fmt.Sprintf("%s: model %q is not in the server's list (GET %s/models)", b.Provider, b.Model, b.BaseURL)} | |
| 83 | 93 | } |
| 84 | 94 | |
| 85 | 95 | // keyVariable names the variable the key is read from, for a message. |
| @@ -4,6 +4,7 @@ import ( | |||
| 4 | "context" | 4 | "context" |
| 5 | "encoding/json" | 5 | "encoding/json" |
| 6 | "fmt" | 6 | "fmt" |
| 7 | + "io" | ||
| 7 | "net/http" | 8 | "net/http" |
| 8 | ) | 9 | ) |
| 9 | 10 | ||
| @@ -47,12 +48,7 @@ func init() { | |||
| 47 | // "nothing answers". 401 / 403 = the server is there and refused the key; | 48 | // "nothing answers". 401 / 403 = the server is there and refused the key; |
| 48 | // 200 = there, and the model is looked for in its list. | 49 | // 200 = there, and the model is looked for in its list. |
| 49 | func probeOpenAI(ctx context.Context, b Backend) Info { | 50 | func probeOpenAI(ctx context.Context, b Backend) Info { |
| 50 | - req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.BaseURL+"/models", nil) | 51 | + resp, err := getModelList(ctx, b) |
| 51 | - if err != nil { | ||
| 52 | - return Info{} | ||
| 53 | - } | ||
| 54 | - req.Header.Set("Authorization", "Bearer "+b.APIKey) | ||
| 55 | - resp, err := probeClient.Do(req) | ||
| 56 | if err != nil { | 52 | if err != nil { |
| 57 | return Info{} | 53 | return Info{} |
| 58 | } | 54 | } |
| @@ -61,25 +57,39 @@ func probeOpenAI(ctx context.Context, b Backend) Info { | |||
| 61 | case http.StatusUnauthorized, http.StatusForbidden: | 57 | case http.StatusUnauthorized, http.StatusForbidden: |
| 62 | return Info{Reachable: true, Warnings: []string{fmt.Sprintf("%s: %s refused the key (HTTP %d) — export %s", b.Provider, b.BaseURL, resp.StatusCode, keyVariable(b))}} | 58 | return Info{Reachable: true, Warnings: []string{fmt.Sprintf("%s: %s refused the key (HTTP %d) — export %s", b.Provider, b.BaseURL, resp.StatusCode, keyVariable(b))}} |
| 63 | case http.StatusOK: | 59 | case http.StatusOK: |
| 64 | - default: | 60 | + return Info{Reachable: true, Warnings: unlistedModel(resp.Body, b)} |
| 65 | - return Info{} | 61 | + } |
| 62 | + return Info{} | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +// getModelList sends GET <base>/models with the key. | ||
| 66 | +func getModelList(ctx context.Context, b Backend) (*http.Response, error) { | ||
| 67 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.BaseURL+"/models", nil) | ||
| 68 | + if err != nil { | ||
| 69 | + return nil, err | ||
| 66 | } | 70 | } |
| 71 | + req.Header.Set("Authorization", "Bearer "+b.APIKey) | ||
| 72 | + return probeClient.Do(req) | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +// unlistedModel is the warning for a model the server's list leaves out; | ||
| 76 | +// none when the list is unreadable or empty (a server that lists nothing | ||
| 77 | +// proves nothing). | ||
| 78 | +func unlistedModel(body io.Reader, b Backend) []string { | ||
| 67 | var list struct { | 79 | var list struct { |
| 68 | Data []struct { | 80 | Data []struct { |
| 69 | ID string `json:"id"` | 81 | ID string `json:"id"` |
| 70 | } `json:"data"` | 82 | } `json:"data"` |
| 71 | } | 83 | } |
| 72 | - info := Info{Reachable: true} | 84 | + if json.NewDecoder(body).Decode(&list) != nil || len(list.Data) == 0 { |
| 73 | - if json.NewDecoder(resp.Body).Decode(&list) != nil || len(list.Data) == 0 { | 85 | + return nil |
| 74 | - return info | ||
| 75 | } | 86 | } |
| 76 | for _, m := range list.Data { | 87 | for _, m := range list.Data { |
| 77 | if m.ID == b.Model { | 88 | if m.ID == b.Model { |
| 78 | - return info | 89 | + return nil |
| 79 | } | 90 | } |
| 80 | } | 91 | } |
| 81 | - info.Warnings = append(info.Warnings, fmt.Sprintf("%s: model %q is not in the server's list (GET %s/models)", b.Provider, b.Model, b.BaseURL)) | 92 | + return []string{fmt.Sprintf("%s: model %q is not in the server's list (GET %s/models)", b.Provider, b.Model, b.BaseURL)} |
| 82 | - return info | ||
| 83 | } | 93 | } |
| 84 | 94 | ||
| 85 | // keyVariable names the variable the key is read from, for a message. | 95 | // keyVariable names the variable the key is read from, for a message. |
modified
internal/engine/pull.go +46 -20 | @@ -99,18 +99,24 @@ func ensureModel(ctx context.Context, p Provider, b Backend, progress func(PullP | ||
| 99 | 99 | if err != nil { |
| 100 | 100 | return false, ErrServerDown |
| 101 | 101 | } |
| 102 | - if listed { | |
| 103 | - return false, nil | |
| 104 | - } | |
| 105 | - if compat.pull == nil { | |
| 106 | - if compat.noPull != "" { | |
| 107 | - return false, fmt.Errorf("%w — %s", ErrCannotPull, compat.noPull) | |
| 108 | - } | |
| 109 | - return false, ErrCannotPull | |
| 102 | + if listed || compat.pull == nil { | |
| 103 | + return false, compat.cannotPull(listed) | |
| 110 | 104 | } |
| 111 | 105 | return true, compat.pull(ctx, b, b.Model, progress) |
| 112 | 106 | } |
| 113 | 107 | |
| 108 | +// cannotPull is nil for a model the server already lists, else | |
| 109 | +// ErrCannotPull with the provider's advice when it has some. | |
| 110 | +func (p *openaiCompat) cannotPull(listed bool) error { | |
| 111 | + switch { | |
| 112 | + case listed: | |
| 113 | + return nil | |
| 114 | + case p.noPull != "": | |
| 115 | + return fmt.Errorf("%w — %s", ErrCannotPull, p.noPull) | |
| 116 | + } | |
| 117 | + return ErrCannotPull | |
| 118 | +} | |
| 119 | + | |
| 114 | 120 | // serverLists reports whether GET <base>/models lists model. A name without |
| 115 | 121 | // a tag also matches its ":latest" entry: Ollama and Docker Model Runner |
| 116 | 122 | // list `qwen3.5` as `qwen3.5:latest`, and pulling it again would be a no-op |
| @@ -200,28 +206,51 @@ func readPullStream(r io.Reader, model string, progress func(PullProgress)) erro | ||
| 200 | 206 | // stream said, the pull counts as done only when the runner then LISTS the |
| 201 | 207 | // model: the confirmation does not depend on the stream's exact format. |
| 202 | 208 | func pullDMR(ctx context.Context, b Backend, model string, progress func(PullProgress)) error { |
| 203 | - body, err := json.Marshal(map[string]string{"from": model}) | |
| 209 | + resp, err := startDMRPull(ctx, b, model) | |
| 204 | 210 | if err != nil { |
| 205 | 211 | return err |
| 206 | 212 | } |
| 207 | - req, err := http.NewRequestWithContext(ctx, http.MethodPost, dmrRoot(b.BaseURL)+"/models/create", strings.NewReader(string(body))) | |
| 213 | + defer func() { _ = resp.Body.Close() }() | |
| 214 | + last, err := readDMRStream(resp.Body, model, progress) | |
| 215 | + if err == nil { | |
| 216 | + err = checkPulled(ctx, b, model, last) | |
| 217 | + } | |
| 208 | 218 | if err != nil { |
| 209 | 219 | return err |
| 210 | 220 | } |
| 221 | + if progress != nil { | |
| 222 | + progress(PullProgress{Model: model, Status: "success"}) | |
| 223 | + } | |
| 224 | + return nil | |
| 225 | +} | |
| 226 | + | |
| 227 | +// startDMRPull posts the pull to the runner and returns its streamed answer | |
| 228 | +// once the runner accepted it (2xx). | |
| 229 | +func startDMRPull(ctx context.Context, b Backend, model string) (*http.Response, error) { | |
| 230 | + body, err := json.Marshal(map[string]string{"from": model}) | |
| 231 | + if err != nil { | |
| 232 | + return nil, err | |
| 233 | + } | |
| 234 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, dmrRoot(b.BaseURL)+"/models/create", strings.NewReader(string(body))) | |
| 235 | + if err != nil { | |
| 236 | + return nil, err | |
| 237 | + } | |
| 211 | 238 | req.Header.Set("Content-Type", "application/json") |
| 212 | 239 | resp, err := pullClient.Do(req) |
| 213 | 240 | if err != nil { |
| 214 | - return fmt.Errorf("the server cannot be reached: %w", err) | |
| 241 | + return nil, fmt.Errorf("the server cannot be reached: %w", err) | |
| 215 | 242 | } |
| 216 | - defer func() { _ = resp.Body.Close() }() | |
| 217 | 243 | if resp.StatusCode/100 != 2 { |
| 244 | + defer func() { _ = resp.Body.Close() }() | |
| 218 | 245 | text, _ := io.ReadAll(io.LimitReader(resp.Body, 300)) |
| 219 | - return &httpStatusError{code: resp.StatusCode, body: strings.TrimSpace(string(text))} | |
| 220 | - } | |
| 221 | - last, err := readDMRStream(resp.Body, model, progress) | |
| 222 | - if err != nil { | |
| 223 | - return err | |
| 246 | + return nil, &httpStatusError{code: resp.StatusCode, body: strings.TrimSpace(string(text))} | |
| 224 | 247 | } |
| 248 | + return resp, nil | |
| 249 | +} | |
| 250 | + | |
| 251 | +// checkPulled confirms the download: the runner now lists the model (last | |
| 252 | +// is the stream's last status, for the message). | |
| 253 | +func checkPulled(ctx context.Context, b Backend, model, last string) error { | |
| 225 | 254 | listed, err := serverLists(ctx, b, model) |
| 226 | 255 | switch { |
| 227 | 256 | case err != nil: |
| @@ -229,9 +258,6 @@ func pullDMR(ctx context.Context, b Backend, model string, progress func(PullPro | ||
| 229 | 258 | case !listed: |
| 230 | 259 | return fmt.Errorf("the download ended (%q), but the server does not list %s", last, model) |
| 231 | 260 | } |
| 232 | - if progress != nil { | |
| 233 | - progress(PullProgress{Model: model, Status: "success"}) | |
| 234 | - } | |
| 235 | 261 | return nil |
| 236 | 262 | } |
| 237 | 263 | |
| @@ -99,18 +99,24 @@ func ensureModel(ctx context.Context, p Provider, b Backend, progress func(PullP | |||
| 99 | if err != nil { | 99 | if err != nil { |
| 100 | return false, ErrServerDown | 100 | return false, ErrServerDown |
| 101 | } | 101 | } |
| 102 | - if listed { | 102 | + if listed || compat.pull == nil { |
| 103 | - return false, nil | 103 | + return false, compat.cannotPull(listed) |
| 104 | - } | ||
| 105 | - if compat.pull == nil { | ||
| 106 | - if compat.noPull != "" { | ||
| 107 | - return false, fmt.Errorf("%w — %s", ErrCannotPull, compat.noPull) | ||
| 108 | - } | ||
| 109 | - return false, ErrCannotPull | ||
| 110 | } | 104 | } |
| 111 | return true, compat.pull(ctx, b, b.Model, progress) | 105 | return true, compat.pull(ctx, b, b.Model, progress) |
| 112 | } | 106 | } |
| 113 | 107 | ||
| 108 | +// cannotPull is nil for a model the server already lists, else | ||
| 109 | +// ErrCannotPull with the provider's advice when it has some. | ||
| 110 | +func (p *openaiCompat) cannotPull(listed bool) error { | ||
| 111 | + switch { | ||
| 112 | + case listed: | ||
| 113 | + return nil | ||
| 114 | + case p.noPull != "": | ||
| 115 | + return fmt.Errorf("%w — %s", ErrCannotPull, p.noPull) | ||
| 116 | + } | ||
| 117 | + return ErrCannotPull | ||
| 118 | +} | ||
| 119 | + | ||
| 114 | // serverLists reports whether GET <base>/models lists model. A name without | 120 | // serverLists reports whether GET <base>/models lists model. A name without |
| 115 | // a tag also matches its ":latest" entry: Ollama and Docker Model Runner | 121 | // a tag also matches its ":latest" entry: Ollama and Docker Model Runner |
| 116 | // list `qwen3.5` as `qwen3.5:latest`, and pulling it again would be a no-op | 122 | // list `qwen3.5` as `qwen3.5:latest`, and pulling it again would be a no-op |
| @@ -200,28 +206,51 @@ func readPullStream(r io.Reader, model string, progress func(PullProgress)) erro | |||
| 200 | // stream said, the pull counts as done only when the runner then LISTS the | 206 | // stream said, the pull counts as done only when the runner then LISTS the |
| 201 | // model: the confirmation does not depend on the stream's exact format. | 207 | // model: the confirmation does not depend on the stream's exact format. |
| 202 | func pullDMR(ctx context.Context, b Backend, model string, progress func(PullProgress)) error { | 208 | func pullDMR(ctx context.Context, b Backend, model string, progress func(PullProgress)) error { |
| 203 | - body, err := json.Marshal(map[string]string{"from": model}) | 209 | + resp, err := startDMRPull(ctx, b, model) |
| 204 | if err != nil { | 210 | if err != nil { |
| 205 | return err | 211 | return err |
| 206 | } | 212 | } |
| 207 | - req, err := http.NewRequestWithContext(ctx, http.MethodPost, dmrRoot(b.BaseURL)+"/models/create", strings.NewReader(string(body))) | 213 | + defer func() { _ = resp.Body.Close() }() |
| 214 | + last, err := readDMRStream(resp.Body, model, progress) | ||
| 215 | + if err == nil { | ||
| 216 | + err = checkPulled(ctx, b, model, last) | ||
| 217 | + } | ||
| 208 | if err != nil { | 218 | if err != nil { |
| 209 | return err | 219 | return err |
| 210 | } | 220 | } |
| 221 | + if progress != nil { | ||
| 222 | + progress(PullProgress{Model: model, Status: "success"}) | ||
| 223 | + } | ||
| 224 | + return nil | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +// startDMRPull posts the pull to the runner and returns its streamed answer | ||
| 228 | +// once the runner accepted it (2xx). | ||
| 229 | +func startDMRPull(ctx context.Context, b Backend, model string) (*http.Response, error) { | ||
| 230 | + body, err := json.Marshal(map[string]string{"from": model}) | ||
| 231 | + if err != nil { | ||
| 232 | + return nil, err | ||
| 233 | + } | ||
| 234 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, dmrRoot(b.BaseURL)+"/models/create", strings.NewReader(string(body))) | ||
| 235 | + if err != nil { | ||
| 236 | + return nil, err | ||
| 237 | + } | ||
| 211 | req.Header.Set("Content-Type", "application/json") | 238 | req.Header.Set("Content-Type", "application/json") |
| 212 | resp, err := pullClient.Do(req) | 239 | resp, err := pullClient.Do(req) |
| 213 | if err != nil { | 240 | if err != nil { |
| 214 | - return fmt.Errorf("the server cannot be reached: %w", err) | 241 | + return nil, fmt.Errorf("the server cannot be reached: %w", err) |
| 215 | } | 242 | } |
| 216 | - defer func() { _ = resp.Body.Close() }() | ||
| 217 | if resp.StatusCode/100 != 2 { | 243 | if resp.StatusCode/100 != 2 { |
| 244 | + defer func() { _ = resp.Body.Close() }() | ||
| 218 | text, _ := io.ReadAll(io.LimitReader(resp.Body, 300)) | 245 | text, _ := io.ReadAll(io.LimitReader(resp.Body, 300)) |
| 219 | - return &httpStatusError{code: resp.StatusCode, body: strings.TrimSpace(string(text))} | 246 | + return nil, &httpStatusError{code: resp.StatusCode, body: strings.TrimSpace(string(text))} |
| 220 | - } | ||
| 221 | - last, err := readDMRStream(resp.Body, model, progress) | ||
| 222 | - if err != nil { | ||
| 223 | - return err | ||
| 224 | } | 247 | } |
| 248 | + return resp, nil | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +// checkPulled confirms the download: the runner now lists the model (last | ||
| 252 | +// is the stream's last status, for the message). | ||
| 253 | +func checkPulled(ctx context.Context, b Backend, model, last string) error { | ||
| 225 | listed, err := serverLists(ctx, b, model) | 254 | listed, err := serverLists(ctx, b, model) |
| 226 | switch { | 255 | switch { |
| 227 | case err != nil: | 256 | case err != nil: |
| @@ -229,9 +258,6 @@ func pullDMR(ctx context.Context, b Backend, model string, progress func(PullPro | |||
| 229 | case !listed: | 258 | case !listed: |
| 230 | return fmt.Errorf("the download ended (%q), but the server does not list %s", last, model) | 259 | return fmt.Errorf("the download ended (%q), but the server does not list %s", last, model) |
| 231 | } | 260 | } |
| 232 | - if progress != nil { | ||
| 233 | - progress(PullProgress{Model: model, Status: "success"}) | ||
| 234 | - } | ||
| 235 | return nil | 261 | return nil |
| 236 | } | 262 | } |
| 237 | 263 | ||
modified
internal/engine/reasoning.go +34 -23 | @@ -101,12 +101,10 @@ func reasoningTap(req *http.Request, next option.MiddlewareNext) (*http.Response | ||
| 101 | 101 | progress := promptProgressFrom(req.Context()) |
| 102 | 102 | speed := speedFrom(req.Context()) |
| 103 | 103 | resp, err := next(req) |
| 104 | - if (on == nil && errs == nil && progress == nil && speed == nil) || err != nil || resp == nil || resp.Body == nil { | |
| 104 | + listened := on != nil || errs != nil || progress != nil || speed != nil | |
| 105 | + if !listened || !isEventStream(resp, err) { | |
| 105 | 106 | return resp, err |
| 106 | 107 | } |
| 107 | - if !strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { | |
| 108 | - return resp, nil | |
| 109 | - } | |
| 110 | 108 | tap := &sseTap{rc: resp.Body, on: on, onProgress: progress, speed: speed} |
| 111 | 109 | if speed != nil { |
| 112 | 110 | speed.begin() |
| @@ -118,6 +116,13 @@ func reasoningTap(req *http.Request, next option.MiddlewareNext) (*http.Response | ||
| 118 | 116 | return resp, nil |
| 119 | 117 | } |
| 120 | 118 | |
| 119 | +// isEventStream tells whether a call answered with a stream of events (SSE) | |
| 120 | +// the tap can read. | |
| 121 | +func isEventStream(resp *http.Response, err error) bool { | |
| 122 | + return err == nil && resp != nil && resp.Body != nil && | |
| 123 | + strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") | |
| 124 | +} | |
| 125 | + | |
| 121 | 126 | // maxSSELine caps the line buffer. A server that never sends a newline must |
| 122 | 127 | // not grow it without end; 1 MiB is far past any real chunk. |
| 123 | 128 | const maxSSELine = 1 << 20 |
| @@ -160,27 +165,33 @@ func (t *sseTap) scan(b []byte) { | ||
| 160 | 165 | } |
| 161 | 166 | line := string(t.buf[:i]) |
| 162 | 167 | t.buf = t.buf[i+1:] |
| 163 | - if t.speed != nil { | |
| 164 | - t.speed.line(line, time.Now()) | |
| 165 | - } | |
| 166 | - if msg := serverErrorOf(line); msg != "" { | |
| 167 | - if t.onErr != nil { | |
| 168 | - t.onErr(msg) | |
| 169 | - } | |
| 170 | - continue | |
| 171 | - } | |
| 172 | - if p, ok := promptProgressOf(line); ok { | |
| 173 | - if t.onProgress != nil { | |
| 174 | - t.onProgress(p) | |
| 175 | - } | |
| 176 | - continue | |
| 177 | - } | |
| 178 | - if t.on == nil { | |
| 179 | - continue | |
| 168 | + t.report(line) | |
| 169 | + } | |
| 170 | +} | |
| 171 | + | |
| 172 | +// report hands one SSE line to whoever listens: the speed meter, then the | |
| 173 | +// first of an error event, a prompt_progress chunk, or reasoning. | |
| 174 | +func (t *sseTap) report(line string) { | |
| 175 | + if t.speed != nil { | |
| 176 | + t.speed.line(line, time.Now()) | |
| 177 | + } | |
| 178 | + if msg := serverErrorOf(line); msg != "" { | |
| 179 | + if t.onErr != nil { | |
| 180 | + t.onErr(msg) | |
| 180 | 181 | } |
| 181 | - if text := reasoningOf(line); text != "" { | |
| 182 | - t.on(text) | |
| 182 | + return | |
| 183 | + } | |
| 184 | + if p, ok := promptProgressOf(line); ok { | |
| 185 | + if t.onProgress != nil { | |
| 186 | + t.onProgress(p) | |
| 183 | 187 | } |
| 188 | + return | |
| 189 | + } | |
| 190 | + if t.on == nil { | |
| 191 | + return | |
| 192 | + } | |
| 193 | + if text := reasoningOf(line); text != "" { | |
| 194 | + t.on(text) | |
| 184 | 195 | } |
| 185 | 196 | } |
| 186 | 197 | |
| @@ -101,12 +101,10 @@ func reasoningTap(req *http.Request, next option.MiddlewareNext) (*http.Response | |||
| 101 | progress := promptProgressFrom(req.Context()) | 101 | progress := promptProgressFrom(req.Context()) |
| 102 | speed := speedFrom(req.Context()) | 102 | speed := speedFrom(req.Context()) |
| 103 | resp, err := next(req) | 103 | resp, err := next(req) |
| 104 | - if (on == nil && errs == nil && progress == nil && speed == nil) || err != nil || resp == nil || resp.Body == nil { | 104 | + listened := on != nil || errs != nil || progress != nil || speed != nil |
| 105 | + if !listened || !isEventStream(resp, err) { | ||
| 105 | return resp, err | 106 | return resp, err |
| 106 | } | 107 | } |
| 107 | - if !strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { | ||
| 108 | - return resp, nil | ||
| 109 | - } | ||
| 110 | tap := &sseTap{rc: resp.Body, on: on, onProgress: progress, speed: speed} | 108 | tap := &sseTap{rc: resp.Body, on: on, onProgress: progress, speed: speed} |
| 111 | if speed != nil { | 109 | if speed != nil { |
| 112 | speed.begin() | 110 | speed.begin() |
| @@ -118,6 +116,13 @@ func reasoningTap(req *http.Request, next option.MiddlewareNext) (*http.Response | |||
| 118 | return resp, nil | 116 | return resp, nil |
| 119 | } | 117 | } |
| 120 | 118 | ||
| 119 | +// isEventStream tells whether a call answered with a stream of events (SSE) | ||
| 120 | +// the tap can read. | ||
| 121 | +func isEventStream(resp *http.Response, err error) bool { | ||
| 122 | + return err == nil && resp != nil && resp.Body != nil && | ||
| 123 | + strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") | ||
| 124 | +} | ||
| 125 | + | ||
| 121 | // maxSSELine caps the line buffer. A server that never sends a newline must | 126 | // maxSSELine caps the line buffer. A server that never sends a newline must |
| 122 | // not grow it without end; 1 MiB is far past any real chunk. | 127 | // not grow it without end; 1 MiB is far past any real chunk. |
| 123 | const maxSSELine = 1 << 20 | 128 | const maxSSELine = 1 << 20 |
| @@ -160,27 +165,33 @@ func (t *sseTap) scan(b []byte) { | |||
| 160 | } | 165 | } |
| 161 | line := string(t.buf[:i]) | 166 | line := string(t.buf[:i]) |
| 162 | t.buf = t.buf[i+1:] | 167 | t.buf = t.buf[i+1:] |
| 163 | - if t.speed != nil { | 168 | + t.report(line) |
| 164 | - t.speed.line(line, time.Now()) | 169 | + } |
| 165 | - } | 170 | +} |
| 166 | - if msg := serverErrorOf(line); msg != "" { | 171 | + |
| 167 | - if t.onErr != nil { | 172 | +// report hands one SSE line to whoever listens: the speed meter, then the |
| 168 | - t.onErr(msg) | 173 | +// first of an error event, a prompt_progress chunk, or reasoning. |
| 169 | - } | 174 | +func (t *sseTap) report(line string) { |
| 170 | - continue | 175 | + if t.speed != nil { |
| 171 | - } | 176 | + t.speed.line(line, time.Now()) |
| 172 | - if p, ok := promptProgressOf(line); ok { | 177 | + } |
| 173 | - if t.onProgress != nil { | 178 | + if msg := serverErrorOf(line); msg != "" { |
| 174 | - t.onProgress(p) | 179 | + if t.onErr != nil { |
| 175 | - } | 180 | + t.onErr(msg) |
| 176 | - continue | ||
| 177 | - } | ||
| 178 | - if t.on == nil { | ||
| 179 | - continue | ||
| 180 | } | 181 | } |
| 181 | - if text := reasoningOf(line); text != "" { | 182 | + return |
| 182 | - t.on(text) | 183 | + } |
| 184 | + if p, ok := promptProgressOf(line); ok { | ||
| 185 | + if t.onProgress != nil { | ||
| 186 | + t.onProgress(p) | ||
| 183 | } | 187 | } |
| 188 | + return | ||
| 189 | + } | ||
| 190 | + if t.on == nil { | ||
| 191 | + return | ||
| 192 | + } | ||
| 193 | + if text := reasoningOf(line); text != "" { | ||
| 194 | + t.on(text) | ||
| 184 | } | 195 | } |
| 185 | } | 196 | } |
| 186 | 197 | ||
modified
internal/engine/responses.go +18 -465 | @@ -1,11 +1,9 @@ | ||
| 1 | 1 | package engine |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | - "bufio" | |
| 5 | 4 | "bytes" |
| 6 | 5 | "context" |
| 7 | 6 | "encoding/json" |
| 8 | - "errors" | |
| 9 | 7 | "fmt" |
| 10 | 8 | "io" |
| 11 | 9 | "net/http" |
| @@ -126,479 +124,34 @@ func (r *responsesModel) post(ctx context.Context, body []byte) (*http.Response, | ||
| 126 | 124 | req.Header.Set("Content-Type", "application/json") |
| 127 | 125 | req.Header.Set("Authorization", "Bearer "+r.backend.APIKey) |
| 128 | 126 | req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } |
| 129 | - next := func(req *http.Request) (*http.Response, error) { return responsesClient.Do(req) } | |
| 130 | - for i := len(r.chain) - 1; i >= 0; i-- { | |
| 131 | - mw, inner := r.chain[i], next | |
| 132 | - next = func(req *http.Request) (*http.Response, error) { return mw(req, inner) } | |
| 127 | + resp, err := sendThrough(r.chain, req) | |
| 128 | + if err == nil { | |
| 129 | + err = httpFailure(url, resp) | |
| 133 | 130 | } |
| 134 | - resp, err := next(req) | |
| 135 | 131 | if err != nil { |
| 136 | 132 | return nil, err |
| 137 | 133 | } |
| 138 | - if resp.StatusCode/100 != 2 { | |
| 139 | - defer func() { _ = resp.Body.Close() }() | |
| 140 | - said, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) | |
| 141 | - return nil, fmt.Errorf("POST %q: %s %s", url, resp.Status, strings.TrimSpace(string(said))) | |
| 142 | - } | |
| 143 | 134 | return resp, nil |
| 144 | 135 | } |
| 145 | 136 | |
| 146 | -// responsesRequest builds the JSON body of one call. | |
| 147 | -// | |
| 148 | -// body, _ := responsesRequest("gpt-6-luna", req, true, false) | |
| 149 | -// // {"model":"gpt-6-luna","input":[…],"tools":[…],"stream":true,"store":false,"include":["reasoning.encrypted_content"],…} | |
| 150 | -func responsesRequest(model string, req *ai.ModelRequest, stream, noThink bool) ([]byte, error) { | |
| 151 | - m, err := samplingFields(req.Config) | |
| 152 | - if err != nil { | |
| 153 | - return nil, err | |
| 154 | - } | |
| 155 | - if noThink { | |
| 156 | - setReasoning(m, "effort", "none") | |
| 157 | - } | |
| 158 | - input, err := responsesInput(req.Messages) | |
| 159 | - if err != nil { | |
| 160 | - return nil, err | |
| 161 | - } | |
| 162 | - m["model"] = model | |
| 163 | - m["input"] = input | |
| 164 | - if len(req.Tools) > 0 { | |
| 165 | - m["tools"] = responsesTools(req.Tools) | |
| 166 | - } | |
| 167 | - if req.ToolChoice != "" { | |
| 168 | - m["tool_choice"] = string(req.ToolChoice) | |
| 169 | - } | |
| 170 | - if format := responsesFormat(req.Output); format != nil { | |
| 171 | - text, _ := m["text"].(map[string]any) | |
| 172 | - if text == nil { | |
| 173 | - text = map[string]any{} | |
| 174 | - } | |
| 175 | - text["format"] = format | |
| 176 | - m["text"] = text | |
| 177 | - } | |
| 178 | - m["stream"] = stream | |
| 179 | - if _, set := m["store"]; !set { | |
| 180 | - m["store"] = false | |
| 181 | - } | |
| 182 | - if _, set := m["include"]; !set && m["store"] == false { | |
| 183 | - m["include"] = []string{"reasoning.encrypted_content"} | |
| 184 | - } | |
| 185 | - return json.Marshal(m) | |
| 186 | -} | |
| 187 | - | |
| 188 | -// samplingFields is the request's config — the file's `sampling:` block — | |
| 189 | -// as the fields of a Responses request, written as they are except for the | |
| 190 | -// Chat Completions names this API spells differently: the answer limit | |
| 191 | -// (max_tokens, max_completion_tokens → max_output_tokens) and | |
| 192 | -// reasoning_effort (→ reasoning.effort). | |
| 193 | -func samplingFields(cfg any) (map[string]any, error) { | |
| 194 | - m := map[string]any{} | |
| 195 | - switch c := cfg.(type) { | |
| 196 | - case nil: | |
| 197 | - case map[string]any: | |
| 198 | - for k, v := range c { | |
| 199 | - m[k] = v | |
| 200 | - } | |
| 201 | - default: | |
| 202 | - raw, err := json.Marshal(c) | |
| 203 | - if err != nil { | |
| 204 | - return nil, fmt.Errorf("responses: config: %w", err) | |
| 205 | - } | |
| 206 | - if err := json.Unmarshal(raw, &m); err != nil { | |
| 207 | - return nil, fmt.Errorf("responses: config: %w", err) | |
| 208 | - } | |
| 209 | - } | |
| 210 | - for _, key := range []string{"max_completion_tokens", "max_tokens"} { | |
| 211 | - if v, ok := m[key]; ok { | |
| 212 | - if _, set := m["max_output_tokens"]; !set { | |
| 213 | - m["max_output_tokens"] = v | |
| 214 | - } | |
| 215 | - delete(m, key) | |
| 216 | - } | |
| 217 | - } | |
| 218 | - if v, ok := m["reasoning_effort"]; ok { | |
| 219 | - delete(m, "reasoning_effort") | |
| 220 | - if r, _ := m["reasoning"].(map[string]any); r == nil || r["effort"] == nil { | |
| 221 | - setReasoning(m, "effort", v) | |
| 222 | - } | |
| 223 | - } | |
| 224 | - return m, nil | |
| 225 | -} | |
| 226 | - | |
| 227 | -// setReasoning sets one field of the `reasoning` object, keeping the others. | |
| 228 | -func setReasoning(m map[string]any, key string, value any) { | |
| 229 | - r, _ := m["reasoning"].(map[string]any) | |
| 230 | - if r == nil { | |
| 231 | - r = map[string]any{} | |
| 232 | - } else { | |
| 233 | - copied := make(map[string]any, len(r)+1) | |
| 234 | - for k, v := range r { | |
| 235 | - copied[k] = v | |
| 236 | - } | |
| 237 | - r = copied | |
| 238 | - } | |
| 239 | - r[key] = value | |
| 240 | - m["reasoning"] = r | |
| 241 | -} | |
| 242 | - | |
| 243 | -// responsesInput turns Genkit's messages into Responses input items: | |
| 244 | -// system and user messages, the model's earlier answers (its reasoning | |
| 245 | -// items, its text, its function calls) and the tool results. | |
| 246 | -func responsesInput(messages []*ai.Message) ([]any, error) { | |
| 247 | - var items []any | |
| 248 | - for _, msg := range messages { | |
| 249 | - if msg == nil { | |
| 250 | - continue | |
| 251 | - } | |
| 252 | - switch msg.Role { | |
| 253 | - case ai.RoleSystem: | |
| 254 | - if text := msg.Text(); text != "" { | |
| 255 | - items = append(items, map[string]any{"role": "system", "content": text}) | |
| 256 | - } | |
| 257 | - case ai.RoleUser: | |
| 258 | - if content := userContent(msg.Content); len(content) > 0 { | |
| 259 | - items = append(items, map[string]any{"role": "user", "content": content}) | |
| 260 | - } | |
| 261 | - case ai.RoleModel: | |
| 262 | - modelItems, err := modelInput(msg) | |
| 263 | - if err != nil { | |
| 264 | - return nil, err | |
| 265 | - } | |
| 266 | - items = append(items, modelItems...) | |
| 267 | - case ai.RoleTool: | |
| 268 | - for _, p := range msg.Content { | |
| 269 | - if p == nil || !p.IsToolResponse() || p.ToolResponse == nil { | |
| 270 | - continue | |
| 271 | - } | |
| 272 | - out, err := responsesToolOutput(p.ToolResponse.Output) | |
| 273 | - if err != nil { | |
| 274 | - return nil, err | |
| 275 | - } | |
| 276 | - items = append(items, map[string]any{"type": "function_call_output", "call_id": callID(p.ToolResponse.Ref, p.ToolResponse.Name), "output": out}) | |
| 277 | - } | |
| 278 | - } | |
| 279 | - } | |
| 280 | - return items, nil | |
| 281 | -} | |
| 282 | - | |
| 283 | -// userContent is a user message's parts: text, and images by URL. | |
| 284 | -func userContent(parts []*ai.Part) []any { | |
| 285 | - var content []any | |
| 286 | - for _, p := range parts { | |
| 287 | - switch { | |
| 288 | - case p == nil: | |
| 289 | - case p.IsText(): | |
| 290 | - content = append(content, map[string]any{"type": "input_text", "text": p.Text}) | |
| 291 | - case p.IsMedia(): | |
| 292 | - content = append(content, map[string]any{"type": "input_image", "image_url": p.Text}) | |
| 293 | - } | |
| 294 | - } | |
| 295 | - return content | |
| 296 | -} | |
| 297 | - | |
| 298 | -// modelInput is one of the model's earlier answers, in the order the server | |
| 299 | -// produced them: reasoning, text, function calls. | |
| 300 | -func modelInput(msg *ai.Message) ([]any, error) { | |
| 301 | - var items []any | |
| 302 | - if raw, ok := msg.Metadata[responsesReasoningKey].([]any); ok { | |
| 303 | - items = append(items, raw...) | |
| 304 | - } | |
| 305 | - var text strings.Builder | |
| 306 | - for _, p := range msg.Content { | |
| 307 | - if p != nil && p.IsText() { | |
| 308 | - text.WriteString(p.Text) | |
| 309 | - } | |
| 310 | - } | |
| 311 | - if text.Len() > 0 { | |
| 312 | - items = append(items, map[string]any{"role": "assistant", "content": text.String()}) | |
| 313 | - } | |
| 314 | - for _, p := range msg.Content { | |
| 315 | - if p == nil || !p.IsToolRequest() || p.ToolRequest == nil { | |
| 316 | - continue | |
| 317 | - } | |
| 318 | - args, err := toolArguments(p.ToolRequest.Input) | |
| 319 | - if err != nil { | |
| 320 | - return nil, err | |
| 321 | - } | |
| 322 | - items = append(items, map[string]any{"type": "function_call", "call_id": callID(p.ToolRequest.Ref, p.ToolRequest.Name), "name": p.ToolRequest.Name, "arguments": args}) | |
| 323 | - } | |
| 324 | - return items, nil | |
| 325 | -} | |
| 326 | - | |
| 327 | -// callID is the call's id, the tool's name when Genkit has none (as | |
| 328 | -// compat_oai does). | |
| 329 | -func callID(ref, name string) string { | |
| 330 | - if ref != "" { | |
| 331 | - return ref | |
| 332 | - } | |
| 333 | - return name | |
| 334 | -} | |
| 335 | - | |
| 336 | -// toolArguments is a tool call's input as the JSON string the API wants. | |
| 337 | -func toolArguments(input any) (string, error) { | |
| 338 | - if s, ok := input.(string); ok { | |
| 339 | - return s, nil | |
| 340 | - } | |
| 341 | - if input == nil { | |
| 342 | - return "{}", nil | |
| 343 | - } | |
| 344 | - raw, err := json.Marshal(input) | |
| 345 | - if err != nil { | |
| 346 | - return "", fmt.Errorf("responses: tool arguments: %w", err) | |
| 347 | - } | |
| 348 | - return string(raw), nil | |
| 349 | -} | |
| 350 | - | |
| 351 | -// responsesToolOutput is a tool's result as a string: a string as is, anything else | |
| 352 | -// in JSON (what compat_oai sends as the tool message). | |
| 353 | -func responsesToolOutput(output any) (string, error) { | |
| 354 | - if s, ok := output.(string); ok { | |
| 355 | - return s, nil | |
| 356 | - } | |
| 357 | - raw, err := json.Marshal(output) | |
| 358 | - if err != nil { | |
| 359 | - return "", fmt.Errorf("responses: tool output: %w", err) | |
| 360 | - } | |
| 361 | - return string(raw), nil | |
| 362 | -} | |
| 363 | - | |
| 364 | -// responsesTools declares the tools as function tools, not strict: mm's | |
| 365 | -// schemas have optional properties, which strict mode refuses. | |
| 366 | -func responsesTools(tools []*ai.ToolDefinition) []any { | |
| 367 | - out := make([]any, 0, len(tools)) | |
| 368 | - for _, t := range tools { | |
| 369 | - if t == nil { | |
| 370 | - continue | |
| 371 | - } | |
| 372 | - params := t.InputSchema | |
| 373 | - if params == nil { | |
| 374 | - params = map[string]any{"type": "object", "properties": map[string]any{}} | |
| 375 | - } | |
| 376 | - out = append(out, map[string]any{"type": "function", "name": t.Name, "description": t.Description, "parameters": params, "strict": false}) | |
| 377 | - } | |
| 378 | - return out | |
| 379 | -} | |
| 380 | - | |
| 381 | -// responsesFormat is `text.format` for structuredOutput (ticket 80): the | |
| 382 | -// schema, strict as the openai provider sends it; nil for plain text. | |
| 383 | -func responsesFormat(output *ai.ModelOutputConfig) map[string]any { | |
| 384 | - if output == nil || output.Format != "json" { | |
| 385 | - return nil | |
| 386 | - } | |
| 387 | - if output.Schema == nil { | |
| 388 | - return map[string]any{"type": "json_object"} | |
| 389 | - } | |
| 390 | - return map[string]any{"type": "json_schema", "name": "output", "schema": output.Schema, "strict": true} | |
| 391 | -} | |
| 392 | - | |
| 393 | -// responsesResult is the little of a Responses answer mm reads. | |
| 394 | -type responsesResult struct { | |
| 395 | - Status string `json:"status"` | |
| 396 | - Output []json.RawMessage `json:"output"` | |
| 397 | - IncompleteDetails *struct { | |
| 398 | - Reason string `json:"reason"` | |
| 399 | - } `json:"incomplete_details"` | |
| 400 | - Error *struct { | |
| 401 | - Message string `json:"message"` | |
| 402 | - } `json:"error"` | |
| 403 | - Usage *struct { | |
| 404 | - InputTokens int `json:"input_tokens"` | |
| 405 | - OutputTokens int `json:"output_tokens"` | |
| 406 | - TotalTokens int `json:"total_tokens"` | |
| 407 | - InputTokensDetails struct { | |
| 408 | - CachedTokens int `json:"cached_tokens"` | |
| 409 | - } `json:"input_tokens_details"` | |
| 410 | - OutputTokensDetails struct { | |
| 411 | - ReasoningTokens int `json:"reasoning_tokens"` | |
| 412 | - } `json:"output_tokens_details"` | |
| 413 | - } `json:"usage"` | |
| 414 | -} | |
| 415 | - | |
| 416 | -// outputItem is one item of the answer's output. | |
| 417 | -type outputItem struct { | |
| 418 | - Type string `json:"type"` | |
| 419 | - CallID string `json:"call_id"` | |
| 420 | - Name string `json:"name"` | |
| 421 | - Arguments string `json:"arguments"` | |
| 422 | - Content []struct { | |
| 423 | - Type string `json:"type"` | |
| 424 | - Text string `json:"text"` | |
| 425 | - Refusal string `json:"refusal"` | |
| 426 | - } `json:"content"` | |
| 427 | -} | |
| 428 | - | |
| 429 | -// modelResponse turns the answer into Genkit's response. A failed answer is | |
| 430 | -// an error; tool arguments that do not parse are the error compat_oai gives | |
| 431 | -// ("could not parse tool args"), so the call is handed back to the model the | |
| 432 | -// same way (toolargs.go). | |
| 433 | -func (r *responsesResult) modelResponse() (*ai.ModelResponse, error) { | |
| 434 | - if r.Status == "failed" { | |
| 435 | - msg := "the response failed" | |
| 436 | - if r.Error != nil && r.Error.Message != "" { | |
| 437 | - msg = r.Error.Message | |
| 438 | - } | |
| 439 | - return nil, fmt.Errorf("stream error: %s", msg) | |
| 440 | - } | |
| 441 | - msg := &ai.Message{Role: ai.RoleModel, Content: []*ai.Part{}} | |
| 442 | - resp := &ai.ModelResponse{Message: msg, FinishReason: ai.FinishReasonStop} | |
| 443 | - var reasoning []any | |
| 444 | - var text strings.Builder | |
| 445 | - var calls []*ai.Part | |
| 446 | - for _, raw := range r.Output { | |
| 447 | - var item outputItem | |
| 448 | - if json.Unmarshal(raw, &item) != nil { | |
| 449 | - continue | |
| 450 | - } | |
| 451 | - switch item.Type { | |
| 452 | - case "reasoning": | |
| 453 | - var keep any | |
| 454 | - if json.Unmarshal(raw, &keep) == nil { | |
| 455 | - reasoning = append(reasoning, keep) | |
| 456 | - } | |
| 457 | - case "message": | |
| 458 | - for _, c := range item.Content { | |
| 459 | - switch c.Type { | |
| 460 | - case "output_text": | |
| 461 | - text.WriteString(c.Text) | |
| 462 | - case "refusal": | |
| 463 | - resp.FinishReason, resp.FinishMessage = ai.FinishReasonBlocked, c.Refusal | |
| 464 | - } | |
| 465 | - } | |
| 466 | - case "function_call": | |
| 467 | - input := map[string]any{} | |
| 468 | - if strings.TrimSpace(item.Arguments) != "" { | |
| 469 | - if err := json.Unmarshal([]byte(item.Arguments), &input); err != nil { | |
| 470 | - return nil, fmt.Errorf("could not parse tool args: %w", err) | |
| 471 | - } | |
| 472 | - } | |
| 473 | - calls = append(calls, ai.NewToolRequestPart(&ai.ToolRequest{Ref: item.CallID, Name: item.Name, Input: input})) | |
| 474 | - } | |
| 475 | - } | |
| 476 | - if text.Len() > 0 { | |
| 477 | - msg.Content = append(msg.Content, ai.NewTextPart(text.String())) | |
| 478 | - } | |
| 479 | - msg.Content = append(msg.Content, calls...) | |
| 480 | - if len(reasoning) > 0 { | |
| 481 | - msg.Metadata = map[string]any{responsesReasoningKey: reasoning} | |
| 482 | - } | |
| 483 | - if r.Status == "incomplete" && r.IncompleteDetails != nil { | |
| 484 | - switch r.IncompleteDetails.Reason { | |
| 485 | - case "max_output_tokens": | |
| 486 | - resp.FinishReason = ai.FinishReasonLength | |
| 487 | - case "content_filter": | |
| 488 | - resp.FinishReason = ai.FinishReasonBlocked | |
| 489 | - default: | |
| 490 | - resp.FinishReason, resp.FinishMessage = ai.FinishReasonOther, r.IncompleteDetails.Reason | |
| 491 | - } | |
| 492 | - } | |
| 493 | - if u := r.Usage; u != nil { | |
| 494 | - resp.Usage = &ai.GenerationUsage{ | |
| 495 | - InputTokens: u.InputTokens, | |
| 496 | - OutputTokens: u.OutputTokens, | |
| 497 | - TotalTokens: u.TotalTokens, | |
| 498 | - ThoughtsTokens: u.OutputTokensDetails.ReasoningTokens, | |
| 499 | - CachedContentTokens: u.InputTokensDetails.CachedTokens, | |
| 500 | - } | |
| 501 | - } | |
| 502 | - return resp, nil | |
| 503 | -} | |
| 504 | - | |
| 505 | -// responsesEvent is one streamed event: its type and the fields mm reads. | |
| 506 | -type responsesEvent struct { | |
| 507 | - Type string `json:"type"` | |
| 508 | - Delta string `json:"delta"` | |
| 509 | - ItemID string `json:"item_id"` | |
| 510 | - Message string `json:"message"` | |
| 511 | - Item *json.RawMessage `json:"item"` | |
| 512 | - Response *responsesResult `json:"response"` | |
| 513 | -} | |
| 514 | - | |
| 515 | -// readResponsesStream reads the SSE events of a streamed call: text deltas | |
| 516 | -// go to Genkit's callback, function-call argument deltas too (the runaway | |
| 517 | -// guard and the watchdog read them), reasoning to the turn's listener | |
| 518 | -// (reasoning.go). The answer is the one `response.completed` (or | |
| 519 | -// `response.incomplete`, `response.failed`) carries. A stream that ends | |
| 520 | -// without one broke: "stream error", which the model call retries once. | |
| 521 | -func readResponsesStream(ctx context.Context, body io.Reader, cb ai.ModelStreamCallback) (*responsesResult, error) { | |
| 522 | - onReasoning := reasoningFrom(ctx) | |
| 523 | - calls := map[string]*ai.ToolRequest{} // item id → name and call id | |
| 524 | - sc := bufio.NewScanner(body) | |
| 525 | - sc.Buffer(make([]byte, 64<<10), maxSSELine*8) | |
| 526 | - for sc.Scan() { | |
| 527 | - data, ok := strings.CutPrefix(strings.TrimSpace(sc.Text()), "data:") | |
| 528 | - if !ok { | |
| 529 | - continue | |
| 530 | - } | |
| 531 | - data = strings.TrimSpace(data) | |
| 532 | - if data == "" || data == "[DONE]" { | |
| 533 | - continue | |
| 534 | - } | |
| 535 | - var ev responsesEvent | |
| 536 | - if json.Unmarshal([]byte(data), &ev) != nil { | |
| 537 | - continue | |
| 538 | - } | |
| 539 | - switch ev.Type { | |
| 540 | - case "response.output_text.delta": | |
| 541 | - if err := sendPart(ctx, cb, ai.NewTextPart(ev.Delta)); err != nil { | |
| 542 | - return nil, err | |
| 543 | - } | |
| 544 | - case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": | |
| 545 | - if onReasoning != nil && ev.Delta != "" { | |
| 546 | - onReasoning(ev.Delta) | |
| 547 | - } | |
| 548 | - case "response.output_item.added": | |
| 549 | - if ev.Item != nil { | |
| 550 | - var item outputItem | |
| 551 | - var id struct { | |
| 552 | - ID string `json:"id"` | |
| 553 | - } | |
| 554 | - if json.Unmarshal(*ev.Item, &item) == nil && json.Unmarshal(*ev.Item, &id) == nil && item.Type == "function_call" { | |
| 555 | - calls[id.ID] = &ai.ToolRequest{Name: item.Name, Ref: item.CallID} | |
| 556 | - } | |
| 557 | - } | |
| 558 | - case "response.function_call_arguments.delta": | |
| 559 | - call := calls[ev.ItemID] | |
| 560 | - if call == nil { | |
| 561 | - call = &ai.ToolRequest{} | |
| 562 | - } | |
| 563 | - if err := sendPart(ctx, cb, ai.NewToolRequestPart(&ai.ToolRequest{Name: call.Name, Ref: call.Ref, Input: ev.Delta})); err != nil { | |
| 564 | - return nil, err | |
| 565 | - } | |
| 566 | - case "response.completed", "response.incomplete", "response.failed": | |
| 567 | - if ev.Response == nil { | |
| 568 | - return nil, fmt.Errorf("stream error: %s without a response", ev.Type) | |
| 569 | - } | |
| 570 | - if ev.Type == "response.failed" && ev.Response.Status == "" { | |
| 571 | - ev.Response.Status = "failed" | |
| 572 | - } | |
| 573 | - return ev.Response, nil | |
| 574 | - case "error": | |
| 575 | - msg := ev.Message | |
| 576 | - if msg == "" { | |
| 577 | - msg = data | |
| 578 | - } | |
| 579 | - if errs := serverErrorsFrom(ctx); errs != nil { | |
| 580 | - errs.record(msg) | |
| 581 | - } | |
| 582 | - return nil, fmt.Errorf("stream error: %s", msg) | |
| 583 | - } | |
| 584 | - } | |
| 585 | - if err := sc.Err(); err != nil { | |
| 586 | - if errors.Is(err, context.Canceled) || ctx.Err() != nil { | |
| 587 | - return nil, err | |
| 588 | - } | |
| 589 | - return nil, fmt.Errorf("stream error: %w", err) | |
| 137 | +// sendThrough sends req through the middlewares, the first one outermost. | |
| 138 | +func sendThrough(chain []option.Middleware, req *http.Request) (*http.Response, error) { | |
| 139 | + next := func(req *http.Request) (*http.Response, error) { return responsesClient.Do(req) } | |
| 140 | + for i := len(chain) - 1; i >= 0; i-- { | |
| 141 | + mw, inner := chain[i], next | |
| 142 | + next = func(req *http.Request) (*http.Response, error) { return mw(req, inner) } | |
| 590 | 143 | } |
| 591 | - return nil, fmt.Errorf("stream error: the stream ended without response.completed (unexpected EOF)") | |
| 144 | + return next(req) | |
| 592 | 145 | } |
| 593 | 146 | |
| 594 | -// sendPart hands one part to Genkit's callback; a callback error stops the | |
| 595 | -// stream (the runaway guard uses it), worded as compat_oai words it. | |
| 596 | -func sendPart(ctx context.Context, cb ai.ModelStreamCallback, part *ai.Part) error { | |
| 597 | - if cb == nil { | |
| 147 | +// httpFailure is nil for a 2xx answer; otherwise the answer is read (4 KiB at | |
| 148 | +// most) and closed, and the error carries the status the way the OpenAI | |
| 149 | +// client's does. | |
| 150 | +func httpFailure(url string, resp *http.Response) error { | |
| 151 | + if resp.StatusCode/100 == 2 { | |
| 598 | 152 | return nil |
| 599 | 153 | } |
| 600 | - if err := cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{part}}); err != nil { | |
| 601 | - return fmt.Errorf("callback error: %w", err) | |
| 602 | - } | |
| 603 | - return nil | |
| 154 | + defer func() { _ = resp.Body.Close() }() | |
| 155 | + said, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) | |
| 156 | + return fmt.Errorf("POST %q: %s %s", url, resp.Status, strings.TrimSpace(string(said))) | |
| 604 | 157 | } |
| @@ -1,11 +1,9 @@ | |||
| 1 | package engine | 1 | package engine |
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | - "bufio" | ||
| 5 | "bytes" | 4 | "bytes" |
| 6 | "context" | 5 | "context" |
| 7 | "encoding/json" | 6 | "encoding/json" |
| 8 | - "errors" | ||
| 9 | "fmt" | 7 | "fmt" |
| 10 | "io" | 8 | "io" |
| 11 | "net/http" | 9 | "net/http" |
| @@ -126,479 +124,34 @@ func (r *responsesModel) post(ctx context.Context, body []byte) (*http.Response, | |||
| 126 | req.Header.Set("Content-Type", "application/json") | 124 | req.Header.Set("Content-Type", "application/json") |
| 127 | req.Header.Set("Authorization", "Bearer "+r.backend.APIKey) | 125 | req.Header.Set("Authorization", "Bearer "+r.backend.APIKey) |
| 128 | req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } | 126 | req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } |
| 129 | - next := func(req *http.Request) (*http.Response, error) { return responsesClient.Do(req) } | 127 | + resp, err := sendThrough(r.chain, req) |
| 130 | - for i := len(r.chain) - 1; i >= 0; i-- { | 128 | + if err == nil { |
| 131 | - mw, inner := r.chain[i], next | 129 | + err = httpFailure(url, resp) |
| 132 | - next = func(req *http.Request) (*http.Response, error) { return mw(req, inner) } | ||
| 133 | } | 130 | } |
| 134 | - resp, err := next(req) | ||
| 135 | if err != nil { | 131 | if err != nil { |
| 136 | return nil, err | 132 | return nil, err |
| 137 | } | 133 | } |
| 138 | - if resp.StatusCode/100 != 2 { | ||
| 139 | - defer func() { _ = resp.Body.Close() }() | ||
| 140 | - said, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) | ||
| 141 | - return nil, fmt.Errorf("POST %q: %s %s", url, resp.Status, strings.TrimSpace(string(said))) | ||
| 142 | - } | ||
| 143 | return resp, nil | 134 | return resp, nil |
| 144 | } | 135 | } |
| 145 | 136 | ||
| 146 | -// responsesRequest builds the JSON body of one call. | 137 | +// sendThrough sends req through the middlewares, the first one outermost. |
| 147 | -// | 138 | +func sendThrough(chain []option.Middleware, req *http.Request) (*http.Response, error) { |
| 148 | -// body, _ := responsesRequest("gpt-6-luna", req, true, false) | 139 | + next := func(req *http.Request) (*http.Response, error) { return responsesClient.Do(req) } |
| 149 | -// // {"model":"gpt-6-luna","input":[…],"tools":[…],"stream":true,"store":false,"include":["reasoning.encrypted_content"],…} | 140 | + for i := len(chain) - 1; i >= 0; i-- { |
| 150 | -func responsesRequest(model string, req *ai.ModelRequest, stream, noThink bool) ([]byte, error) { | 141 | + mw, inner := chain[i], next |
| 151 | - m, err := samplingFields(req.Config) | 142 | + next = func(req *http.Request) (*http.Response, error) { return mw(req, inner) } |
| 152 | - if err != nil { | ||
| 153 | - return nil, err | ||
| 154 | - } | ||
| 155 | - if noThink { | ||
| 156 | - setReasoning(m, "effort", "none") | ||
| 157 | - } | ||
| 158 | - input, err := responsesInput(req.Messages) | ||
| 159 | - if err != nil { | ||
| 160 | - return nil, err | ||
| 161 | - } | ||
| 162 | - m["model"] = model | ||
| 163 | - m["input"] = input | ||
| 164 | - if len(req.Tools) > 0 { | ||
| 165 | - m["tools"] = responsesTools(req.Tools) | ||
| 166 | - } | ||
| 167 | - if req.ToolChoice != "" { | ||
| 168 | - m["tool_choice"] = string(req.ToolChoice) | ||
| 169 | - } | ||
| 170 | - if format := responsesFormat(req.Output); format != nil { | ||
| 171 | - text, _ := m["text"].(map[string]any) | ||
| 172 | - if text == nil { | ||
| 173 | - text = map[string]any{} | ||
| 174 | - } | ||
| 175 | - text["format"] = format | ||
| 176 | - m["text"] = text | ||
| 177 | - } | ||
| 178 | - m["stream"] = stream | ||
| 179 | - if _, set := m["store"]; !set { | ||
| 180 | - m["store"] = false | ||
| 181 | - } | ||
| 182 | - if _, set := m["include"]; !set && m["store"] == false { | ||
| 183 | - m["include"] = []string{"reasoning.encrypted_content"} | ||
| 184 | - } | ||
| 185 | - return json.Marshal(m) | ||
| 186 | -} | ||
| 187 | - | ||
| 188 | -// samplingFields is the request's config — the file's `sampling:` block — | ||
| 189 | -// as the fields of a Responses request, written as they are except for the | ||
| 190 | -// Chat Completions names this API spells differently: the answer limit | ||
| 191 | -// (max_tokens, max_completion_tokens → max_output_tokens) and | ||
| 192 | -// reasoning_effort (→ reasoning.effort). | ||
| 193 | -func samplingFields(cfg any) (map[string]any, error) { | ||
| 194 | - m := map[string]any{} | ||
| 195 | - switch c := cfg.(type) { | ||
| 196 | - case nil: | ||
| 197 | - case map[string]any: | ||
| 198 | - for k, v := range c { | ||
| 199 | - m[k] = v | ||
| 200 | - } | ||
| 201 | - default: | ||
| 202 | - raw, err := json.Marshal(c) | ||
| 203 | - if err != nil { | ||
| 204 | - return nil, fmt.Errorf("responses: config: %w", err) | ||
| 205 | - } | ||
| 206 | - if err := json.Unmarshal(raw, &m); err != nil { | ||
| 207 | - return nil, fmt.Errorf("responses: config: %w", err) | ||
| 208 | - } | ||
| 209 | - } | ||
| 210 | - for _, key := range []string{"max_completion_tokens", "max_tokens"} { | ||
| 211 | - if v, ok := m[key]; ok { | ||
| 212 | - if _, set := m["max_output_tokens"]; !set { | ||
| 213 | - m["max_output_tokens"] = v | ||
| 214 | - } | ||
| 215 | - delete(m, key) | ||
| 216 | - } | ||
| 217 | - } | ||
| 218 | - if v, ok := m["reasoning_effort"]; ok { | ||
| 219 | - delete(m, "reasoning_effort") | ||
| 220 | - if r, _ := m["reasoning"].(map[string]any); r == nil || r["effort"] == nil { | ||
| 221 | - setReasoning(m, "effort", v) | ||
| 222 | - } | ||
| 223 | - } | ||
| 224 | - return m, nil | ||
| 225 | -} | ||
| 226 | - | ||
| 227 | -// setReasoning sets one field of the `reasoning` object, keeping the others. | ||
| 228 | -func setReasoning(m map[string]any, key string, value any) { | ||
| 229 | - r, _ := m["reasoning"].(map[string]any) | ||
| 230 | - if r == nil { | ||
| 231 | - r = map[string]any{} | ||
| 232 | - } else { | ||
| 233 | - copied := make(map[string]any, len(r)+1) | ||
| 234 | - for k, v := range r { | ||
| 235 | - copied[k] = v | ||
| 236 | - } | ||
| 237 | - r = copied | ||
| 238 | - } | ||
| 239 | - r[key] = value | ||
| 240 | - m["reasoning"] = r | ||
| 241 | -} | ||
| 242 | - | ||
| 243 | -// responsesInput turns Genkit's messages into Responses input items: | ||
| 244 | -// system and user messages, the model's earlier answers (its reasoning | ||
| 245 | -// items, its text, its function calls) and the tool results. | ||
| 246 | -func responsesInput(messages []*ai.Message) ([]any, error) { | ||
| 247 | - var items []any | ||
| 248 | - for _, msg := range messages { | ||
| 249 | - if msg == nil { | ||
| 250 | - continue | ||
| 251 | - } | ||
| 252 | - switch msg.Role { | ||
| 253 | - case ai.RoleSystem: | ||
| 254 | - if text := msg.Text(); text != "" { | ||
| 255 | - items = append(items, map[string]any{"role": "system", "content": text}) | ||
| 256 | - } | ||
| 257 | - case ai.RoleUser: | ||
| 258 | - if content := userContent(msg.Content); len(content) > 0 { | ||
| 259 | - items = append(items, map[string]any{"role": "user", "content": content}) | ||
| 260 | - } | ||
| 261 | - case ai.RoleModel: | ||
| 262 | - modelItems, err := modelInput(msg) | ||
| 263 | - if err != nil { | ||
| 264 | - return nil, err | ||
| 265 | - } | ||
| 266 | - items = append(items, modelItems...) | ||
| 267 | - case ai.RoleTool: | ||
| 268 | - for _, p := range msg.Content { | ||
| 269 | - if p == nil || !p.IsToolResponse() || p.ToolResponse == nil { | ||
| 270 | - continue | ||
| 271 | - } | ||
| 272 | - out, err := responsesToolOutput(p.ToolResponse.Output) | ||
| 273 | - if err != nil { | ||
| 274 | - return nil, err | ||
| 275 | - } | ||
| 276 | - items = append(items, map[string]any{"type": "function_call_output", "call_id": callID(p.ToolResponse.Ref, p.ToolResponse.Name), "output": out}) | ||
| 277 | - } | ||
| 278 | - } | ||
| 279 | - } | ||
| 280 | - return items, nil | ||
| 281 | -} | ||
| 282 | - | ||
| 283 | -// userContent is a user message's parts: text, and images by URL. | ||
| 284 | -func userContent(parts []*ai.Part) []any { | ||
| 285 | - var content []any | ||
| 286 | - for _, p := range parts { | ||
| 287 | - switch { | ||
| 288 | - case p == nil: | ||
| 289 | - case p.IsText(): | ||
| 290 | - content = append(content, map[string]any{"type": "input_text", "text": p.Text}) | ||
| 291 | - case p.IsMedia(): | ||
| 292 | - content = append(content, map[string]any{"type": "input_image", "image_url": p.Text}) | ||
| 293 | - } | ||
| 294 | - } | ||
| 295 | - return content | ||
| 296 | -} | ||
| 297 | - | ||
| 298 | -// modelInput is one of the model's earlier answers, in the order the server | ||
| 299 | -// produced them: reasoning, text, function calls. | ||
| 300 | -func modelInput(msg *ai.Message) ([]any, error) { | ||
| 301 | - var items []any | ||
| 302 | - if raw, ok := msg.Metadata[responsesReasoningKey].([]any); ok { | ||
| 303 | - items = append(items, raw...) | ||
| 304 | - } | ||
| 305 | - var text strings.Builder | ||
| 306 | - for _, p := range msg.Content { | ||
| 307 | - if p != nil && p.IsText() { | ||
| 308 | - text.WriteString(p.Text) | ||
| 309 | - } | ||
| 310 | - } | ||
| 311 | - if text.Len() > 0 { | ||
| 312 | - items = append(items, map[string]any{"role": "assistant", "content": text.String()}) | ||
| 313 | - } | ||
| 314 | - for _, p := range msg.Content { | ||
| 315 | - if p == nil || !p.IsToolRequest() || p.ToolRequest == nil { | ||
| 316 | - continue | ||
| 317 | - } | ||
| 318 | - args, err := toolArguments(p.ToolRequest.Input) | ||
| 319 | - if err != nil { | ||
| 320 | - return nil, err | ||
| 321 | - } | ||
| 322 | - items = append(items, map[string]any{"type": "function_call", "call_id": callID(p.ToolRequest.Ref, p.ToolRequest.Name), "name": p.ToolRequest.Name, "arguments": args}) | ||
| 323 | - } | ||
| 324 | - return items, nil | ||
| 325 | -} | ||
| 326 | - | ||
| 327 | -// callID is the call's id, the tool's name when Genkit has none (as | ||
| 328 | -// compat_oai does). | ||
| 329 | -func callID(ref, name string) string { | ||
| 330 | - if ref != "" { | ||
| 331 | - return ref | ||
| 332 | - } | ||
| 333 | - return name | ||
| 334 | -} | ||
| 335 | - | ||
| 336 | -// toolArguments is a tool call's input as the JSON string the API wants. | ||
| 337 | -func toolArguments(input any) (string, error) { | ||
| 338 | - if s, ok := input.(string); ok { | ||
| 339 | - return s, nil | ||
| 340 | - } | ||
| 341 | - if input == nil { | ||
| 342 | - return "{}", nil | ||
| 343 | - } | ||
| 344 | - raw, err := json.Marshal(input) | ||
| 345 | - if err != nil { | ||
| 346 | - return "", fmt.Errorf("responses: tool arguments: %w", err) | ||
| 347 | - } | ||
| 348 | - return string(raw), nil | ||
| 349 | -} | ||
| 350 | - | ||
| 351 | -// responsesToolOutput is a tool's result as a string: a string as is, anything else | ||
| 352 | -// in JSON (what compat_oai sends as the tool message). | ||
| 353 | -func responsesToolOutput(output any) (string, error) { | ||
| 354 | - if s, ok := output.(string); ok { | ||
| 355 | - return s, nil | ||
| 356 | - } | ||
| 357 | - raw, err := json.Marshal(output) | ||
| 358 | - if err != nil { | ||
| 359 | - return "", fmt.Errorf("responses: tool output: %w", err) | ||
| 360 | - } | ||
| 361 | - return string(raw), nil | ||
| 362 | -} | ||
| 363 | - | ||
| 364 | -// responsesTools declares the tools as function tools, not strict: mm's | ||
| 365 | -// schemas have optional properties, which strict mode refuses. | ||
| 366 | -func responsesTools(tools []*ai.ToolDefinition) []any { | ||
| 367 | - out := make([]any, 0, len(tools)) | ||
| 368 | - for _, t := range tools { | ||
| 369 | - if t == nil { | ||
| 370 | - continue | ||
| 371 | - } | ||
| 372 | - params := t.InputSchema | ||
| 373 | - if params == nil { | ||
| 374 | - params = map[string]any{"type": "object", "properties": map[string]any{}} | ||
| 375 | - } | ||
| 376 | - out = append(out, map[string]any{"type": "function", "name": t.Name, "description": t.Description, "parameters": params, "strict": false}) | ||
| 377 | - } | ||
| 378 | - return out | ||
| 379 | -} | ||
| 380 | - | ||
| 381 | -// responsesFormat is `text.format` for structuredOutput (ticket 80): the | ||
| 382 | -// schema, strict as the openai provider sends it; nil for plain text. | ||
| 383 | -func responsesFormat(output *ai.ModelOutputConfig) map[string]any { | ||
| 384 | - if output == nil || output.Format != "json" { | ||
| 385 | - return nil | ||
| 386 | - } | ||
| 387 | - if output.Schema == nil { | ||
| 388 | - return map[string]any{"type": "json_object"} | ||
| 389 | - } | ||
| 390 | - return map[string]any{"type": "json_schema", "name": "output", "schema": output.Schema, "strict": true} | ||
| 391 | -} | ||
| 392 | - | ||
| 393 | -// responsesResult is the little of a Responses answer mm reads. | ||
| 394 | -type responsesResult struct { | ||
| 395 | - Status string `json:"status"` | ||
| 396 | - Output []json.RawMessage `json:"output"` | ||
| 397 | - IncompleteDetails *struct { | ||
| 398 | - Reason string `json:"reason"` | ||
| 399 | - } `json:"incomplete_details"` | ||
| 400 | - Error *struct { | ||
| 401 | - Message string `json:"message"` | ||
| 402 | - } `json:"error"` | ||
| 403 | - Usage *struct { | ||
| 404 | - InputTokens int `json:"input_tokens"` | ||
| 405 | - OutputTokens int `json:"output_tokens"` | ||
| 406 | - TotalTokens int `json:"total_tokens"` | ||
| 407 | - InputTokensDetails struct { | ||
| 408 | - CachedTokens int `json:"cached_tokens"` | ||
| 409 | - } `json:"input_tokens_details"` | ||
| 410 | - OutputTokensDetails struct { | ||
| 411 | - ReasoningTokens int `json:"reasoning_tokens"` | ||
| 412 | - } `json:"output_tokens_details"` | ||
| 413 | - } `json:"usage"` | ||
| 414 | -} | ||
| 415 | - | ||
| 416 | -// outputItem is one item of the answer's output. | ||
| 417 | -type outputItem struct { | ||
| 418 | - Type string `json:"type"` | ||
| 419 | - CallID string `json:"call_id"` | ||
| 420 | - Name string `json:"name"` | ||
| 421 | - Arguments string `json:"arguments"` | ||
| 422 | - Content []struct { | ||
| 423 | - Type string `json:"type"` | ||
| 424 | - Text string `json:"text"` | ||
| 425 | - Refusal string `json:"refusal"` | ||
| 426 | - } `json:"content"` | ||
| 427 | -} | ||
| 428 | - | ||
| 429 | -// modelResponse turns the answer into Genkit's response. A failed answer is | ||
| 430 | -// an error; tool arguments that do not parse are the error compat_oai gives | ||
| 431 | -// ("could not parse tool args"), so the call is handed back to the model the | ||
| 432 | -// same way (toolargs.go). | ||
| 433 | -func (r *responsesResult) modelResponse() (*ai.ModelResponse, error) { | ||
| 434 | - if r.Status == "failed" { | ||
| 435 | - msg := "the response failed" | ||
| 436 | - if r.Error != nil && r.Error.Message != "" { | ||
| 437 | - msg = r.Error.Message | ||
| 438 | - } | ||
| 439 | - return nil, fmt.Errorf("stream error: %s", msg) | ||
| 440 | - } | ||
| 441 | - msg := &ai.Message{Role: ai.RoleModel, Content: []*ai.Part{}} | ||
| 442 | - resp := &ai.ModelResponse{Message: msg, FinishReason: ai.FinishReasonStop} | ||
| 443 | - var reasoning []any | ||
| 444 | - var text strings.Builder | ||
| 445 | - var calls []*ai.Part | ||
| 446 | - for _, raw := range r.Output { | ||
| 447 | - var item outputItem | ||
| 448 | - if json.Unmarshal(raw, &item) != nil { | ||
| 449 | - continue | ||
| 450 | - } | ||
| 451 | - switch item.Type { | ||
| 452 | - case "reasoning": | ||
| 453 | - var keep any | ||
| 454 | - if json.Unmarshal(raw, &keep) == nil { | ||
| 455 | - reasoning = append(reasoning, keep) | ||
| 456 | - } | ||
| 457 | - case "message": | ||
| 458 | - for _, c := range item.Content { | ||
| 459 | - switch c.Type { | ||
| 460 | - case "output_text": | ||
| 461 | - text.WriteString(c.Text) | ||
| 462 | - case "refusal": | ||
| 463 | - resp.FinishReason, resp.FinishMessage = ai.FinishReasonBlocked, c.Refusal | ||
| 464 | - } | ||
| 465 | - } | ||
| 466 | - case "function_call": | ||
| 467 | - input := map[string]any{} | ||
| 468 | - if strings.TrimSpace(item.Arguments) != "" { | ||
| 469 | - if err := json.Unmarshal([]byte(item.Arguments), &input); err != nil { | ||
| 470 | - return nil, fmt.Errorf("could not parse tool args: %w", err) | ||
| 471 | - } | ||
| 472 | - } | ||
| 473 | - calls = append(calls, ai.NewToolRequestPart(&ai.ToolRequest{Ref: item.CallID, Name: item.Name, Input: input})) | ||
| 474 | - } | ||
| 475 | - } | ||
| 476 | - if text.Len() > 0 { | ||
| 477 | - msg.Content = append(msg.Content, ai.NewTextPart(text.String())) | ||
| 478 | - } | ||
| 479 | - msg.Content = append(msg.Content, calls...) | ||
| 480 | - if len(reasoning) > 0 { | ||
| 481 | - msg.Metadata = map[string]any{responsesReasoningKey: reasoning} | ||
| 482 | - } | ||
| 483 | - if r.Status == "incomplete" && r.IncompleteDetails != nil { | ||
| 484 | - switch r.IncompleteDetails.Reason { | ||
| 485 | - case "max_output_tokens": | ||
| 486 | - resp.FinishReason = ai.FinishReasonLength | ||
| 487 | - case "content_filter": | ||
| 488 | - resp.FinishReason = ai.FinishReasonBlocked | ||
| 489 | - default: | ||
| 490 | - resp.FinishReason, resp.FinishMessage = ai.FinishReasonOther, r.IncompleteDetails.Reason | ||
| 491 | - } | ||
| 492 | - } | ||
| 493 | - if u := r.Usage; u != nil { | ||
| 494 | - resp.Usage = &ai.GenerationUsage{ | ||
| 495 | - InputTokens: u.InputTokens, | ||
| 496 | - OutputTokens: u.OutputTokens, | ||
| 497 | - TotalTokens: u.TotalTokens, | ||
| 498 | - ThoughtsTokens: u.OutputTokensDetails.ReasoningTokens, | ||
| 499 | - CachedContentTokens: u.InputTokensDetails.CachedTokens, | ||
| 500 | - } | ||
| 501 | - } | ||
| 502 | - return resp, nil | ||
| 503 | -} | ||
| 504 | - | ||
| 505 | -// responsesEvent is one streamed event: its type and the fields mm reads. | ||
| 506 | -type responsesEvent struct { | ||
| 507 | - Type string `json:"type"` | ||
| 508 | - Delta string `json:"delta"` | ||
| 509 | - ItemID string `json:"item_id"` | ||
| 510 | - Message string `json:"message"` | ||
| 511 | - Item *json.RawMessage `json:"item"` | ||
| 512 | - Response *responsesResult `json:"response"` | ||
| 513 | -} | ||
| 514 | - | ||
| 515 | -// readResponsesStream reads the SSE events of a streamed call: text deltas | ||
| 516 | -// go to Genkit's callback, function-call argument deltas too (the runaway | ||
| 517 | -// guard and the watchdog read them), reasoning to the turn's listener | ||
| 518 | -// (reasoning.go). The answer is the one `response.completed` (or | ||
| 519 | -// `response.incomplete`, `response.failed`) carries. A stream that ends | ||
| 520 | -// without one broke: "stream error", which the model call retries once. | ||
| 521 | -func readResponsesStream(ctx context.Context, body io.Reader, cb ai.ModelStreamCallback) (*responsesResult, error) { | ||
| 522 | - onReasoning := reasoningFrom(ctx) | ||
| 523 | - calls := map[string]*ai.ToolRequest{} // item id → name and call id | ||
| 524 | - sc := bufio.NewScanner(body) | ||
| 525 | - sc.Buffer(make([]byte, 64<<10), maxSSELine*8) | ||
| 526 | - for sc.Scan() { | ||
| 527 | - data, ok := strings.CutPrefix(strings.TrimSpace(sc.Text()), "data:") | ||
| 528 | - if !ok { | ||
| 529 | - continue | ||
| 530 | - } | ||
| 531 | - data = strings.TrimSpace(data) | ||
| 532 | - if data == "" || data == "[DONE]" { | ||
| 533 | - continue | ||
| 534 | - } | ||
| 535 | - var ev responsesEvent | ||
| 536 | - if json.Unmarshal([]byte(data), &ev) != nil { | ||
| 537 | - continue | ||
| 538 | - } | ||
| 539 | - switch ev.Type { | ||
| 540 | - case "response.output_text.delta": | ||
| 541 | - if err := sendPart(ctx, cb, ai.NewTextPart(ev.Delta)); err != nil { | ||
| 542 | - return nil, err | ||
| 543 | - } | ||
| 544 | - case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": | ||
| 545 | - if onReasoning != nil && ev.Delta != "" { | ||
| 546 | - onReasoning(ev.Delta) | ||
| 547 | - } | ||
| 548 | - case "response.output_item.added": | ||
| 549 | - if ev.Item != nil { | ||
| 550 | - var item outputItem | ||
| 551 | - var id struct { | ||
| 552 | - ID string `json:"id"` | ||
| 553 | - } | ||
| 554 | - if json.Unmarshal(*ev.Item, &item) == nil && json.Unmarshal(*ev.Item, &id) == nil && item.Type == "function_call" { | ||
| 555 | - calls[id.ID] = &ai.ToolRequest{Name: item.Name, Ref: item.CallID} | ||
| 556 | - } | ||
| 557 | - } | ||
| 558 | - case "response.function_call_arguments.delta": | ||
| 559 | - call := calls[ev.ItemID] | ||
| 560 | - if call == nil { | ||
| 561 | - call = &ai.ToolRequest{} | ||
| 562 | - } | ||
| 563 | - if err := sendPart(ctx, cb, ai.NewToolRequestPart(&ai.ToolRequest{Name: call.Name, Ref: call.Ref, Input: ev.Delta})); err != nil { | ||
| 564 | - return nil, err | ||
| 565 | - } | ||
| 566 | - case "response.completed", "response.incomplete", "response.failed": | ||
| 567 | - if ev.Response == nil { | ||
| 568 | - return nil, fmt.Errorf("stream error: %s without a response", ev.Type) | ||
| 569 | - } | ||
| 570 | - if ev.Type == "response.failed" && ev.Response.Status == "" { | ||
| 571 | - ev.Response.Status = "failed" | ||
| 572 | - } | ||
| 573 | - return ev.Response, nil | ||
| 574 | - case "error": | ||
| 575 | - msg := ev.Message | ||
| 576 | - if msg == "" { | ||
| 577 | - msg = data | ||
| 578 | - } | ||
| 579 | - if errs := serverErrorsFrom(ctx); errs != nil { | ||
| 580 | - errs.record(msg) | ||
| 581 | - } | ||
| 582 | - return nil, fmt.Errorf("stream error: %s", msg) | ||
| 583 | - } | ||
| 584 | - } | ||
| 585 | - if err := sc.Err(); err != nil { | ||
| 586 | - if errors.Is(err, context.Canceled) || ctx.Err() != nil { | ||
| 587 | - return nil, err | ||
| 588 | - } | ||
| 589 | - return nil, fmt.Errorf("stream error: %w", err) | ||
| 590 | } | 143 | } |
| 591 | - return nil, fmt.Errorf("stream error: the stream ended without response.completed (unexpected EOF)") | 144 | + return next(req) |
| 592 | } | 145 | } |
| 593 | 146 | ||
| 594 | -// sendPart hands one part to Genkit's callback; a callback error stops the | 147 | +// httpFailure is nil for a 2xx answer; otherwise the answer is read (4 KiB at |
| 595 | -// stream (the runaway guard uses it), worded as compat_oai words it. | 148 | +// most) and closed, and the error carries the status the way the OpenAI |
| 596 | -func sendPart(ctx context.Context, cb ai.ModelStreamCallback, part *ai.Part) error { | 149 | +// client's does. |
| 597 | - if cb == nil { | 150 | +func httpFailure(url string, resp *http.Response) error { |
| 151 | + if resp.StatusCode/100 == 2 { | ||
| 598 | return nil | 152 | return nil |
| 599 | } | 153 | } |
| 600 | - if err := cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{part}}); err != nil { | 154 | + defer func() { _ = resp.Body.Close() }() |
| 601 | - return fmt.Errorf("callback error: %w", err) | 155 | + said, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) |
| 602 | - } | 156 | + return fmt.Errorf("POST %q: %s %s", url, resp.Status, strings.TrimSpace(string(said))) |
| 603 | - return nil | ||
| 604 | } | 157 | } |
added
internal/engine/responses_input.go +143 -0 | new file mode 100644 | ||
| @@ -0,0 +1,143 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "encoding/json" | |
| 5 | + "fmt" | |
| 6 | + "strings" | |
| 7 | + | |
| 8 | + "github.com/firebase/genkit/go/ai" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// responsesInput turns Genkit's messages into Responses input items: | |
| 12 | +// system and user messages, the model's earlier answers (its reasoning | |
| 13 | +// items, its text, its function calls) and the tool results. | |
| 14 | +func responsesInput(messages []*ai.Message) ([]any, error) { | |
| 15 | + var items []any | |
| 16 | + for _, msg := range messages { | |
| 17 | + if msg == nil { | |
| 18 | + continue | |
| 19 | + } | |
| 20 | + more, err := messageItems(msg) | |
| 21 | + if err != nil { | |
| 22 | + return nil, err | |
| 23 | + } | |
| 24 | + items = append(items, more...) | |
| 25 | + } | |
| 26 | + return items, nil | |
| 27 | +} | |
| 28 | + | |
| 29 | +// messageItems is one message as input items, by role. | |
| 30 | +func messageItems(msg *ai.Message) ([]any, error) { | |
| 31 | + switch msg.Role { | |
| 32 | + case ai.RoleSystem: | |
| 33 | + if text := msg.Text(); text != "" { | |
| 34 | + return []any{map[string]any{"role": "system", "content": text}}, nil | |
| 35 | + } | |
| 36 | + case ai.RoleUser: | |
| 37 | + if content := userContent(msg.Content); len(content) > 0 { | |
| 38 | + return []any{map[string]any{"role": "user", "content": content}}, nil | |
| 39 | + } | |
| 40 | + case ai.RoleModel: | |
| 41 | + return modelInput(msg) | |
| 42 | + case ai.RoleTool: | |
| 43 | + return toolResultItems(msg) | |
| 44 | + } | |
| 45 | + return nil, nil | |
| 46 | +} | |
| 47 | + | |
| 48 | +// toolResultItems is a tool message's results, one function_call_output each. | |
| 49 | +func toolResultItems(msg *ai.Message) ([]any, error) { | |
| 50 | + var items []any | |
| 51 | + for _, p := range msg.Content { | |
| 52 | + if p == nil || !p.IsToolResponse() || p.ToolResponse == nil { | |
| 53 | + continue | |
| 54 | + } | |
| 55 | + out, err := responsesToolOutput(p.ToolResponse.Output) | |
| 56 | + if err != nil { | |
| 57 | + return nil, err | |
| 58 | + } | |
| 59 | + items = append(items, map[string]any{"type": "function_call_output", "call_id": callID(p.ToolResponse.Ref, p.ToolResponse.Name), "output": out}) | |
| 60 | + } | |
| 61 | + return items, nil | |
| 62 | +} | |
| 63 | + | |
| 64 | +// userContent is a user message's parts: text, and images by URL. | |
| 65 | +func userContent(parts []*ai.Part) []any { | |
| 66 | + var content []any | |
| 67 | + for _, p := range parts { | |
| 68 | + switch { | |
| 69 | + case p == nil: | |
| 70 | + case p.IsText(): | |
| 71 | + content = append(content, map[string]any{"type": "input_text", "text": p.Text}) | |
| 72 | + case p.IsMedia(): | |
| 73 | + content = append(content, map[string]any{"type": "input_image", "image_url": p.Text}) | |
| 74 | + } | |
| 75 | + } | |
| 76 | + return content | |
| 77 | +} | |
| 78 | + | |
| 79 | +// modelInput is one of the model's earlier answers, in the order the server | |
| 80 | +// produced them: reasoning, text, function calls. | |
| 81 | +func modelInput(msg *ai.Message) ([]any, error) { | |
| 82 | + var items []any | |
| 83 | + if raw, ok := msg.Metadata[responsesReasoningKey].([]any); ok { | |
| 84 | + items = append(items, raw...) | |
| 85 | + } | |
| 86 | + var text strings.Builder | |
| 87 | + for _, p := range msg.Content { | |
| 88 | + if p != nil && p.IsText() { | |
| 89 | + text.WriteString(p.Text) | |
| 90 | + } | |
| 91 | + } | |
| 92 | + if text.Len() > 0 { | |
| 93 | + items = append(items, map[string]any{"role": "assistant", "content": text.String()}) | |
| 94 | + } | |
| 95 | + for _, p := range msg.Content { | |
| 96 | + if p == nil || !p.IsToolRequest() || p.ToolRequest == nil { | |
| 97 | + continue | |
| 98 | + } | |
| 99 | + args, err := toolArguments(p.ToolRequest.Input) | |
| 100 | + if err != nil { | |
| 101 | + return nil, err | |
| 102 | + } | |
| 103 | + items = append(items, map[string]any{"type": "function_call", "call_id": callID(p.ToolRequest.Ref, p.ToolRequest.Name), "name": p.ToolRequest.Name, "arguments": args}) | |
| 104 | + } | |
| 105 | + return items, nil | |
| 106 | +} | |
| 107 | + | |
| 108 | +// callID is the call's id, the tool's name when Genkit has none (as | |
| 109 | +// compat_oai does). | |
| 110 | +func callID(ref, name string) string { | |
| 111 | + if ref != "" { | |
| 112 | + return ref | |
| 113 | + } | |
| 114 | + return name | |
| 115 | +} | |
| 116 | + | |
| 117 | +// toolArguments is a tool call's input as the JSON string the API wants. | |
| 118 | +func toolArguments(input any) (string, error) { | |
| 119 | + if s, ok := input.(string); ok { | |
| 120 | + return s, nil | |
| 121 | + } | |
| 122 | + if input == nil { | |
| 123 | + return "{}", nil | |
| 124 | + } | |
| 125 | + raw, err := json.Marshal(input) | |
| 126 | + if err != nil { | |
| 127 | + return "", fmt.Errorf("responses: tool arguments: %w", err) | |
| 128 | + } | |
| 129 | + return string(raw), nil | |
| 130 | +} | |
| 131 | + | |
| 132 | +// responsesToolOutput is a tool's result as a string: a string as is, anything else | |
| 133 | +// in JSON (what compat_oai sends as the tool message). | |
| 134 | +func responsesToolOutput(output any) (string, error) { | |
| 135 | + if s, ok := output.(string); ok { | |
| 136 | + return s, nil | |
| 137 | + } | |
| 138 | + raw, err := json.Marshal(output) | |
| 139 | + if err != nil { | |
| 140 | + return "", fmt.Errorf("responses: tool output: %w", err) | |
| 141 | + } | |
| 142 | + return string(raw), nil | |
| 143 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,143 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "encoding/json" | ||
| 5 | + "fmt" | ||
| 6 | + "strings" | ||
| 7 | + | ||
| 8 | + "github.com/firebase/genkit/go/ai" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// responsesInput turns Genkit's messages into Responses input items: | ||
| 12 | +// system and user messages, the model's earlier answers (its reasoning | ||
| 13 | +// items, its text, its function calls) and the tool results. | ||
| 14 | +func responsesInput(messages []*ai.Message) ([]any, error) { | ||
| 15 | + var items []any | ||
| 16 | + for _, msg := range messages { | ||
| 17 | + if msg == nil { | ||
| 18 | + continue | ||
| 19 | + } | ||
| 20 | + more, err := messageItems(msg) | ||
| 21 | + if err != nil { | ||
| 22 | + return nil, err | ||
| 23 | + } | ||
| 24 | + items = append(items, more...) | ||
| 25 | + } | ||
| 26 | + return items, nil | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +// messageItems is one message as input items, by role. | ||
| 30 | +func messageItems(msg *ai.Message) ([]any, error) { | ||
| 31 | + switch msg.Role { | ||
| 32 | + case ai.RoleSystem: | ||
| 33 | + if text := msg.Text(); text != "" { | ||
| 34 | + return []any{map[string]any{"role": "system", "content": text}}, nil | ||
| 35 | + } | ||
| 36 | + case ai.RoleUser: | ||
| 37 | + if content := userContent(msg.Content); len(content) > 0 { | ||
| 38 | + return []any{map[string]any{"role": "user", "content": content}}, nil | ||
| 39 | + } | ||
| 40 | + case ai.RoleModel: | ||
| 41 | + return modelInput(msg) | ||
| 42 | + case ai.RoleTool: | ||
| 43 | + return toolResultItems(msg) | ||
| 44 | + } | ||
| 45 | + return nil, nil | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +// toolResultItems is a tool message's results, one function_call_output each. | ||
| 49 | +func toolResultItems(msg *ai.Message) ([]any, error) { | ||
| 50 | + var items []any | ||
| 51 | + for _, p := range msg.Content { | ||
| 52 | + if p == nil || !p.IsToolResponse() || p.ToolResponse == nil { | ||
| 53 | + continue | ||
| 54 | + } | ||
| 55 | + out, err := responsesToolOutput(p.ToolResponse.Output) | ||
| 56 | + if err != nil { | ||
| 57 | + return nil, err | ||
| 58 | + } | ||
| 59 | + items = append(items, map[string]any{"type": "function_call_output", "call_id": callID(p.ToolResponse.Ref, p.ToolResponse.Name), "output": out}) | ||
| 60 | + } | ||
| 61 | + return items, nil | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +// userContent is a user message's parts: text, and images by URL. | ||
| 65 | +func userContent(parts []*ai.Part) []any { | ||
| 66 | + var content []any | ||
| 67 | + for _, p := range parts { | ||
| 68 | + switch { | ||
| 69 | + case p == nil: | ||
| 70 | + case p.IsText(): | ||
| 71 | + content = append(content, map[string]any{"type": "input_text", "text": p.Text}) | ||
| 72 | + case p.IsMedia(): | ||
| 73 | + content = append(content, map[string]any{"type": "input_image", "image_url": p.Text}) | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | + return content | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +// modelInput is one of the model's earlier answers, in the order the server | ||
| 80 | +// produced them: reasoning, text, function calls. | ||
| 81 | +func modelInput(msg *ai.Message) ([]any, error) { | ||
| 82 | + var items []any | ||
| 83 | + if raw, ok := msg.Metadata[responsesReasoningKey].([]any); ok { | ||
| 84 | + items = append(items, raw...) | ||
| 85 | + } | ||
| 86 | + var text strings.Builder | ||
| 87 | + for _, p := range msg.Content { | ||
| 88 | + if p != nil && p.IsText() { | ||
| 89 | + text.WriteString(p.Text) | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | + if text.Len() > 0 { | ||
| 93 | + items = append(items, map[string]any{"role": "assistant", "content": text.String()}) | ||
| 94 | + } | ||
| 95 | + for _, p := range msg.Content { | ||
| 96 | + if p == nil || !p.IsToolRequest() || p.ToolRequest == nil { | ||
| 97 | + continue | ||
| 98 | + } | ||
| 99 | + args, err := toolArguments(p.ToolRequest.Input) | ||
| 100 | + if err != nil { | ||
| 101 | + return nil, err | ||
| 102 | + } | ||
| 103 | + items = append(items, map[string]any{"type": "function_call", "call_id": callID(p.ToolRequest.Ref, p.ToolRequest.Name), "name": p.ToolRequest.Name, "arguments": args}) | ||
| 104 | + } | ||
| 105 | + return items, nil | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +// callID is the call's id, the tool's name when Genkit has none (as | ||
| 109 | +// compat_oai does). | ||
| 110 | +func callID(ref, name string) string { | ||
| 111 | + if ref != "" { | ||
| 112 | + return ref | ||
| 113 | + } | ||
| 114 | + return name | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +// toolArguments is a tool call's input as the JSON string the API wants. | ||
| 118 | +func toolArguments(input any) (string, error) { | ||
| 119 | + if s, ok := input.(string); ok { | ||
| 120 | + return s, nil | ||
| 121 | + } | ||
| 122 | + if input == nil { | ||
| 123 | + return "{}", nil | ||
| 124 | + } | ||
| 125 | + raw, err := json.Marshal(input) | ||
| 126 | + if err != nil { | ||
| 127 | + return "", fmt.Errorf("responses: tool arguments: %w", err) | ||
| 128 | + } | ||
| 129 | + return string(raw), nil | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +// responsesToolOutput is a tool's result as a string: a string as is, anything else | ||
| 133 | +// in JSON (what compat_oai sends as the tool message). | ||
| 134 | +func responsesToolOutput(output any) (string, error) { | ||
| 135 | + if s, ok := output.(string); ok { | ||
| 136 | + return s, nil | ||
| 137 | + } | ||
| 138 | + raw, err := json.Marshal(output) | ||
| 139 | + if err != nil { | ||
| 140 | + return "", fmt.Errorf("responses: tool output: %w", err) | ||
| 141 | + } | ||
| 142 | + return string(raw), nil | ||
| 143 | +} | ||
added
internal/engine/responses_request.go +134 -0 | new file mode 100644 | ||
| @@ -0,0 +1,134 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "encoding/json" | |
| 5 | + "fmt" | |
| 6 | + | |
| 7 | + "github.com/firebase/genkit/go/ai" | |
| 8 | +) | |
| 9 | + | |
| 10 | +// responsesRequest builds the JSON body of one call. | |
| 11 | +// | |
| 12 | +// body, _ := responsesRequest("gpt-6-luna", req, true, false) | |
| 13 | +// // {"model":"gpt-6-luna","input":[…],"tools":[…],"stream":true,"store":false,"include":["reasoning.encrypted_content"],…} | |
| 14 | +func responsesRequest(model string, req *ai.ModelRequest, stream, noThink bool) ([]byte, error) { | |
| 15 | + m, err := samplingFields(req.Config) | |
| 16 | + if err != nil { | |
| 17 | + return nil, err | |
| 18 | + } | |
| 19 | + if noThink { | |
| 20 | + setReasoning(m, "effort", "none") | |
| 21 | + } | |
| 22 | + input, err := responsesInput(req.Messages) | |
| 23 | + if err != nil { | |
| 24 | + return nil, err | |
| 25 | + } | |
| 26 | + m["model"] = model | |
| 27 | + m["input"] = input | |
| 28 | + if len(req.Tools) > 0 { | |
| 29 | + m["tools"] = responsesTools(req.Tools) | |
| 30 | + } | |
| 31 | + if req.ToolChoice != "" { | |
| 32 | + m["tool_choice"] = string(req.ToolChoice) | |
| 33 | + } | |
| 34 | + if format := responsesFormat(req.Output); format != nil { | |
| 35 | + text, _ := m["text"].(map[string]any) | |
| 36 | + if text == nil { | |
| 37 | + text = map[string]any{} | |
| 38 | + } | |
| 39 | + text["format"] = format | |
| 40 | + m["text"] = text | |
| 41 | + } | |
| 42 | + m["stream"] = stream | |
| 43 | + if _, set := m["store"]; !set { | |
| 44 | + m["store"] = false | |
| 45 | + } | |
| 46 | + if _, set := m["include"]; !set && m["store"] == false { | |
| 47 | + m["include"] = []string{"reasoning.encrypted_content"} | |
| 48 | + } | |
| 49 | + return json.Marshal(m) | |
| 50 | +} | |
| 51 | + | |
| 52 | +// samplingFields is the request's config — the file's `sampling:` block — | |
| 53 | +// as the fields of a Responses request, written as they are except for the | |
| 54 | +// Chat Completions names this API spells differently: the answer limit | |
| 55 | +// (max_tokens, max_completion_tokens → max_output_tokens) and | |
| 56 | +// reasoning_effort (→ reasoning.effort). | |
| 57 | +func samplingFields(cfg any) (map[string]any, error) { | |
| 58 | + m := map[string]any{} | |
| 59 | + switch c := cfg.(type) { | |
| 60 | + case nil: | |
| 61 | + case map[string]any: | |
| 62 | + for k, v := range c { | |
| 63 | + m[k] = v | |
| 64 | + } | |
| 65 | + default: | |
| 66 | + raw, err := json.Marshal(c) | |
| 67 | + if err != nil { | |
| 68 | + return nil, fmt.Errorf("responses: config: %w", err) | |
| 69 | + } | |
| 70 | + if err := json.Unmarshal(raw, &m); err != nil { | |
| 71 | + return nil, fmt.Errorf("responses: config: %w", err) | |
| 72 | + } | |
| 73 | + } | |
| 74 | + for _, key := range []string{"max_completion_tokens", "max_tokens"} { | |
| 75 | + if v, ok := m[key]; ok { | |
| 76 | + if _, set := m["max_output_tokens"]; !set { | |
| 77 | + m["max_output_tokens"] = v | |
| 78 | + } | |
| 79 | + delete(m, key) | |
| 80 | + } | |
| 81 | + } | |
| 82 | + if v, ok := m["reasoning_effort"]; ok { | |
| 83 | + delete(m, "reasoning_effort") | |
| 84 | + if r, _ := m["reasoning"].(map[string]any); r == nil || r["effort"] == nil { | |
| 85 | + setReasoning(m, "effort", v) | |
| 86 | + } | |
| 87 | + } | |
| 88 | + return m, nil | |
| 89 | +} | |
| 90 | + | |
| 91 | +// setReasoning sets one field of the `reasoning` object, keeping the others. | |
| 92 | +func setReasoning(m map[string]any, key string, value any) { | |
| 93 | + r, _ := m["reasoning"].(map[string]any) | |
| 94 | + if r == nil { | |
| 95 | + r = map[string]any{} | |
| 96 | + } else { | |
| 97 | + copied := make(map[string]any, len(r)+1) | |
| 98 | + for k, v := range r { | |
| 99 | + copied[k] = v | |
| 100 | + } | |
| 101 | + r = copied | |
| 102 | + } | |
| 103 | + r[key] = value | |
| 104 | + m["reasoning"] = r | |
| 105 | +} | |
| 106 | + | |
| 107 | +// responsesTools declares the tools as function tools, not strict: mm's | |
| 108 | +// schemas have optional properties, which strict mode refuses. | |
| 109 | +func responsesTools(tools []*ai.ToolDefinition) []any { | |
| 110 | + out := make([]any, 0, len(tools)) | |
| 111 | + for _, t := range tools { | |
| 112 | + if t == nil { | |
| 113 | + continue | |
| 114 | + } | |
| 115 | + params := t.InputSchema | |
| 116 | + if params == nil { | |
| 117 | + params = map[string]any{"type": "object", "properties": map[string]any{}} | |
| 118 | + } | |
| 119 | + out = append(out, map[string]any{"type": "function", "name": t.Name, "description": t.Description, "parameters": params, "strict": false}) | |
| 120 | + } | |
| 121 | + return out | |
| 122 | +} | |
| 123 | + | |
| 124 | +// responsesFormat is `text.format` for structuredOutput (ticket 80): the | |
| 125 | +// schema, strict as the openai provider sends it; nil for plain text. | |
| 126 | +func responsesFormat(output *ai.ModelOutputConfig) map[string]any { | |
| 127 | + if output == nil || output.Format != "json" { | |
| 128 | + return nil | |
| 129 | + } | |
| 130 | + if output.Schema == nil { | |
| 131 | + return map[string]any{"type": "json_object"} | |
| 132 | + } | |
| 133 | + return map[string]any{"type": "json_schema", "name": "output", "schema": output.Schema, "strict": true} | |
| 134 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,134 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "encoding/json" | ||
| 5 | + "fmt" | ||
| 6 | + | ||
| 7 | + "github.com/firebase/genkit/go/ai" | ||
| 8 | +) | ||
| 9 | + | ||
| 10 | +// responsesRequest builds the JSON body of one call. | ||
| 11 | +// | ||
| 12 | +// body, _ := responsesRequest("gpt-6-luna", req, true, false) | ||
| 13 | +// // {"model":"gpt-6-luna","input":[…],"tools":[…],"stream":true,"store":false,"include":["reasoning.encrypted_content"],…} | ||
| 14 | +func responsesRequest(model string, req *ai.ModelRequest, stream, noThink bool) ([]byte, error) { | ||
| 15 | + m, err := samplingFields(req.Config) | ||
| 16 | + if err != nil { | ||
| 17 | + return nil, err | ||
| 18 | + } | ||
| 19 | + if noThink { | ||
| 20 | + setReasoning(m, "effort", "none") | ||
| 21 | + } | ||
| 22 | + input, err := responsesInput(req.Messages) | ||
| 23 | + if err != nil { | ||
| 24 | + return nil, err | ||
| 25 | + } | ||
| 26 | + m["model"] = model | ||
| 27 | + m["input"] = input | ||
| 28 | + if len(req.Tools) > 0 { | ||
| 29 | + m["tools"] = responsesTools(req.Tools) | ||
| 30 | + } | ||
| 31 | + if req.ToolChoice != "" { | ||
| 32 | + m["tool_choice"] = string(req.ToolChoice) | ||
| 33 | + } | ||
| 34 | + if format := responsesFormat(req.Output); format != nil { | ||
| 35 | + text, _ := m["text"].(map[string]any) | ||
| 36 | + if text == nil { | ||
| 37 | + text = map[string]any{} | ||
| 38 | + } | ||
| 39 | + text["format"] = format | ||
| 40 | + m["text"] = text | ||
| 41 | + } | ||
| 42 | + m["stream"] = stream | ||
| 43 | + if _, set := m["store"]; !set { | ||
| 44 | + m["store"] = false | ||
| 45 | + } | ||
| 46 | + if _, set := m["include"]; !set && m["store"] == false { | ||
| 47 | + m["include"] = []string{"reasoning.encrypted_content"} | ||
| 48 | + } | ||
| 49 | + return json.Marshal(m) | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +// samplingFields is the request's config — the file's `sampling:` block — | ||
| 53 | +// as the fields of a Responses request, written as they are except for the | ||
| 54 | +// Chat Completions names this API spells differently: the answer limit | ||
| 55 | +// (max_tokens, max_completion_tokens → max_output_tokens) and | ||
| 56 | +// reasoning_effort (→ reasoning.effort). | ||
| 57 | +func samplingFields(cfg any) (map[string]any, error) { | ||
| 58 | + m := map[string]any{} | ||
| 59 | + switch c := cfg.(type) { | ||
| 60 | + case nil: | ||
| 61 | + case map[string]any: | ||
| 62 | + for k, v := range c { | ||
| 63 | + m[k] = v | ||
| 64 | + } | ||
| 65 | + default: | ||
| 66 | + raw, err := json.Marshal(c) | ||
| 67 | + if err != nil { | ||
| 68 | + return nil, fmt.Errorf("responses: config: %w", err) | ||
| 69 | + } | ||
| 70 | + if err := json.Unmarshal(raw, &m); err != nil { | ||
| 71 | + return nil, fmt.Errorf("responses: config: %w", err) | ||
| 72 | + } | ||
| 73 | + } | ||
| 74 | + for _, key := range []string{"max_completion_tokens", "max_tokens"} { | ||
| 75 | + if v, ok := m[key]; ok { | ||
| 76 | + if _, set := m["max_output_tokens"]; !set { | ||
| 77 | + m["max_output_tokens"] = v | ||
| 78 | + } | ||
| 79 | + delete(m, key) | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + if v, ok := m["reasoning_effort"]; ok { | ||
| 83 | + delete(m, "reasoning_effort") | ||
| 84 | + if r, _ := m["reasoning"].(map[string]any); r == nil || r["effort"] == nil { | ||
| 85 | + setReasoning(m, "effort", v) | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + return m, nil | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +// setReasoning sets one field of the `reasoning` object, keeping the others. | ||
| 92 | +func setReasoning(m map[string]any, key string, value any) { | ||
| 93 | + r, _ := m["reasoning"].(map[string]any) | ||
| 94 | + if r == nil { | ||
| 95 | + r = map[string]any{} | ||
| 96 | + } else { | ||
| 97 | + copied := make(map[string]any, len(r)+1) | ||
| 98 | + for k, v := range r { | ||
| 99 | + copied[k] = v | ||
| 100 | + } | ||
| 101 | + r = copied | ||
| 102 | + } | ||
| 103 | + r[key] = value | ||
| 104 | + m["reasoning"] = r | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +// responsesTools declares the tools as function tools, not strict: mm's | ||
| 108 | +// schemas have optional properties, which strict mode refuses. | ||
| 109 | +func responsesTools(tools []*ai.ToolDefinition) []any { | ||
| 110 | + out := make([]any, 0, len(tools)) | ||
| 111 | + for _, t := range tools { | ||
| 112 | + if t == nil { | ||
| 113 | + continue | ||
| 114 | + } | ||
| 115 | + params := t.InputSchema | ||
| 116 | + if params == nil { | ||
| 117 | + params = map[string]any{"type": "object", "properties": map[string]any{}} | ||
| 118 | + } | ||
| 119 | + out = append(out, map[string]any{"type": "function", "name": t.Name, "description": t.Description, "parameters": params, "strict": false}) | ||
| 120 | + } | ||
| 121 | + return out | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +// responsesFormat is `text.format` for structuredOutput (ticket 80): the | ||
| 125 | +// schema, strict as the openai provider sends it; nil for plain text. | ||
| 126 | +func responsesFormat(output *ai.ModelOutputConfig) map[string]any { | ||
| 127 | + if output == nil || output.Format != "json" { | ||
| 128 | + return nil | ||
| 129 | + } | ||
| 130 | + if output.Schema == nil { | ||
| 131 | + return map[string]any{"type": "json_object"} | ||
| 132 | + } | ||
| 133 | + return map[string]any{"type": "json_schema", "name": "output", "schema": output.Schema, "strict": true} | ||
| 134 | +} | ||
added
internal/engine/responses_result.go +161 -0 | new file mode 100644 | ||
| @@ -0,0 +1,161 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "encoding/json" | |
| 5 | + "fmt" | |
| 6 | + "strings" | |
| 7 | + | |
| 8 | + "github.com/firebase/genkit/go/ai" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// responsesResult is the little of a Responses answer mm reads. | |
| 12 | +type responsesResult struct { | |
| 13 | + Status string `json:"status"` | |
| 14 | + Output []json.RawMessage `json:"output"` | |
| 15 | + IncompleteDetails *struct { | |
| 16 | + Reason string `json:"reason"` | |
| 17 | + } `json:"incomplete_details"` | |
| 18 | + Error *struct { | |
| 19 | + Message string `json:"message"` | |
| 20 | + } `json:"error"` | |
| 21 | + Usage *struct { | |
| 22 | + InputTokens int `json:"input_tokens"` | |
| 23 | + OutputTokens int `json:"output_tokens"` | |
| 24 | + TotalTokens int `json:"total_tokens"` | |
| 25 | + InputTokensDetails struct { | |
| 26 | + CachedTokens int `json:"cached_tokens"` | |
| 27 | + } `json:"input_tokens_details"` | |
| 28 | + OutputTokensDetails struct { | |
| 29 | + ReasoningTokens int `json:"reasoning_tokens"` | |
| 30 | + } `json:"output_tokens_details"` | |
| 31 | + } `json:"usage"` | |
| 32 | +} | |
| 33 | + | |
| 34 | +// outputItem is one item of the answer's output. | |
| 35 | +type outputItem struct { | |
| 36 | + Type string `json:"type"` | |
| 37 | + CallID string `json:"call_id"` | |
| 38 | + Name string `json:"name"` | |
| 39 | + Arguments string `json:"arguments"` | |
| 40 | + Content []struct { | |
| 41 | + Type string `json:"type"` | |
| 42 | + Text string `json:"text"` | |
| 43 | + Refusal string `json:"refusal"` | |
| 44 | + } `json:"content"` | |
| 45 | +} | |
| 46 | + | |
| 47 | +// modelResponse turns the answer into Genkit's response. A failed answer is | |
| 48 | +// an error; tool arguments that do not parse are the error compat_oai gives | |
| 49 | +// ("could not parse tool args"), so the call is handed back to the model the | |
| 50 | +// same way (toolargs.go). | |
| 51 | +func (r *responsesResult) modelResponse() (*ai.ModelResponse, error) { | |
| 52 | + if r.Status == "failed" { | |
| 53 | + msg := "the response failed" | |
| 54 | + if r.Error != nil && r.Error.Message != "" { | |
| 55 | + msg = r.Error.Message | |
| 56 | + } | |
| 57 | + return nil, fmt.Errorf("stream error: %s", msg) | |
| 58 | + } | |
| 59 | + resp := &ai.ModelResponse{Message: &ai.Message{Role: ai.RoleModel, Content: []*ai.Part{}}, FinishReason: ai.FinishReasonStop} | |
| 60 | + var out outputParts | |
| 61 | + if err := out.collect(r.Output, resp); err != nil { | |
| 62 | + return nil, err | |
| 63 | + } | |
| 64 | + out.fill(resp.Message) | |
| 65 | + r.finish(resp) | |
| 66 | + resp.Usage = r.usage() | |
| 67 | + return resp, nil | |
| 68 | +} | |
| 69 | + | |
| 70 | +// outputParts gathers the output items of an answer. | |
| 71 | +type outputParts struct { | |
| 72 | + reasoning []any | |
| 73 | + text strings.Builder | |
| 74 | + calls []*ai.Part | |
| 75 | +} | |
| 76 | + | |
| 77 | +// collect reads every output item; a refusal sets resp's finish. | |
| 78 | +func (o *outputParts) collect(output []json.RawMessage, resp *ai.ModelResponse) error { | |
| 79 | + for _, raw := range output { | |
| 80 | + var item outputItem | |
| 81 | + if json.Unmarshal(raw, &item) != nil { | |
| 82 | + continue | |
| 83 | + } | |
| 84 | + if err := o.add(item, raw, resp); err != nil { | |
| 85 | + return err | |
| 86 | + } | |
| 87 | + } | |
| 88 | + return nil | |
| 89 | +} | |
| 90 | + | |
| 91 | +// add takes one output item: reasoning kept whole (it goes back to the | |
| 92 | +// server on the next call), text, a refusal, a function call. | |
| 93 | +func (o *outputParts) add(item outputItem, raw json.RawMessage, resp *ai.ModelResponse) error { | |
| 94 | + switch item.Type { | |
| 95 | + case "reasoning": | |
| 96 | + var keep any | |
| 97 | + if json.Unmarshal(raw, &keep) == nil { | |
| 98 | + o.reasoning = append(o.reasoning, keep) | |
| 99 | + } | |
| 100 | + case "message": | |
| 101 | + for _, c := range item.Content { | |
| 102 | + switch c.Type { | |
| 103 | + case "output_text": | |
| 104 | + o.text.WriteString(c.Text) | |
| 105 | + case "refusal": | |
| 106 | + resp.FinishReason, resp.FinishMessage = ai.FinishReasonBlocked, c.Refusal | |
| 107 | + } | |
| 108 | + } | |
| 109 | + case "function_call": | |
| 110 | + input := map[string]any{} | |
| 111 | + if strings.TrimSpace(item.Arguments) != "" { | |
| 112 | + if err := json.Unmarshal([]byte(item.Arguments), &input); err != nil { | |
| 113 | + return fmt.Errorf("could not parse tool args: %w", err) | |
| 114 | + } | |
| 115 | + } | |
| 116 | + o.calls = append(o.calls, ai.NewToolRequestPart(&ai.ToolRequest{Ref: item.CallID, Name: item.Name, Input: input})) | |
| 117 | + } | |
| 118 | + return nil | |
| 119 | +} | |
| 120 | + | |
| 121 | +// fill puts the text, then the calls, in msg, and the reasoning in its | |
| 122 | +// metadata. | |
| 123 | +func (o *outputParts) fill(msg *ai.Message) { | |
| 124 | + if o.text.Len() > 0 { | |
| 125 | + msg.Content = append(msg.Content, ai.NewTextPart(o.text.String())) | |
| 126 | + } | |
| 127 | + msg.Content = append(msg.Content, o.calls...) | |
| 128 | + if len(o.reasoning) > 0 { | |
| 129 | + msg.Metadata = map[string]any{responsesReasoningKey: o.reasoning} | |
| 130 | + } | |
| 131 | +} | |
| 132 | + | |
| 133 | +// finish sets the finish reason of an incomplete answer. | |
| 134 | +func (r *responsesResult) finish(resp *ai.ModelResponse) { | |
| 135 | + if r.Status != "incomplete" || r.IncompleteDetails == nil { | |
| 136 | + return | |
| 137 | + } | |
| 138 | + switch r.IncompleteDetails.Reason { | |
| 139 | + case "max_output_tokens": | |
| 140 | + resp.FinishReason = ai.FinishReasonLength | |
| 141 | + case "content_filter": | |
| 142 | + resp.FinishReason = ai.FinishReasonBlocked | |
| 143 | + default: | |
| 144 | + resp.FinishReason, resp.FinishMessage = ai.FinishReasonOther, r.IncompleteDetails.Reason | |
| 145 | + } | |
| 146 | +} | |
| 147 | + | |
| 148 | +// usage is the answer's token counts in Genkit's terms; nil without any. | |
| 149 | +func (r *responsesResult) usage() *ai.GenerationUsage { | |
| 150 | + u := r.Usage | |
| 151 | + if u == nil { | |
| 152 | + return nil | |
| 153 | + } | |
| 154 | + return &ai.GenerationUsage{ | |
| 155 | + InputTokens: u.InputTokens, | |
| 156 | + OutputTokens: u.OutputTokens, | |
| 157 | + TotalTokens: u.TotalTokens, | |
| 158 | + ThoughtsTokens: u.OutputTokensDetails.ReasoningTokens, | |
| 159 | + CachedContentTokens: u.InputTokensDetails.CachedTokens, | |
| 160 | + } | |
| 161 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,161 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "encoding/json" | ||
| 5 | + "fmt" | ||
| 6 | + "strings" | ||
| 7 | + | ||
| 8 | + "github.com/firebase/genkit/go/ai" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// responsesResult is the little of a Responses answer mm reads. | ||
| 12 | +type responsesResult struct { | ||
| 13 | + Status string `json:"status"` | ||
| 14 | + Output []json.RawMessage `json:"output"` | ||
| 15 | + IncompleteDetails *struct { | ||
| 16 | + Reason string `json:"reason"` | ||
| 17 | + } `json:"incomplete_details"` | ||
| 18 | + Error *struct { | ||
| 19 | + Message string `json:"message"` | ||
| 20 | + } `json:"error"` | ||
| 21 | + Usage *struct { | ||
| 22 | + InputTokens int `json:"input_tokens"` | ||
| 23 | + OutputTokens int `json:"output_tokens"` | ||
| 24 | + TotalTokens int `json:"total_tokens"` | ||
| 25 | + InputTokensDetails struct { | ||
| 26 | + CachedTokens int `json:"cached_tokens"` | ||
| 27 | + } `json:"input_tokens_details"` | ||
| 28 | + OutputTokensDetails struct { | ||
| 29 | + ReasoningTokens int `json:"reasoning_tokens"` | ||
| 30 | + } `json:"output_tokens_details"` | ||
| 31 | + } `json:"usage"` | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +// outputItem is one item of the answer's output. | ||
| 35 | +type outputItem struct { | ||
| 36 | + Type string `json:"type"` | ||
| 37 | + CallID string `json:"call_id"` | ||
| 38 | + Name string `json:"name"` | ||
| 39 | + Arguments string `json:"arguments"` | ||
| 40 | + Content []struct { | ||
| 41 | + Type string `json:"type"` | ||
| 42 | + Text string `json:"text"` | ||
| 43 | + Refusal string `json:"refusal"` | ||
| 44 | + } `json:"content"` | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +// modelResponse turns the answer into Genkit's response. A failed answer is | ||
| 48 | +// an error; tool arguments that do not parse are the error compat_oai gives | ||
| 49 | +// ("could not parse tool args"), so the call is handed back to the model the | ||
| 50 | +// same way (toolargs.go). | ||
| 51 | +func (r *responsesResult) modelResponse() (*ai.ModelResponse, error) { | ||
| 52 | + if r.Status == "failed" { | ||
| 53 | + msg := "the response failed" | ||
| 54 | + if r.Error != nil && r.Error.Message != "" { | ||
| 55 | + msg = r.Error.Message | ||
| 56 | + } | ||
| 57 | + return nil, fmt.Errorf("stream error: %s", msg) | ||
| 58 | + } | ||
| 59 | + resp := &ai.ModelResponse{Message: &ai.Message{Role: ai.RoleModel, Content: []*ai.Part{}}, FinishReason: ai.FinishReasonStop} | ||
| 60 | + var out outputParts | ||
| 61 | + if err := out.collect(r.Output, resp); err != nil { | ||
| 62 | + return nil, err | ||
| 63 | + } | ||
| 64 | + out.fill(resp.Message) | ||
| 65 | + r.finish(resp) | ||
| 66 | + resp.Usage = r.usage() | ||
| 67 | + return resp, nil | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +// outputParts gathers the output items of an answer. | ||
| 71 | +type outputParts struct { | ||
| 72 | + reasoning []any | ||
| 73 | + text strings.Builder | ||
| 74 | + calls []*ai.Part | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +// collect reads every output item; a refusal sets resp's finish. | ||
| 78 | +func (o *outputParts) collect(output []json.RawMessage, resp *ai.ModelResponse) error { | ||
| 79 | + for _, raw := range output { | ||
| 80 | + var item outputItem | ||
| 81 | + if json.Unmarshal(raw, &item) != nil { | ||
| 82 | + continue | ||
| 83 | + } | ||
| 84 | + if err := o.add(item, raw, resp); err != nil { | ||
| 85 | + return err | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + return nil | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +// add takes one output item: reasoning kept whole (it goes back to the | ||
| 92 | +// server on the next call), text, a refusal, a function call. | ||
| 93 | +func (o *outputParts) add(item outputItem, raw json.RawMessage, resp *ai.ModelResponse) error { | ||
| 94 | + switch item.Type { | ||
| 95 | + case "reasoning": | ||
| 96 | + var keep any | ||
| 97 | + if json.Unmarshal(raw, &keep) == nil { | ||
| 98 | + o.reasoning = append(o.reasoning, keep) | ||
| 99 | + } | ||
| 100 | + case "message": | ||
| 101 | + for _, c := range item.Content { | ||
| 102 | + switch c.Type { | ||
| 103 | + case "output_text": | ||
| 104 | + o.text.WriteString(c.Text) | ||
| 105 | + case "refusal": | ||
| 106 | + resp.FinishReason, resp.FinishMessage = ai.FinishReasonBlocked, c.Refusal | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + case "function_call": | ||
| 110 | + input := map[string]any{} | ||
| 111 | + if strings.TrimSpace(item.Arguments) != "" { | ||
| 112 | + if err := json.Unmarshal([]byte(item.Arguments), &input); err != nil { | ||
| 113 | + return fmt.Errorf("could not parse tool args: %w", err) | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | + o.calls = append(o.calls, ai.NewToolRequestPart(&ai.ToolRequest{Ref: item.CallID, Name: item.Name, Input: input})) | ||
| 117 | + } | ||
| 118 | + return nil | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +// fill puts the text, then the calls, in msg, and the reasoning in its | ||
| 122 | +// metadata. | ||
| 123 | +func (o *outputParts) fill(msg *ai.Message) { | ||
| 124 | + if o.text.Len() > 0 { | ||
| 125 | + msg.Content = append(msg.Content, ai.NewTextPart(o.text.String())) | ||
| 126 | + } | ||
| 127 | + msg.Content = append(msg.Content, o.calls...) | ||
| 128 | + if len(o.reasoning) > 0 { | ||
| 129 | + msg.Metadata = map[string]any{responsesReasoningKey: o.reasoning} | ||
| 130 | + } | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +// finish sets the finish reason of an incomplete answer. | ||
| 134 | +func (r *responsesResult) finish(resp *ai.ModelResponse) { | ||
| 135 | + if r.Status != "incomplete" || r.IncompleteDetails == nil { | ||
| 136 | + return | ||
| 137 | + } | ||
| 138 | + switch r.IncompleteDetails.Reason { | ||
| 139 | + case "max_output_tokens": | ||
| 140 | + resp.FinishReason = ai.FinishReasonLength | ||
| 141 | + case "content_filter": | ||
| 142 | + resp.FinishReason = ai.FinishReasonBlocked | ||
| 143 | + default: | ||
| 144 | + resp.FinishReason, resp.FinishMessage = ai.FinishReasonOther, r.IncompleteDetails.Reason | ||
| 145 | + } | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +// usage is the answer's token counts in Genkit's terms; nil without any. | ||
| 149 | +func (r *responsesResult) usage() *ai.GenerationUsage { | ||
| 150 | + u := r.Usage | ||
| 151 | + if u == nil { | ||
| 152 | + return nil | ||
| 153 | + } | ||
| 154 | + return &ai.GenerationUsage{ | ||
| 155 | + InputTokens: u.InputTokens, | ||
| 156 | + OutputTokens: u.OutputTokens, | ||
| 157 | + TotalTokens: u.TotalTokens, | ||
| 158 | + ThoughtsTokens: u.OutputTokensDetails.ReasoningTokens, | ||
| 159 | + CachedContentTokens: u.InputTokensDetails.CachedTokens, | ||
| 160 | + } | ||
| 161 | +} | ||
added
internal/engine/responses_stream.go +155 -0 | new file mode 100644 | ||
| @@ -0,0 +1,155 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "bufio" | |
| 5 | + "context" | |
| 6 | + "encoding/json" | |
| 7 | + "errors" | |
| 8 | + "fmt" | |
| 9 | + "io" | |
| 10 | + "strings" | |
| 11 | + | |
| 12 | + "github.com/firebase/genkit/go/ai" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// responsesEvent is one streamed event: its type and the fields mm reads. | |
| 16 | +type responsesEvent struct { | |
| 17 | + Type string `json:"type"` | |
| 18 | + Delta string `json:"delta"` | |
| 19 | + ItemID string `json:"item_id"` | |
| 20 | + Message string `json:"message"` | |
| 21 | + Item *json.RawMessage `json:"item"` | |
| 22 | + Response *responsesResult `json:"response"` | |
| 23 | +} | |
| 24 | + | |
| 25 | +// readResponsesStream reads the SSE events of a streamed call: text deltas | |
| 26 | +// go to Genkit's callback, function-call argument deltas too (the runaway | |
| 27 | +// guard and the watchdog read them), reasoning to the turn's listener | |
| 28 | +// (reasoning.go). The answer is the one `response.completed` (or | |
| 29 | +// `response.incomplete`, `response.failed`) carries. A stream that ends | |
| 30 | +// without one broke: "stream error", which the model call retries once. | |
| 31 | +func readResponsesStream(ctx context.Context, body io.Reader, cb ai.ModelStreamCallback) (*responsesResult, error) { | |
| 32 | + st := &responsesStream{ctx: ctx, cb: cb, onReasoning: reasoningFrom(ctx), calls: map[string]*ai.ToolRequest{}} | |
| 33 | + sc := bufio.NewScanner(body) | |
| 34 | + sc.Buffer(make([]byte, 64<<10), maxSSELine*8) | |
| 35 | + for sc.Scan() { | |
| 36 | + ev, data, ok := eventOf(sc.Text()) | |
| 37 | + if !ok { | |
| 38 | + continue | |
| 39 | + } | |
| 40 | + if res, done, err := st.handle(ev, data); done || err != nil { | |
| 41 | + return res, err | |
| 42 | + } | |
| 43 | + } | |
| 44 | + return nil, streamEnd(ctx, sc.Err()) | |
| 45 | +} | |
| 46 | + | |
| 47 | +// eventOf decodes one SSE line into an event; ok is false for anything that | |
| 48 | +// is not one (a comment, the [DONE] mark, a line that is not JSON). | |
| 49 | +func eventOf(line string) (responsesEvent, string, bool) { | |
| 50 | + var ev responsesEvent | |
| 51 | + data, ok := strings.CutPrefix(strings.TrimSpace(line), "data:") | |
| 52 | + data = strings.TrimSpace(data) | |
| 53 | + if !ok || data == "" || data == "[DONE]" || json.Unmarshal([]byte(data), &ev) != nil { | |
| 54 | + return ev, "", false | |
| 55 | + } | |
| 56 | + return ev, data, true | |
| 57 | +} | |
| 58 | + | |
| 59 | +// streamEnd is the error of a stream that ended without its final event: | |
| 60 | +// the reader's error (a cancellation as it is), or an unexpected end. | |
| 61 | +func streamEnd(ctx context.Context, err error) error { | |
| 62 | + switch { | |
| 63 | + case err != nil && (errors.Is(err, context.Canceled) || ctx.Err() != nil): | |
| 64 | + return err | |
| 65 | + case err != nil: | |
| 66 | + return fmt.Errorf("stream error: %w", err) | |
| 67 | + } | |
| 68 | + return fmt.Errorf("stream error: the stream ended without response.completed (unexpected EOF)") | |
| 69 | +} | |
| 70 | + | |
| 71 | +// responsesStream is the state of one streamed call: where the parts go, | |
| 72 | +// and the function calls announced so far (item id → name and call id). | |
| 73 | +type responsesStream struct { | |
| 74 | + ctx context.Context | |
| 75 | + cb ai.ModelStreamCallback | |
| 76 | + onReasoning func(string) | |
| 77 | + calls map[string]*ai.ToolRequest | |
| 78 | +} | |
| 79 | + | |
| 80 | +// handle takes one event. done is true once the answer (or a failure) came. | |
| 81 | +func (st *responsesStream) handle(ev responsesEvent, data string) (*responsesResult, bool, error) { | |
| 82 | + switch ev.Type { | |
| 83 | + case "response.output_text.delta": | |
| 84 | + return nil, false, sendPart(st.ctx, st.cb, ai.NewTextPart(ev.Delta)) | |
| 85 | + case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": | |
| 86 | + if st.onReasoning != nil && ev.Delta != "" { | |
| 87 | + st.onReasoning(ev.Delta) | |
| 88 | + } | |
| 89 | + case "response.output_item.added": | |
| 90 | + st.announce(ev.Item) | |
| 91 | + case "response.function_call_arguments.delta": | |
| 92 | + call := st.calls[ev.ItemID] | |
| 93 | + if call == nil { | |
| 94 | + call = &ai.ToolRequest{} | |
| 95 | + } | |
| 96 | + return nil, false, sendPart(st.ctx, st.cb, ai.NewToolRequestPart(&ai.ToolRequest{Name: call.Name, Ref: call.Ref, Input: ev.Delta})) | |
| 97 | + case "response.completed", "response.incomplete", "response.failed": | |
| 98 | + res, err := finalResponse(ev) | |
| 99 | + return res, true, err | |
| 100 | + case "error": | |
| 101 | + return nil, true, st.streamError(ev, data) | |
| 102 | + } | |
| 103 | + return nil, false, nil | |
| 104 | +} | |
| 105 | + | |
| 106 | +// announce remembers a function call the server starts, for its argument | |
| 107 | +// deltas, which only carry the item id. | |
| 108 | +func (st *responsesStream) announce(raw *json.RawMessage) { | |
| 109 | + if raw == nil { | |
| 110 | + return | |
| 111 | + } | |
| 112 | + var item outputItem | |
| 113 | + var id struct { | |
| 114 | + ID string `json:"id"` | |
| 115 | + } | |
| 116 | + if json.Unmarshal(*raw, &item) == nil && json.Unmarshal(*raw, &id) == nil && item.Type == "function_call" { | |
| 117 | + st.calls[id.ID] = &ai.ToolRequest{Name: item.Name, Ref: item.CallID} | |
| 118 | + } | |
| 119 | +} | |
| 120 | + | |
| 121 | +// finalResponse is the answer a final event carries; a failed one without a | |
| 122 | +// status is marked failed. | |
| 123 | +func finalResponse(ev responsesEvent) (*responsesResult, error) { | |
| 124 | + if ev.Response == nil { | |
| 125 | + return nil, fmt.Errorf("stream error: %s without a response", ev.Type) | |
| 126 | + } | |
| 127 | + if ev.Type == "response.failed" && ev.Response.Status == "" { | |
| 128 | + ev.Response.Status = "failed" | |
| 129 | + } | |
| 130 | + return ev.Response, nil | |
| 131 | +} | |
| 132 | + | |
| 133 | +// streamError reports an error event to the turn's listener and returns it. | |
| 134 | +func (st *responsesStream) streamError(ev responsesEvent, data string) error { | |
| 135 | + msg := ev.Message | |
| 136 | + if msg == "" { | |
| 137 | + msg = data | |
| 138 | + } | |
| 139 | + if errs := serverErrorsFrom(st.ctx); errs != nil { | |
| 140 | + errs.record(msg) | |
| 141 | + } | |
| 142 | + return fmt.Errorf("stream error: %s", msg) | |
| 143 | +} | |
| 144 | + | |
| 145 | +// sendPart hands one part to Genkit's callback; a callback error stops the | |
| 146 | +// stream (the runaway guard uses it), worded as compat_oai words it. | |
| 147 | +func sendPart(ctx context.Context, cb ai.ModelStreamCallback, part *ai.Part) error { | |
| 148 | + if cb == nil { | |
| 149 | + return nil | |
| 150 | + } | |
| 151 | + if err := cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{part}}); err != nil { | |
| 152 | + return fmt.Errorf("callback error: %w", err) | |
| 153 | + } | |
| 154 | + return nil | |
| 155 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,155 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "bufio" | ||
| 5 | + "context" | ||
| 6 | + "encoding/json" | ||
| 7 | + "errors" | ||
| 8 | + "fmt" | ||
| 9 | + "io" | ||
| 10 | + "strings" | ||
| 11 | + | ||
| 12 | + "github.com/firebase/genkit/go/ai" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// responsesEvent is one streamed event: its type and the fields mm reads. | ||
| 16 | +type responsesEvent struct { | ||
| 17 | + Type string `json:"type"` | ||
| 18 | + Delta string `json:"delta"` | ||
| 19 | + ItemID string `json:"item_id"` | ||
| 20 | + Message string `json:"message"` | ||
| 21 | + Item *json.RawMessage `json:"item"` | ||
| 22 | + Response *responsesResult `json:"response"` | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +// readResponsesStream reads the SSE events of a streamed call: text deltas | ||
| 26 | +// go to Genkit's callback, function-call argument deltas too (the runaway | ||
| 27 | +// guard and the watchdog read them), reasoning to the turn's listener | ||
| 28 | +// (reasoning.go). The answer is the one `response.completed` (or | ||
| 29 | +// `response.incomplete`, `response.failed`) carries. A stream that ends | ||
| 30 | +// without one broke: "stream error", which the model call retries once. | ||
| 31 | +func readResponsesStream(ctx context.Context, body io.Reader, cb ai.ModelStreamCallback) (*responsesResult, error) { | ||
| 32 | + st := &responsesStream{ctx: ctx, cb: cb, onReasoning: reasoningFrom(ctx), calls: map[string]*ai.ToolRequest{}} | ||
| 33 | + sc := bufio.NewScanner(body) | ||
| 34 | + sc.Buffer(make([]byte, 64<<10), maxSSELine*8) | ||
| 35 | + for sc.Scan() { | ||
| 36 | + ev, data, ok := eventOf(sc.Text()) | ||
| 37 | + if !ok { | ||
| 38 | + continue | ||
| 39 | + } | ||
| 40 | + if res, done, err := st.handle(ev, data); done || err != nil { | ||
| 41 | + return res, err | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | + return nil, streamEnd(ctx, sc.Err()) | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +// eventOf decodes one SSE line into an event; ok is false for anything that | ||
| 48 | +// is not one (a comment, the [DONE] mark, a line that is not JSON). | ||
| 49 | +func eventOf(line string) (responsesEvent, string, bool) { | ||
| 50 | + var ev responsesEvent | ||
| 51 | + data, ok := strings.CutPrefix(strings.TrimSpace(line), "data:") | ||
| 52 | + data = strings.TrimSpace(data) | ||
| 53 | + if !ok || data == "" || data == "[DONE]" || json.Unmarshal([]byte(data), &ev) != nil { | ||
| 54 | + return ev, "", false | ||
| 55 | + } | ||
| 56 | + return ev, data, true | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +// streamEnd is the error of a stream that ended without its final event: | ||
| 60 | +// the reader's error (a cancellation as it is), or an unexpected end. | ||
| 61 | +func streamEnd(ctx context.Context, err error) error { | ||
| 62 | + switch { | ||
| 63 | + case err != nil && (errors.Is(err, context.Canceled) || ctx.Err() != nil): | ||
| 64 | + return err | ||
| 65 | + case err != nil: | ||
| 66 | + return fmt.Errorf("stream error: %w", err) | ||
| 67 | + } | ||
| 68 | + return fmt.Errorf("stream error: the stream ended without response.completed (unexpected EOF)") | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +// responsesStream is the state of one streamed call: where the parts go, | ||
| 72 | +// and the function calls announced so far (item id → name and call id). | ||
| 73 | +type responsesStream struct { | ||
| 74 | + ctx context.Context | ||
| 75 | + cb ai.ModelStreamCallback | ||
| 76 | + onReasoning func(string) | ||
| 77 | + calls map[string]*ai.ToolRequest | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +// handle takes one event. done is true once the answer (or a failure) came. | ||
| 81 | +func (st *responsesStream) handle(ev responsesEvent, data string) (*responsesResult, bool, error) { | ||
| 82 | + switch ev.Type { | ||
| 83 | + case "response.output_text.delta": | ||
| 84 | + return nil, false, sendPart(st.ctx, st.cb, ai.NewTextPart(ev.Delta)) | ||
| 85 | + case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": | ||
| 86 | + if st.onReasoning != nil && ev.Delta != "" { | ||
| 87 | + st.onReasoning(ev.Delta) | ||
| 88 | + } | ||
| 89 | + case "response.output_item.added": | ||
| 90 | + st.announce(ev.Item) | ||
| 91 | + case "response.function_call_arguments.delta": | ||
| 92 | + call := st.calls[ev.ItemID] | ||
| 93 | + if call == nil { | ||
| 94 | + call = &ai.ToolRequest{} | ||
| 95 | + } | ||
| 96 | + return nil, false, sendPart(st.ctx, st.cb, ai.NewToolRequestPart(&ai.ToolRequest{Name: call.Name, Ref: call.Ref, Input: ev.Delta})) | ||
| 97 | + case "response.completed", "response.incomplete", "response.failed": | ||
| 98 | + res, err := finalResponse(ev) | ||
| 99 | + return res, true, err | ||
| 100 | + case "error": | ||
| 101 | + return nil, true, st.streamError(ev, data) | ||
| 102 | + } | ||
| 103 | + return nil, false, nil | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +// announce remembers a function call the server starts, for its argument | ||
| 107 | +// deltas, which only carry the item id. | ||
| 108 | +func (st *responsesStream) announce(raw *json.RawMessage) { | ||
| 109 | + if raw == nil { | ||
| 110 | + return | ||
| 111 | + } | ||
| 112 | + var item outputItem | ||
| 113 | + var id struct { | ||
| 114 | + ID string `json:"id"` | ||
| 115 | + } | ||
| 116 | + if json.Unmarshal(*raw, &item) == nil && json.Unmarshal(*raw, &id) == nil && item.Type == "function_call" { | ||
| 117 | + st.calls[id.ID] = &ai.ToolRequest{Name: item.Name, Ref: item.CallID} | ||
| 118 | + } | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +// finalResponse is the answer a final event carries; a failed one without a | ||
| 122 | +// status is marked failed. | ||
| 123 | +func finalResponse(ev responsesEvent) (*responsesResult, error) { | ||
| 124 | + if ev.Response == nil { | ||
| 125 | + return nil, fmt.Errorf("stream error: %s without a response", ev.Type) | ||
| 126 | + } | ||
| 127 | + if ev.Type == "response.failed" && ev.Response.Status == "" { | ||
| 128 | + ev.Response.Status = "failed" | ||
| 129 | + } | ||
| 130 | + return ev.Response, nil | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +// streamError reports an error event to the turn's listener and returns it. | ||
| 134 | +func (st *responsesStream) streamError(ev responsesEvent, data string) error { | ||
| 135 | + msg := ev.Message | ||
| 136 | + if msg == "" { | ||
| 137 | + msg = data | ||
| 138 | + } | ||
| 139 | + if errs := serverErrorsFrom(st.ctx); errs != nil { | ||
| 140 | + errs.record(msg) | ||
| 141 | + } | ||
| 142 | + return fmt.Errorf("stream error: %s", msg) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +// sendPart hands one part to Genkit's callback; a callback error stops the | ||
| 146 | +// stream (the runaway guard uses it), worded as compat_oai words it. | ||
| 147 | +func sendPart(ctx context.Context, cb ai.ModelStreamCallback, part *ai.Part) error { | ||
| 148 | + if cb == nil { | ||
| 149 | + return nil | ||
| 150 | + } | ||
| 151 | + if err := cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{part}}); err != nil { | ||
| 152 | + return fmt.Errorf("callback error: %w", err) | ||
| 153 | + } | ||
| 154 | + return nil | ||
| 155 | +} | ||
added
internal/engine/skills.go +65 -0 | new file mode 100644 | ||
| @@ -0,0 +1,65 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "fmt" | |
| 5 | + "strings" | |
| 6 | + "sync/atomic" | |
| 7 | + | |
| 8 | + "github.com/firebase/genkit/go/ai" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// Skills counts the skills loaded — one per response of `read_skill`. Shown | |
| 12 | +// next to the command count: seeing which procedure the agent chose to follow is | |
| 13 | +// half the point of this part. | |
| 14 | +func Skills(history []*ai.Message) int { | |
| 15 | + n := 0 | |
| 16 | + for _, m := range history { | |
| 17 | + for _, p := range m.Content { | |
| 18 | + if !p.IsToolResponse() || p.ToolResponse == nil || p.ToolResponse.Name != toolSkill { | |
| 19 | + continue | |
| 20 | + } | |
| 21 | + if !strings.HasPrefix(strings.TrimSpace(responseText(p.ToolResponse)), skillMiss) { | |
| 22 | + n++ | |
| 23 | + } | |
| 24 | + } | |
| 25 | + } | |
| 26 | + return n | |
| 27 | +} | |
| 28 | + | |
| 29 | +// skillMiss is how `read_skill` answers a name that is not in the catalogue. | |
| 30 | +// Counting those as skills made the number say the opposite of what it is | |
| 31 | +// for: `📖 2 skill(s)` could mean two failed lookups and nothing loaded. | |
| 32 | +const skillMiss = "[skill:" | |
| 33 | + | |
| 34 | +// responseText is a tool response as text. Every tool here returns a string; | |
| 35 | +// anything else is formatted rather than dropped, so a change of shape shows | |
| 36 | +// up as an odd count instead of a silent zero. | |
| 37 | +func responseText(r *ai.ToolResponse) string { | |
| 38 | + if s, ok := r.Output.(string); ok { | |
| 39 | + return s | |
| 40 | + } | |
| 41 | + return fmt.Sprintf("%v", r.Output) | |
| 42 | +} | |
| 43 | + | |
| 44 | +// skillsDeclared says this agent has a skills catalogue at all. Set once by | |
| 45 | +// main, read by the three turn recaps. | |
| 46 | +// | |
| 47 | +// Why it exists: `📖 N skill(s)` used to be printed only when N > 0, so | |
| 48 | +// "no skill applied" and "a skill applied and the model ignored it" looked | |
| 49 | +// identical — nothing at all. Showing `📖 0 skill(s)` is the whole point; | |
| 50 | +// showing it in a project that has no skills would be noise. | |
| 51 | +var skillsDeclared atomic.Bool | |
| 52 | + | |
| 53 | +// DeclareSkills records whether the agent was given any skill. | |
| 54 | +func DeclareSkills(yes bool) { skillsDeclared.Store(yes) } | |
| 55 | + | |
| 56 | +// SkillsAvailable reports it, for the turn recaps. | |
| 57 | +func SkillsAvailable() bool { return skillsDeclared.Load() } | |
| 58 | + | |
| 59 | +// LSPCalls counts the `lsp` tool responses in a history — questions put to a | |
| 60 | +// language server (definition, references, hover, symbols, diagnostics, | |
| 61 | +// rename). Shown apart from the commands for the same reason as the file | |
| 62 | +// ops: asking the compiler is not running a command. | |
| 63 | +func LSPCalls(history []*ai.Message) int { | |
| 64 | + return responses(history, toolLSP) | |
| 65 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,65 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "fmt" | ||
| 5 | + "strings" | ||
| 6 | + "sync/atomic" | ||
| 7 | + | ||
| 8 | + "github.com/firebase/genkit/go/ai" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// Skills counts the skills loaded — one per response of `read_skill`. Shown | ||
| 12 | +// next to the command count: seeing which procedure the agent chose to follow is | ||
| 13 | +// half the point of this part. | ||
| 14 | +func Skills(history []*ai.Message) int { | ||
| 15 | + n := 0 | ||
| 16 | + for _, m := range history { | ||
| 17 | + for _, p := range m.Content { | ||
| 18 | + if !p.IsToolResponse() || p.ToolResponse == nil || p.ToolResponse.Name != toolSkill { | ||
| 19 | + continue | ||
| 20 | + } | ||
| 21 | + if !strings.HasPrefix(strings.TrimSpace(responseText(p.ToolResponse)), skillMiss) { | ||
| 22 | + n++ | ||
| 23 | + } | ||
| 24 | + } | ||
| 25 | + } | ||
| 26 | + return n | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +// skillMiss is how `read_skill` answers a name that is not in the catalogue. | ||
| 30 | +// Counting those as skills made the number say the opposite of what it is | ||
| 31 | +// for: `📖 2 skill(s)` could mean two failed lookups and nothing loaded. | ||
| 32 | +const skillMiss = "[skill:" | ||
| 33 | + | ||
| 34 | +// responseText is a tool response as text. Every tool here returns a string; | ||
| 35 | +// anything else is formatted rather than dropped, so a change of shape shows | ||
| 36 | +// up as an odd count instead of a silent zero. | ||
| 37 | +func responseText(r *ai.ToolResponse) string { | ||
| 38 | + if s, ok := r.Output.(string); ok { | ||
| 39 | + return s | ||
| 40 | + } | ||
| 41 | + return fmt.Sprintf("%v", r.Output) | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// skillsDeclared says this agent has a skills catalogue at all. Set once by | ||
| 45 | +// main, read by the three turn recaps. | ||
| 46 | +// | ||
| 47 | +// Why it exists: `📖 N skill(s)` used to be printed only when N > 0, so | ||
| 48 | +// "no skill applied" and "a skill applied and the model ignored it" looked | ||
| 49 | +// identical — nothing at all. Showing `📖 0 skill(s)` is the whole point; | ||
| 50 | +// showing it in a project that has no skills would be noise. | ||
| 51 | +var skillsDeclared atomic.Bool | ||
| 52 | + | ||
| 53 | +// DeclareSkills records whether the agent was given any skill. | ||
| 54 | +func DeclareSkills(yes bool) { skillsDeclared.Store(yes) } | ||
| 55 | + | ||
| 56 | +// SkillsAvailable reports it, for the turn recaps. | ||
| 57 | +func SkillsAvailable() bool { return skillsDeclared.Load() } | ||
| 58 | + | ||
| 59 | +// LSPCalls counts the `lsp` tool responses in a history — questions put to a | ||
| 60 | +// language server (definition, references, hover, symbols, diagnostics, | ||
| 61 | +// rename). Shown apart from the commands for the same reason as the file | ||
| 62 | +// ops: asking the compiler is not running a command. | ||
| 63 | +func LSPCalls(history []*ai.Message) int { | ||
| 64 | + return responses(history, toolLSP) | ||
| 65 | +} | ||
modified
internal/engine/struggle.go +43 -26 | @@ -64,39 +64,56 @@ func (e *Engine) reportTurn(ctx context.Context, resp *ai.ModelResponse, err err | ||
| 64 | 64 | // |
| 65 | 65 | // turnStruggle(nil, errStalled) // ✖ stalled, true |
| 66 | 66 | func turnStruggle(resp *ai.ModelResponse, err error) (ui.Struggle, bool) { |
| 67 | - if err == nil { | |
| 68 | - if reasoningCut(resp, nil) { | |
| 69 | - return ui.Struggle{Severe: true, Label: cutLabel()}, true | |
| 70 | - } | |
| 71 | - if s, ok := answerStruggle(resp); ok { | |
| 72 | - return s, true | |
| 73 | - } | |
| 74 | - if resp != nil && strings.TrimSpace(resp.Text()) == "" && len(resp.ToolRequests()) == 0 { | |
| 75 | - return ui.Struggle{Label: "empty answer"}, true | |
| 76 | - } | |
| 77 | - return ui.Struggle{}, false | |
| 78 | - } | |
| 79 | - var runaway runawayError | |
| 80 | - if _, ok := looped(err); ok { | |
| 81 | - return ui.Struggle{Severe: true, Label: "looped — stopped"}, true | |
| 67 | + if err != nil { | |
| 68 | + return errorStruggle(err) | |
| 82 | 69 | } |
| 83 | - switch { | |
| 84 | - case errors.Is(err, errStalled): | |
| 85 | - return ui.Struggle{Severe: true, Label: "stalled"}, true | |
| 86 | - case errors.As(err, &runaway): | |
| 87 | - return ui.Struggle{Severe: true, Label: "runaway tool call"}, true | |
| 88 | - case errors.Is(err, ai.ErrMaxTurnsExceeded) || strings.Contains(err.Error(), "exceeded maximum tool call iterations"): | |
| 89 | - return ui.Struggle{Severe: true, Label: "max turns reached"}, true | |
| 70 | + if reasoningCut(resp, nil) { | |
| 71 | + return ui.Struggle{Severe: true, Label: cutLabel()}, true | |
| 90 | 72 | } |
| 91 | - if m := unknownTool.FindStringSubmatch(err.Error()); m != nil { | |
| 92 | - return ui.Struggle{Severe: true, Label: "unknown tool: " + m[1]}, true | |
| 73 | + if s, ok := answerStruggle(resp); ok { | |
| 74 | + return s, true | |
| 93 | 75 | } |
| 94 | - if errors.Is(err, ai.ErrToolNotFound) { | |
| 95 | - return ui.Struggle{Severe: true, Label: "unknown tool"}, true | |
| 76 | + if resp != nil && strings.TrimSpace(resp.Text()) == "" && len(resp.ToolRequests()) == 0 { | |
| 77 | + return ui.Struggle{Label: "empty answer"}, true | |
| 96 | 78 | } |
| 97 | 79 | return ui.Struggle{}, false |
| 98 | 80 | } |
| 99 | 81 | |
| 82 | +// errorStruggles name the failures that end a turn, checked in order. | |
| 83 | +var errorStruggles = []struct { | |
| 84 | + label string | |
| 85 | + is func(error) bool | |
| 86 | +}{ | |
| 87 | + {"looped — stopped", func(err error) bool { _, ok := looped(err); return ok }}, | |
| 88 | + {"stalled", func(err error) bool { return errors.Is(err, errStalled) }}, | |
| 89 | + {"runaway tool call", func(err error) bool { var r runawayError; return errors.As(err, &r) }}, | |
| 90 | + {"max turns reached", func(err error) bool { | |
| 91 | + return errors.Is(err, ai.ErrMaxTurnsExceeded) || strings.Contains(err.Error(), "exceeded maximum tool call iterations") | |
| 92 | + }}, | |
| 93 | +} | |
| 94 | + | |
| 95 | +// errorStruggle is the severe struggle a failed turn shows, when its error | |
| 96 | +// is a known one. | |
| 97 | +func errorStruggle(err error) (ui.Struggle, bool) { | |
| 98 | + label := "" | |
| 99 | + for _, s := range errorStruggles { | |
| 100 | + if s.is(err) { | |
| 101 | + label = s.label | |
| 102 | + break | |
| 103 | + } | |
| 104 | + } | |
| 105 | + if m := unknownTool.FindStringSubmatch(err.Error()); label == "" && m != nil { | |
| 106 | + label = "unknown tool: " + m[1] | |
| 107 | + } | |
| 108 | + if label == "" && errors.Is(err, ai.ErrToolNotFound) { | |
| 109 | + label = "unknown tool" | |
| 110 | + } | |
| 111 | + if label == "" { | |
| 112 | + return ui.Struggle{}, false | |
| 113 | + } | |
| 114 | + return ui.Struggle{Severe: true, Label: label}, true | |
| 115 | +} | |
| 116 | + | |
| 100 | 117 | // contextStruggle warns when the last model call read contextFullShare |
| 101 | 118 | // percent of the window or more. An unknown window says nothing. |
| 102 | 119 | // |
| @@ -64,39 +64,56 @@ func (e *Engine) reportTurn(ctx context.Context, resp *ai.ModelResponse, err err | |||
| 64 | // | 64 | // |
| 65 | // turnStruggle(nil, errStalled) // ✖ stalled, true | 65 | // turnStruggle(nil, errStalled) // ✖ stalled, true |
| 66 | func turnStruggle(resp *ai.ModelResponse, err error) (ui.Struggle, bool) { | 66 | func turnStruggle(resp *ai.ModelResponse, err error) (ui.Struggle, bool) { |
| 67 | - if err == nil { | 67 | + if err != nil { |
| 68 | - if reasoningCut(resp, nil) { | 68 | + return errorStruggle(err) |
| 69 | - return ui.Struggle{Severe: true, Label: cutLabel()}, true | ||
| 70 | - } | ||
| 71 | - if s, ok := answerStruggle(resp); ok { | ||
| 72 | - return s, true | ||
| 73 | - } | ||
| 74 | - if resp != nil && strings.TrimSpace(resp.Text()) == "" && len(resp.ToolRequests()) == 0 { | ||
| 75 | - return ui.Struggle{Label: "empty answer"}, true | ||
| 76 | - } | ||
| 77 | - return ui.Struggle{}, false | ||
| 78 | - } | ||
| 79 | - var runaway runawayError | ||
| 80 | - if _, ok := looped(err); ok { | ||
| 81 | - return ui.Struggle{Severe: true, Label: "looped — stopped"}, true | ||
| 82 | } | 69 | } |
| 83 | - switch { | 70 | + if reasoningCut(resp, nil) { |
| 84 | - case errors.Is(err, errStalled): | 71 | + return ui.Struggle{Severe: true, Label: cutLabel()}, true |
| 85 | - return ui.Struggle{Severe: true, Label: "stalled"}, true | ||
| 86 | - case errors.As(err, &runaway): | ||
| 87 | - return ui.Struggle{Severe: true, Label: "runaway tool call"}, true | ||
| 88 | - case errors.Is(err, ai.ErrMaxTurnsExceeded) || strings.Contains(err.Error(), "exceeded maximum tool call iterations"): | ||
| 89 | - return ui.Struggle{Severe: true, Label: "max turns reached"}, true | ||
| 90 | } | 72 | } |
| 91 | - if m := unknownTool.FindStringSubmatch(err.Error()); m != nil { | 73 | + if s, ok := answerStruggle(resp); ok { |
| 92 | - return ui.Struggle{Severe: true, Label: "unknown tool: " + m[1]}, true | 74 | + return s, true |
| 93 | } | 75 | } |
| 94 | - if errors.Is(err, ai.ErrToolNotFound) { | 76 | + if resp != nil && strings.TrimSpace(resp.Text()) == "" && len(resp.ToolRequests()) == 0 { |
| 95 | - return ui.Struggle{Severe: true, Label: "unknown tool"}, true | 77 | + return ui.Struggle{Label: "empty answer"}, true |
| 96 | } | 78 | } |
| 97 | return ui.Struggle{}, false | 79 | return ui.Struggle{}, false |
| 98 | } | 80 | } |
| 99 | 81 | ||
| 82 | +// errorStruggles name the failures that end a turn, checked in order. | ||
| 83 | +var errorStruggles = []struct { | ||
| 84 | + label string | ||
| 85 | + is func(error) bool | ||
| 86 | +}{ | ||
| 87 | + {"looped — stopped", func(err error) bool { _, ok := looped(err); return ok }}, | ||
| 88 | + {"stalled", func(err error) bool { return errors.Is(err, errStalled) }}, | ||
| 89 | + {"runaway tool call", func(err error) bool { var r runawayError; return errors.As(err, &r) }}, | ||
| 90 | + {"max turns reached", func(err error) bool { | ||
| 91 | + return errors.Is(err, ai.ErrMaxTurnsExceeded) || strings.Contains(err.Error(), "exceeded maximum tool call iterations") | ||
| 92 | + }}, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +// errorStruggle is the severe struggle a failed turn shows, when its error | ||
| 96 | +// is a known one. | ||
| 97 | +func errorStruggle(err error) (ui.Struggle, bool) { | ||
| 98 | + label := "" | ||
| 99 | + for _, s := range errorStruggles { | ||
| 100 | + if s.is(err) { | ||
| 101 | + label = s.label | ||
| 102 | + break | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + if m := unknownTool.FindStringSubmatch(err.Error()); label == "" && m != nil { | ||
| 106 | + label = "unknown tool: " + m[1] | ||
| 107 | + } | ||
| 108 | + if label == "" && errors.Is(err, ai.ErrToolNotFound) { | ||
| 109 | + label = "unknown tool" | ||
| 110 | + } | ||
| 111 | + if label == "" { | ||
| 112 | + return ui.Struggle{}, false | ||
| 113 | + } | ||
| 114 | + return ui.Struggle{Severe: true, Label: label}, true | ||
| 115 | +} | ||
| 116 | + | ||
| 100 | // contextStruggle warns when the last model call read contextFullShare | 117 | // contextStruggle warns when the last model call read contextFullShare |
| 101 | // percent of the window or more. An unknown window says nothing. | 118 | // percent of the window or more. An unknown window says nothing. |
| 102 | // | 119 | // |
added
internal/engine/summarize.go +104 -0 | new file mode 100644 | ||
| @@ -0,0 +1,104 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "fmt" | |
| 6 | + "maps" | |
| 7 | + "mm/internal/config" | |
| 8 | + "strings" | |
| 9 | + "sync/atomic" | |
| 10 | + | |
| 11 | + "github.com/firebase/genkit/go/ai" | |
| 12 | + "github.com/firebase/genkit/go/genkit" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// Summarize asks the model for a plain-text answer to `messages` — no tools, | |
| 16 | +// no screen output. It exists for the context compression (internal/compact): | |
| 17 | +// the summary must not stream onto the screen as if it were an answer, and a | |
| 18 | +// request that offers tools invites the model to call them instead of writing. | |
| 19 | +// It goes through the same Genkit and the same model reference as Generate, | |
| 20 | +// so it lands on the same provider and the same server. | |
| 21 | +// | |
| 22 | +// The watchdog is kept, with twice the usual patience: this is the longest | |
| 23 | +// prefill of the session (the whole old history at once) and nothing streams | |
| 24 | +// until it is done. Streaming stays on so that the summary's own tokens beat | |
| 25 | +// the watchdog while it is being written. | |
| 26 | +// | |
| 27 | +// A thinking model is asked not to reason (withoutThinking, llama.cpp | |
| 28 | +// providers and Ollama), over what the sampling config says: its reasoning counts against maxTokens and is not in | |
| 29 | +// resp.Text(), so it can spend the whole budget and leave no summary. On the | |
| 30 | +// other providers that can still happen; emptySummary then says so. | |
| 31 | +func (e *Engine) Summarize(ctx context.Context, messages []*ai.Message, maxTokens int) (string, error) { | |
| 32 | + // The agent's sampling, minus what does not apply here: `parallel_tool_calls` | |
| 33 | + // without tools is a 400 on the OpenAI API, and the answer limit is the | |
| 34 | + // summary's budget, not the answer's — under the name the config uses | |
| 35 | + // (max_completion_tokens for the OpenAI models that refuse max_tokens). | |
| 36 | + sampling := maps.Clone(config.Cfg.Sampling) | |
| 37 | + if sampling == nil { | |
| 38 | + sampling = map[string]any{} | |
| 39 | + } | |
| 40 | + delete(sampling, "parallel_tool_calls") | |
| 41 | + sampling[limitKey(sampling)] = maxTokens | |
| 42 | + | |
| 43 | + genCtx, pl, cancel := watchdog(ctx, 2*config.Cfg.WatchdogTimeout, | |
| 44 | + firstTokenTimeout(2*config.Cfg.WatchdogTimeout, config.Cfg.FirstTokenTimeout)) | |
| 45 | + defer cancel() | |
| 46 | + beat := pl.beat | |
| 47 | + // The same heartbeat, and deliberately no display: a summary is written | |
| 48 | + // behind the user's back, and a model that thinks about it must not spill | |
| 49 | + // that onto the screen in the middle of their conversation. The length is | |
| 50 | + // kept for emptySummary. | |
| 51 | + var reasoned atomic.Int64 | |
| 52 | + genCtx = WithReasoning(genCtx, func(s string) { reasoned.Add(int64(len(s))); beat() }) | |
| 53 | + genCtx = withoutThinking(genCtx) | |
| 54 | + genCtx, srvErrs := withServerErrors(genCtx) | |
| 55 | + genCtx = withPromptProgress(genCtx, func(promptProgress) { pl.alive() }) | |
| 56 | + | |
| 57 | + resp, err := genkit.Generate(genCtx, e.G, | |
| 58 | + ai.WithModelName(e.Model), | |
| 59 | + ai.WithMessages(messages...), | |
| 60 | + ai.WithConfig(sampling), | |
| 61 | + ai.WithStreaming(func(_ context.Context, _ *ai.ModelResponseChunk) error { | |
| 62 | + beat() | |
| 63 | + return nil | |
| 64 | + }), | |
| 65 | + ) | |
| 66 | + if err != nil { | |
| 67 | + return "", summaryError(ctx, genCtx, srvErrs, err) | |
| 68 | + } | |
| 69 | + text := strings.TrimSpace(resp.Text()) | |
| 70 | + if text == "" { | |
| 71 | + return "", emptySummary(resp, maxTokens, int(reasoned.Load())) | |
| 72 | + } | |
| 73 | + return text, nil | |
| 74 | +} | |
| 75 | + | |
| 76 | +// summaryError says why a summary failed: a silence (the same test as in | |
| 77 | +// generate: the contexts, not the wrapped error), the server's own words when | |
| 78 | +// it streamed some, else the error. | |
| 79 | +func summaryError(ctx, genCtx context.Context, srvErrs *serverErrors, err error) error { | |
| 80 | + if genCtx.Err() != nil && ctx.Err() == nil { | |
| 81 | + return fmt.Errorf("summary timed out (stalled)") | |
| 82 | + } | |
| 83 | + if msg := srvErrs.take(); msg != "" { | |
| 84 | + return &serverError{msg: msg, err: err} | |
| 85 | + } | |
| 86 | + return err | |
| 87 | +} | |
| 88 | + | |
| 89 | +// emptySummary is the error of a summary request that came back without | |
| 90 | +// text, with what the response says about why: the line lands in the session | |
| 91 | +// file's `errors`, and "empty summary" alone sent an investigation to replay | |
| 92 | +// an 18k-token request. The usual cause is a thinking model that reasoned | |
| 93 | +// until max_tokens; the line then names the setting to raise. | |
| 94 | +func emptySummary(resp *ai.ModelResponse, maxTokens, reasoned int) error { | |
| 95 | + out := 0 | |
| 96 | + if resp.Usage != nil { | |
| 97 | + out = resp.Usage.OutputTokens | |
| 98 | + } | |
| 99 | + why := fmt.Sprintf("finish: %s, %d output token(s), %d char(s) of reasoning", resp.FinishReason, out, reasoned) | |
| 100 | + if resp.FinishReason == ai.FinishReasonLength && reasoned > 0 { | |
| 101 | + return fmt.Errorf("the model returned an empty summary: it reasoned until the %d-token limit (%s) — raise context.summaryMaxTokens", maxTokens, why) | |
| 102 | + } | |
| 103 | + return fmt.Errorf("the model returned an empty summary (%s)", why) | |
| 104 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,104 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "fmt" | ||
| 6 | + "maps" | ||
| 7 | + "mm/internal/config" | ||
| 8 | + "strings" | ||
| 9 | + "sync/atomic" | ||
| 10 | + | ||
| 11 | + "github.com/firebase/genkit/go/ai" | ||
| 12 | + "github.com/firebase/genkit/go/genkit" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// Summarize asks the model for a plain-text answer to `messages` — no tools, | ||
| 16 | +// no screen output. It exists for the context compression (internal/compact): | ||
| 17 | +// the summary must not stream onto the screen as if it were an answer, and a | ||
| 18 | +// request that offers tools invites the model to call them instead of writing. | ||
| 19 | +// It goes through the same Genkit and the same model reference as Generate, | ||
| 20 | +// so it lands on the same provider and the same server. | ||
| 21 | +// | ||
| 22 | +// The watchdog is kept, with twice the usual patience: this is the longest | ||
| 23 | +// prefill of the session (the whole old history at once) and nothing streams | ||
| 24 | +// until it is done. Streaming stays on so that the summary's own tokens beat | ||
| 25 | +// the watchdog while it is being written. | ||
| 26 | +// | ||
| 27 | +// A thinking model is asked not to reason (withoutThinking, llama.cpp | ||
| 28 | +// providers and Ollama), over what the sampling config says: its reasoning counts against maxTokens and is not in | ||
| 29 | +// resp.Text(), so it can spend the whole budget and leave no summary. On the | ||
| 30 | +// other providers that can still happen; emptySummary then says so. | ||
| 31 | +func (e *Engine) Summarize(ctx context.Context, messages []*ai.Message, maxTokens int) (string, error) { | ||
| 32 | + // The agent's sampling, minus what does not apply here: `parallel_tool_calls` | ||
| 33 | + // without tools is a 400 on the OpenAI API, and the answer limit is the | ||
| 34 | + // summary's budget, not the answer's — under the name the config uses | ||
| 35 | + // (max_completion_tokens for the OpenAI models that refuse max_tokens). | ||
| 36 | + sampling := maps.Clone(config.Cfg.Sampling) | ||
| 37 | + if sampling == nil { | ||
| 38 | + sampling = map[string]any{} | ||
| 39 | + } | ||
| 40 | + delete(sampling, "parallel_tool_calls") | ||
| 41 | + sampling[limitKey(sampling)] = maxTokens | ||
| 42 | + | ||
| 43 | + genCtx, pl, cancel := watchdog(ctx, 2*config.Cfg.WatchdogTimeout, | ||
| 44 | + firstTokenTimeout(2*config.Cfg.WatchdogTimeout, config.Cfg.FirstTokenTimeout)) | ||
| 45 | + defer cancel() | ||
| 46 | + beat := pl.beat | ||
| 47 | + // The same heartbeat, and deliberately no display: a summary is written | ||
| 48 | + // behind the user's back, and a model that thinks about it must not spill | ||
| 49 | + // that onto the screen in the middle of their conversation. The length is | ||
| 50 | + // kept for emptySummary. | ||
| 51 | + var reasoned atomic.Int64 | ||
| 52 | + genCtx = WithReasoning(genCtx, func(s string) { reasoned.Add(int64(len(s))); beat() }) | ||
| 53 | + genCtx = withoutThinking(genCtx) | ||
| 54 | + genCtx, srvErrs := withServerErrors(genCtx) | ||
| 55 | + genCtx = withPromptProgress(genCtx, func(promptProgress) { pl.alive() }) | ||
| 56 | + | ||
| 57 | + resp, err := genkit.Generate(genCtx, e.G, | ||
| 58 | + ai.WithModelName(e.Model), | ||
| 59 | + ai.WithMessages(messages...), | ||
| 60 | + ai.WithConfig(sampling), | ||
| 61 | + ai.WithStreaming(func(_ context.Context, _ *ai.ModelResponseChunk) error { | ||
| 62 | + beat() | ||
| 63 | + return nil | ||
| 64 | + }), | ||
| 65 | + ) | ||
| 66 | + if err != nil { | ||
| 67 | + return "", summaryError(ctx, genCtx, srvErrs, err) | ||
| 68 | + } | ||
| 69 | + text := strings.TrimSpace(resp.Text()) | ||
| 70 | + if text == "" { | ||
| 71 | + return "", emptySummary(resp, maxTokens, int(reasoned.Load())) | ||
| 72 | + } | ||
| 73 | + return text, nil | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +// summaryError says why a summary failed: a silence (the same test as in | ||
| 77 | +// generate: the contexts, not the wrapped error), the server's own words when | ||
| 78 | +// it streamed some, else the error. | ||
| 79 | +func summaryError(ctx, genCtx context.Context, srvErrs *serverErrors, err error) error { | ||
| 80 | + if genCtx.Err() != nil && ctx.Err() == nil { | ||
| 81 | + return fmt.Errorf("summary timed out (stalled)") | ||
| 82 | + } | ||
| 83 | + if msg := srvErrs.take(); msg != "" { | ||
| 84 | + return &serverError{msg: msg, err: err} | ||
| 85 | + } | ||
| 86 | + return err | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +// emptySummary is the error of a summary request that came back without | ||
| 90 | +// text, with what the response says about why: the line lands in the session | ||
| 91 | +// file's `errors`, and "empty summary" alone sent an investigation to replay | ||
| 92 | +// an 18k-token request. The usual cause is a thinking model that reasoned | ||
| 93 | +// until max_tokens; the line then names the setting to raise. | ||
| 94 | +func emptySummary(resp *ai.ModelResponse, maxTokens, reasoned int) error { | ||
| 95 | + out := 0 | ||
| 96 | + if resp.Usage != nil { | ||
| 97 | + out = resp.Usage.OutputTokens | ||
| 98 | + } | ||
| 99 | + why := fmt.Sprintf("finish: %s, %d output token(s), %d char(s) of reasoning", resp.FinishReason, out, reasoned) | ||
| 100 | + if resp.FinishReason == ai.FinishReasonLength && reasoned > 0 { | ||
| 101 | + return fmt.Errorf("the model returned an empty summary: it reasoned until the %d-token limit (%s) — raise context.summaryMaxTokens", maxTokens, why) | ||
| 102 | + } | ||
| 103 | + return fmt.Errorf("the model returned an empty summary (%s)", why) | ||
| 104 | +} | ||
modified
internal/engine/toolargs.go +6 -2 | @@ -139,8 +139,12 @@ const maxCutRetries = 1 | ||
| 139 | 139 | // reasoningCut reports whether a model reply was cut by the answer limit |
| 140 | 140 | // before it said or called anything. |
| 141 | 141 | func reasoningCut(resp *ai.ModelResponse, err error) bool { |
| 142 | - return err == nil && resp != nil && resp.FinishReason == ai.FinishReasonLength && | |
| 143 | - strings.TrimSpace(resp.Text()) == "" && len(resp.ToolRequests()) == 0 | |
| 142 | + return err == nil && resp != nil && resp.FinishReason == ai.FinishReasonLength && saidNothing(resp) | |
| 143 | +} | |
| 144 | + | |
| 145 | +// saidNothing tells whether a reply has neither text nor a tool call. | |
| 146 | +func saidNothing(resp *ai.ModelResponse) bool { | |
| 147 | + return strings.TrimSpace(resp.Text()) == "" && len(resp.ToolRequests()) == 0 | |
| 144 | 148 | } |
| 145 | 149 | |
| 146 | 150 | // cutRetryNote is what the model reads after a reply cut mid-reasoning. |
| @@ -139,8 +139,12 @@ const maxCutRetries = 1 | |||
| 139 | // reasoningCut reports whether a model reply was cut by the answer limit | 139 | // reasoningCut reports whether a model reply was cut by the answer limit |
| 140 | // before it said or called anything. | 140 | // before it said or called anything. |
| 141 | func reasoningCut(resp *ai.ModelResponse, err error) bool { | 141 | func reasoningCut(resp *ai.ModelResponse, err error) bool { |
| 142 | - return err == nil && resp != nil && resp.FinishReason == ai.FinishReasonLength && | 142 | + return err == nil && resp != nil && resp.FinishReason == ai.FinishReasonLength && saidNothing(resp) |
| 143 | - strings.TrimSpace(resp.Text()) == "" && len(resp.ToolRequests()) == 0 | 143 | +} |
| 144 | + | ||
| 145 | +// saidNothing tells whether a reply has neither text nor a tool call. | ||
| 146 | +func saidNothing(resp *ai.ModelResponse) bool { | ||
| 147 | + return strings.TrimSpace(resp.Text()) == "" && len(resp.ToolRequests()) == 0 | ||
| 144 | } | 148 | } |
| 145 | 149 | ||
| 146 | // cutRetryNote is what the model reads after a reply cut mid-reasoning. | 150 | // cutRetryNote is what the model reads after a reply cut mid-reasoning. |
added
internal/engine/toolnormalize.go +158 -0 | new file mode 100644 | ||
| @@ -0,0 +1,158 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "encoding/json" | |
| 5 | + "strconv" | |
| 6 | + "strings" | |
| 7 | +) | |
| 8 | + | |
| 9 | +// normalizeToolInput repairs the arguments of a write_file or edit_file call | |
| 10 | +// when the repair is unambiguous, and reports whether it changed anything. | |
| 11 | +// Any other tool, or an input it cannot read, is returned as it is: the | |
| 12 | +// schema validation then says what is wrong. | |
| 13 | +// | |
| 14 | +// in := map[string]any{"file_path": "a.go", "edits": []any{map[string]any{"old_text": "x", "new_text": "y"}}} | |
| 15 | +// out, changed := normalizeToolInput("edit_file", in) | |
| 16 | +// // out = {"path": "a.go", "edits": [{"old": "x", "new": "y"}]}, changed = true | |
| 17 | +func normalizeToolInput(tool string, input any) (any, bool) { | |
| 18 | + args, ok := input.(map[string]any) | |
| 19 | + if !ok { | |
| 20 | + return input, false | |
| 21 | + } | |
| 22 | + switch tool { | |
| 23 | + case "write_file": | |
| 24 | + return normalizeWrite(args) | |
| 25 | + case "edit_file": | |
| 26 | + return normalizeEdit(args) | |
| 27 | + } | |
| 28 | + return input, false | |
| 29 | +} | |
| 30 | + | |
| 31 | +func normalizeWrite(args map[string]any) (any, bool) { | |
| 32 | + out := copyMap(args) | |
| 33 | + changed := rename(out, pathKeys) | |
| 34 | + changed = rename(out, contentKeys) || changed | |
| 35 | + return out, changed | |
| 36 | +} | |
| 37 | + | |
| 38 | +func normalizeEdit(args map[string]any) (any, bool) { | |
| 39 | + out := copyMap(args) | |
| 40 | + changed := rename(out, pathKeys) | |
| 41 | + edits, reshaped := editList(out) | |
| 42 | + changed = reshaped || changed | |
| 43 | + list, ok := edits.([]any) | |
| 44 | + if !ok { | |
| 45 | + return out, changed | |
| 46 | + } | |
| 47 | + fixed := make([]any, 0, len(list)) | |
| 48 | + for _, item := range list { | |
| 49 | + e, ok := item.(map[string]any) | |
| 50 | + if !ok { | |
| 51 | + fixed = append(fixed, item) | |
| 52 | + continue | |
| 53 | + } | |
| 54 | + e, edited := normalizeOneEdit(out, e) | |
| 55 | + changed = edited || changed | |
| 56 | + fixed = append(fixed, e) | |
| 57 | + } | |
| 58 | + out["edits"] = fixed | |
| 59 | + return out, changed | |
| 60 | +} | |
| 61 | + | |
| 62 | +// editList finds the edits however the model sent them: the list as a JSON | |
| 63 | +// string, one edit without the list, or the edit's fields at the top level | |
| 64 | +// (taken out of out). It reports whether it had to reshape them. | |
| 65 | +func editList(out map[string]any) (any, bool) { | |
| 66 | + edits, changed := out["edits"], false | |
| 67 | + if s, ok := edits.(string); ok { // the list sent as a JSON string | |
| 68 | + var decoded any | |
| 69 | + if json.Unmarshal([]byte(s), &decoded) == nil { | |
| 70 | + edits, changed = decoded, true | |
| 71 | + } | |
| 72 | + } | |
| 73 | + if one, ok := edits.(map[string]any); ok { // one edit without the list | |
| 74 | + edits, changed = []any{one}, true | |
| 75 | + } | |
| 76 | + if edits == nil && firstKey(out, oldKeys) != "" { // edit fields at the top level | |
| 77 | + edit := map[string]any{} | |
| 78 | + for _, k := range append(append([]string{}, oldKeys...), newKeys...) { | |
| 79 | + if v, ok := out[k]; ok { | |
| 80 | + edit[k] = v | |
| 81 | + delete(out, k) | |
| 82 | + } | |
| 83 | + } | |
| 84 | + edits, changed = []any{edit}, true | |
| 85 | + } | |
| 86 | + return edits, changed | |
| 87 | +} | |
| 88 | + | |
| 89 | +// normalizeOneEdit fixes one edit (a copy): a `path` inside it moves up to | |
| 90 | +// out when out has none, aliases get the real keys, a `line` sent as a | |
| 91 | +// string becomes an integer (ticket 241), and any other key goes — the edit | |
| 92 | +// schema allows no other. It reports whether it changed anything. | |
| 93 | +func normalizeOneEdit(out, e map[string]any) (map[string]any, bool) { | |
| 94 | + e = copyMap(e) | |
| 95 | + changed := false | |
| 96 | + if _, hasPath := out["path"]; !hasPath { | |
| 97 | + if k := firstKey(e, pathKeys); k != "" { | |
| 98 | + out["path"] = e[k] | |
| 99 | + changed = true | |
| 100 | + } | |
| 101 | + } | |
| 102 | + changed = rename(e, oldKeys) || changed | |
| 103 | + changed = rename(e, newKeys) || changed | |
| 104 | + if fixed, ok := editLine(e["line"]); ok { | |
| 105 | + e["line"], changed = fixed, true | |
| 106 | + } | |
| 107 | + for k := range e { | |
| 108 | + if k != "old" && k != "new" && k != "line" { | |
| 109 | + delete(e, k) | |
| 110 | + changed = true | |
| 111 | + } | |
| 112 | + } | |
| 113 | + return e, changed | |
| 114 | +} | |
| 115 | + | |
| 116 | +// editLine turns an edit's `line` sent as a string ("8") into an integer. | |
| 117 | +// ok is false when there is nothing to change. | |
| 118 | +func editLine(v any) (int64, bool) { | |
| 119 | + s, isString := v.(string) | |
| 120 | + if !isString { | |
| 121 | + return 0, false | |
| 122 | + } | |
| 123 | + n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64) | |
| 124 | + return n, err == nil | |
| 125 | +} | |
| 126 | + | |
| 127 | +// rename moves the first alias found to the real key (keys[0]), when the real | |
| 128 | +// key is absent. It reports whether it moved something. | |
| 129 | +func rename(m map[string]any, keys []string) bool { | |
| 130 | + if _, ok := m[keys[0]]; ok { | |
| 131 | + return false | |
| 132 | + } | |
| 133 | + for _, k := range keys[1:] { | |
| 134 | + if v, ok := m[k]; ok { | |
| 135 | + m[keys[0]] = v | |
| 136 | + delete(m, k) | |
| 137 | + return true | |
| 138 | + } | |
| 139 | + } | |
| 140 | + return false | |
| 141 | +} | |
| 142 | + | |
| 143 | +func firstKey(m map[string]any, keys []string) string { | |
| 144 | + for _, k := range keys { | |
| 145 | + if _, ok := m[k]; ok { | |
| 146 | + return k | |
| 147 | + } | |
| 148 | + } | |
| 149 | + return "" | |
| 150 | +} | |
| 151 | + | |
| 152 | +func copyMap(m map[string]any) map[string]any { | |
| 153 | + out := make(map[string]any, len(m)) | |
| 154 | + for k, v := range m { | |
| 155 | + out[k] = v | |
| 156 | + } | |
| 157 | + return out | |
| 158 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,158 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "encoding/json" | ||
| 5 | + "strconv" | ||
| 6 | + "strings" | ||
| 7 | +) | ||
| 8 | + | ||
| 9 | +// normalizeToolInput repairs the arguments of a write_file or edit_file call | ||
| 10 | +// when the repair is unambiguous, and reports whether it changed anything. | ||
| 11 | +// Any other tool, or an input it cannot read, is returned as it is: the | ||
| 12 | +// schema validation then says what is wrong. | ||
| 13 | +// | ||
| 14 | +// in := map[string]any{"file_path": "a.go", "edits": []any{map[string]any{"old_text": "x", "new_text": "y"}}} | ||
| 15 | +// out, changed := normalizeToolInput("edit_file", in) | ||
| 16 | +// // out = {"path": "a.go", "edits": [{"old": "x", "new": "y"}]}, changed = true | ||
| 17 | +func normalizeToolInput(tool string, input any) (any, bool) { | ||
| 18 | + args, ok := input.(map[string]any) | ||
| 19 | + if !ok { | ||
| 20 | + return input, false | ||
| 21 | + } | ||
| 22 | + switch tool { | ||
| 23 | + case "write_file": | ||
| 24 | + return normalizeWrite(args) | ||
| 25 | + case "edit_file": | ||
| 26 | + return normalizeEdit(args) | ||
| 27 | + } | ||
| 28 | + return input, false | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +func normalizeWrite(args map[string]any) (any, bool) { | ||
| 32 | + out := copyMap(args) | ||
| 33 | + changed := rename(out, pathKeys) | ||
| 34 | + changed = rename(out, contentKeys) || changed | ||
| 35 | + return out, changed | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +func normalizeEdit(args map[string]any) (any, bool) { | ||
| 39 | + out := copyMap(args) | ||
| 40 | + changed := rename(out, pathKeys) | ||
| 41 | + edits, reshaped := editList(out) | ||
| 42 | + changed = reshaped || changed | ||
| 43 | + list, ok := edits.([]any) | ||
| 44 | + if !ok { | ||
| 45 | + return out, changed | ||
| 46 | + } | ||
| 47 | + fixed := make([]any, 0, len(list)) | ||
| 48 | + for _, item := range list { | ||
| 49 | + e, ok := item.(map[string]any) | ||
| 50 | + if !ok { | ||
| 51 | + fixed = append(fixed, item) | ||
| 52 | + continue | ||
| 53 | + } | ||
| 54 | + e, edited := normalizeOneEdit(out, e) | ||
| 55 | + changed = edited || changed | ||
| 56 | + fixed = append(fixed, e) | ||
| 57 | + } | ||
| 58 | + out["edits"] = fixed | ||
| 59 | + return out, changed | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +// editList finds the edits however the model sent them: the list as a JSON | ||
| 63 | +// string, one edit without the list, or the edit's fields at the top level | ||
| 64 | +// (taken out of out). It reports whether it had to reshape them. | ||
| 65 | +func editList(out map[string]any) (any, bool) { | ||
| 66 | + edits, changed := out["edits"], false | ||
| 67 | + if s, ok := edits.(string); ok { // the list sent as a JSON string | ||
| 68 | + var decoded any | ||
| 69 | + if json.Unmarshal([]byte(s), &decoded) == nil { | ||
| 70 | + edits, changed = decoded, true | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + if one, ok := edits.(map[string]any); ok { // one edit without the list | ||
| 74 | + edits, changed = []any{one}, true | ||
| 75 | + } | ||
| 76 | + if edits == nil && firstKey(out, oldKeys) != "" { // edit fields at the top level | ||
| 77 | + edit := map[string]any{} | ||
| 78 | + for _, k := range append(append([]string{}, oldKeys...), newKeys...) { | ||
| 79 | + if v, ok := out[k]; ok { | ||
| 80 | + edit[k] = v | ||
| 81 | + delete(out, k) | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + edits, changed = []any{edit}, true | ||
| 85 | + } | ||
| 86 | + return edits, changed | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +// normalizeOneEdit fixes one edit (a copy): a `path` inside it moves up to | ||
| 90 | +// out when out has none, aliases get the real keys, a `line` sent as a | ||
| 91 | +// string becomes an integer (ticket 241), and any other key goes — the edit | ||
| 92 | +// schema allows no other. It reports whether it changed anything. | ||
| 93 | +func normalizeOneEdit(out, e map[string]any) (map[string]any, bool) { | ||
| 94 | + e = copyMap(e) | ||
| 95 | + changed := false | ||
| 96 | + if _, hasPath := out["path"]; !hasPath { | ||
| 97 | + if k := firstKey(e, pathKeys); k != "" { | ||
| 98 | + out["path"] = e[k] | ||
| 99 | + changed = true | ||
| 100 | + } | ||
| 101 | + } | ||
| 102 | + changed = rename(e, oldKeys) || changed | ||
| 103 | + changed = rename(e, newKeys) || changed | ||
| 104 | + if fixed, ok := editLine(e["line"]); ok { | ||
| 105 | + e["line"], changed = fixed, true | ||
| 106 | + } | ||
| 107 | + for k := range e { | ||
| 108 | + if k != "old" && k != "new" && k != "line" { | ||
| 109 | + delete(e, k) | ||
| 110 | + changed = true | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + return e, changed | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +// editLine turns an edit's `line` sent as a string ("8") into an integer. | ||
| 117 | +// ok is false when there is nothing to change. | ||
| 118 | +func editLine(v any) (int64, bool) { | ||
| 119 | + s, isString := v.(string) | ||
| 120 | + if !isString { | ||
| 121 | + return 0, false | ||
| 122 | + } | ||
| 123 | + n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64) | ||
| 124 | + return n, err == nil | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +// rename moves the first alias found to the real key (keys[0]), when the real | ||
| 128 | +// key is absent. It reports whether it moved something. | ||
| 129 | +func rename(m map[string]any, keys []string) bool { | ||
| 130 | + if _, ok := m[keys[0]]; ok { | ||
| 131 | + return false | ||
| 132 | + } | ||
| 133 | + for _, k := range keys[1:] { | ||
| 134 | + if v, ok := m[k]; ok { | ||
| 135 | + m[keys[0]] = v | ||
| 136 | + delete(m, k) | ||
| 137 | + return true | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | + return false | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +func firstKey(m map[string]any, keys []string) string { | ||
| 144 | + for _, k := range keys { | ||
| 145 | + if _, ok := m[k]; ok { | ||
| 146 | + return k | ||
| 147 | + } | ||
| 148 | + } | ||
| 149 | + return "" | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +func copyMap(m map[string]any) map[string]any { | ||
| 153 | + out := make(map[string]any, len(m)) | ||
| 154 | + for k, v := range m { | ||
| 155 | + out[k] = v | ||
| 156 | + } | ||
| 157 | + return out | ||
| 158 | +} | ||
added
internal/engine/toolscalars.go +64 -0 | new file mode 100644 | ||
| @@ -0,0 +1,64 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strconv" | |
| 5 | + "strings" | |
| 6 | +) | |
| 7 | + | |
| 8 | +// coerceScalars converts the top-level arguments a model sent as strings when | |
| 9 | +// the schema wants a boolean, an integer or a number, and the string reads | |
| 10 | +// unambiguously as one: "true"/"false" (any case), "8", "0.5". It reports | |
| 11 | +// whether it changed anything. Anything else — "yes", "8a", a string | |
| 12 | +// parameter — is left for the validation to report (ticket 237: Olala-v1.0-mini | |
| 13 | +// sent `"numbered": "true"`, `"start": "1"`, `"end": "8"` to read_file three | |
| 14 | +// times in a row, each refused, and never got the numbered lines it needed). | |
| 15 | +// | |
| 16 | +// coerceScalars(map[string]any{"path": "a.go", "numbered": "true", "start": "1"}, readFileSchema) | |
| 17 | +// // {"path": "a.go", "numbered": true, "start": 1}, true | |
| 18 | +func coerceScalars(input any, schema map[string]any) (any, bool) { | |
| 19 | + args, ok := input.(map[string]any) | |
| 20 | + props, _ := schema["properties"].(map[string]any) | |
| 21 | + if !ok || len(props) == 0 { | |
| 22 | + return input, false | |
| 23 | + } | |
| 24 | + out, changed := args, false | |
| 25 | + for name, value := range args { | |
| 26 | + s, isString := value.(string) | |
| 27 | + prop, _ := props[name].(map[string]any) | |
| 28 | + if !isString || prop == nil { | |
| 29 | + continue | |
| 30 | + } | |
| 31 | + converted, ok := convertScalar(strings.TrimSpace(s), prop["type"]) | |
| 32 | + if !ok { | |
| 33 | + continue | |
| 34 | + } | |
| 35 | + if !changed { | |
| 36 | + out, changed = copyMap(args), true | |
| 37 | + } | |
| 38 | + out[name] = converted | |
| 39 | + } | |
| 40 | + return out, changed | |
| 41 | +} | |
| 42 | + | |
| 43 | +// convertScalar reads s as the JSON schema type typ ("boolean", "integer", | |
| 44 | +// "number"), and reports whether it could. | |
| 45 | +func convertScalar(s string, typ any) (any, bool) { | |
| 46 | + switch typ { | |
| 47 | + case "boolean": | |
| 48 | + switch strings.ToLower(s) { | |
| 49 | + case "true": | |
| 50 | + return true, true | |
| 51 | + case "false": | |
| 52 | + return false, true | |
| 53 | + } | |
| 54 | + case "integer": | |
| 55 | + if n, err := strconv.ParseInt(s, 10, 64); err == nil { | |
| 56 | + return n, true | |
| 57 | + } | |
| 58 | + case "number": | |
| 59 | + if f, err := strconv.ParseFloat(s, 64); err == nil { | |
| 60 | + return f, true | |
| 61 | + } | |
| 62 | + } | |
| 63 | + return nil, false | |
| 64 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strconv" | ||
| 5 | + "strings" | ||
| 6 | +) | ||
| 7 | + | ||
| 8 | +// coerceScalars converts the top-level arguments a model sent as strings when | ||
| 9 | +// the schema wants a boolean, an integer or a number, and the string reads | ||
| 10 | +// unambiguously as one: "true"/"false" (any case), "8", "0.5". It reports | ||
| 11 | +// whether it changed anything. Anything else — "yes", "8a", a string | ||
| 12 | +// parameter — is left for the validation to report (ticket 237: Olala-v1.0-mini | ||
| 13 | +// sent `"numbered": "true"`, `"start": "1"`, `"end": "8"` to read_file three | ||
| 14 | +// times in a row, each refused, and never got the numbered lines it needed). | ||
| 15 | +// | ||
| 16 | +// coerceScalars(map[string]any{"path": "a.go", "numbered": "true", "start": "1"}, readFileSchema) | ||
| 17 | +// // {"path": "a.go", "numbered": true, "start": 1}, true | ||
| 18 | +func coerceScalars(input any, schema map[string]any) (any, bool) { | ||
| 19 | + args, ok := input.(map[string]any) | ||
| 20 | + props, _ := schema["properties"].(map[string]any) | ||
| 21 | + if !ok || len(props) == 0 { | ||
| 22 | + return input, false | ||
| 23 | + } | ||
| 24 | + out, changed := args, false | ||
| 25 | + for name, value := range args { | ||
| 26 | + s, isString := value.(string) | ||
| 27 | + prop, _ := props[name].(map[string]any) | ||
| 28 | + if !isString || prop == nil { | ||
| 29 | + continue | ||
| 30 | + } | ||
| 31 | + converted, ok := convertScalar(strings.TrimSpace(s), prop["type"]) | ||
| 32 | + if !ok { | ||
| 33 | + continue | ||
| 34 | + } | ||
| 35 | + if !changed { | ||
| 36 | + out, changed = copyMap(args), true | ||
| 37 | + } | ||
| 38 | + out[name] = converted | ||
| 39 | + } | ||
| 40 | + return out, changed | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +// convertScalar reads s as the JSON schema type typ ("boolean", "integer", | ||
| 44 | +// "number"), and reports whether it could. | ||
| 45 | +func convertScalar(s string, typ any) (any, bool) { | ||
| 46 | + switch typ { | ||
| 47 | + case "boolean": | ||
| 48 | + switch strings.ToLower(s) { | ||
| 49 | + case "true": | ||
| 50 | + return true, true | ||
| 51 | + case "false": | ||
| 52 | + return false, true | ||
| 53 | + } | ||
| 54 | + case "integer": | ||
| 55 | + if n, err := strconv.ParseInt(s, 10, 64); err == nil { | ||
| 56 | + return n, true | ||
| 57 | + } | ||
| 58 | + case "number": | ||
| 59 | + if f, err := strconv.ParseFloat(s, 64); err == nil { | ||
| 60 | + return f, true | ||
| 61 | + } | ||
| 62 | + } | ||
| 63 | + return nil, false | ||
| 64 | +} | ||
modified
internal/engine/toolschema.go +34 -213 | @@ -6,7 +6,6 @@ import ( | ||
| 6 | 6 | "encoding/json" |
| 7 | 7 | "fmt" |
| 8 | 8 | "sort" |
| 9 | - "strconv" | |
| 10 | 9 | "strings" |
| 11 | 10 | "sync" |
| 12 | 11 | |
| @@ -47,138 +46,6 @@ var ( | ||
| 47 | 46 | newKeys = []string{"new", "new_text", "new_string", "newText", "newString", "replace", "replacement", "updated"} |
| 48 | 47 | ) |
| 49 | 48 | |
| 50 | -// normalizeToolInput repairs the arguments of a write_file or edit_file call | |
| 51 | -// when the repair is unambiguous, and reports whether it changed anything. | |
| 52 | -// Any other tool, or an input it cannot read, is returned as it is: the | |
| 53 | -// schema validation then says what is wrong. | |
| 54 | -// | |
| 55 | -// in := map[string]any{"file_path": "a.go", "edits": []any{map[string]any{"old_text": "x", "new_text": "y"}}} | |
| 56 | -// out, changed := normalizeToolInput("edit_file", in) | |
| 57 | -// // out = {"path": "a.go", "edits": [{"old": "x", "new": "y"}]}, changed = true | |
| 58 | -func normalizeToolInput(tool string, input any) (any, bool) { | |
| 59 | - args, ok := input.(map[string]any) | |
| 60 | - if !ok { | |
| 61 | - return input, false | |
| 62 | - } | |
| 63 | - switch tool { | |
| 64 | - case "write_file": | |
| 65 | - return normalizeWrite(args) | |
| 66 | - case "edit_file": | |
| 67 | - return normalizeEdit(args) | |
| 68 | - } | |
| 69 | - return input, false | |
| 70 | -} | |
| 71 | - | |
| 72 | -func normalizeWrite(args map[string]any) (any, bool) { | |
| 73 | - out := copyMap(args) | |
| 74 | - changed := rename(out, pathKeys) | |
| 75 | - changed = rename(out, contentKeys) || changed | |
| 76 | - return out, changed | |
| 77 | -} | |
| 78 | - | |
| 79 | -func normalizeEdit(args map[string]any) (any, bool) { | |
| 80 | - out := copyMap(args) | |
| 81 | - changed := rename(out, pathKeys) | |
| 82 | - | |
| 83 | - edits := out["edits"] | |
| 84 | - if s, ok := edits.(string); ok { // the list sent as a JSON string | |
| 85 | - var decoded any | |
| 86 | - if json.Unmarshal([]byte(s), &decoded) == nil { | |
| 87 | - edits, changed = decoded, true | |
| 88 | - } | |
| 89 | - } | |
| 90 | - if one, ok := edits.(map[string]any); ok { // one edit without the list | |
| 91 | - edits, changed = []any{one}, true | |
| 92 | - } | |
| 93 | - if edits == nil && firstKey(out, oldKeys) != "" { // edit fields at the top level | |
| 94 | - edit := map[string]any{} | |
| 95 | - for _, k := range append(append([]string{}, oldKeys...), newKeys...) { | |
| 96 | - if v, ok := out[k]; ok { | |
| 97 | - edit[k] = v | |
| 98 | - delete(out, k) | |
| 99 | - } | |
| 100 | - } | |
| 101 | - edits, changed = []any{edit}, true | |
| 102 | - } | |
| 103 | - list, ok := edits.([]any) | |
| 104 | - if !ok { | |
| 105 | - return out, changed | |
| 106 | - } | |
| 107 | - fixed := make([]any, 0, len(list)) | |
| 108 | - for _, item := range list { | |
| 109 | - e, ok := item.(map[string]any) | |
| 110 | - if !ok { | |
| 111 | - fixed = append(fixed, item) | |
| 112 | - continue | |
| 113 | - } | |
| 114 | - e = copyMap(e) | |
| 115 | - if _, hasPath := out["path"]; !hasPath { // `path` inside an edit | |
| 116 | - if k := firstKey(e, pathKeys); k != "" { | |
| 117 | - out["path"] = e[k] | |
| 118 | - changed = true | |
| 119 | - } | |
| 120 | - } | |
| 121 | - changed = rename(e, oldKeys) || changed | |
| 122 | - changed = rename(e, newKeys) || changed | |
| 123 | - if fixed, ok := editLine(e["line"]); ok { // "8" or 8.0 → 8 (ticket 241) | |
| 124 | - e["line"], changed = fixed, true | |
| 125 | - } | |
| 126 | - for k := range e { // the edit schema allows no other key | |
| 127 | - if k != "old" && k != "new" && k != "line" { | |
| 128 | - delete(e, k) | |
| 129 | - changed = true | |
| 130 | - } | |
| 131 | - } | |
| 132 | - fixed = append(fixed, e) | |
| 133 | - } | |
| 134 | - out["edits"] = fixed | |
| 135 | - return out, changed | |
| 136 | -} | |
| 137 | - | |
| 138 | -// editLine turns an edit's `line` sent as a string ("8") into an integer. | |
| 139 | -// ok is false when there is nothing to change. | |
| 140 | -func editLine(v any) (int64, bool) { | |
| 141 | - s, isString := v.(string) | |
| 142 | - if !isString { | |
| 143 | - return 0, false | |
| 144 | - } | |
| 145 | - n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64) | |
| 146 | - return n, err == nil | |
| 147 | -} | |
| 148 | - | |
| 149 | -// rename moves the first alias found to the real key (keys[0]), when the real | |
| 150 | -// key is absent. It reports whether it moved something. | |
| 151 | -func rename(m map[string]any, keys []string) bool { | |
| 152 | - if _, ok := m[keys[0]]; ok { | |
| 153 | - return false | |
| 154 | - } | |
| 155 | - for _, k := range keys[1:] { | |
| 156 | - if v, ok := m[k]; ok { | |
| 157 | - m[keys[0]] = v | |
| 158 | - delete(m, k) | |
| 159 | - return true | |
| 160 | - } | |
| 161 | - } | |
| 162 | - return false | |
| 163 | -} | |
| 164 | - | |
| 165 | -func firstKey(m map[string]any, keys []string) string { | |
| 166 | - for _, k := range keys { | |
| 167 | - if _, ok := m[k]; ok { | |
| 168 | - return k | |
| 169 | - } | |
| 170 | - } | |
| 171 | - return "" | |
| 172 | -} | |
| 173 | - | |
| 174 | -func copyMap(m map[string]any) map[string]any { | |
| 175 | - out := make(map[string]any, len(m)) | |
| 176 | - for k, v := range m { | |
| 177 | - out[k] = v | |
| 178 | - } | |
| 179 | - return out | |
| 180 | -} | |
| 181 | - | |
| 182 | 49 | // schemaFailure recognises Genkit's input-validation error and returns the |
| 183 | 50 | // lines that say what is wrong ("- edits.0: old is required"). ok is false for |
| 184 | 51 | // any other error. |
| @@ -224,19 +91,7 @@ func expectedArgs(tool ai.Tool) string { | ||
| 224 | 91 | if len(props) == 0 { |
| 225 | 92 | return "" |
| 226 | 93 | } |
| 227 | - required := map[string]bool{} | |
| 228 | - if req, ok := schema["required"].([]any); ok { | |
| 229 | - for _, r := range req { | |
| 230 | - if s, ok := r.(string); ok { | |
| 231 | - required[s] = true | |
| 232 | - } | |
| 233 | - } | |
| 234 | - } | |
| 235 | - if req, ok := schema["required"].([]string); ok { | |
| 236 | - for _, s := range req { | |
| 237 | - required[s] = true | |
| 238 | - } | |
| 239 | - } | |
| 94 | + required := requiredArgs(schema) | |
| 240 | 95 | names := make([]string, 0, len(props)) |
| 241 | 96 | for n := range props { |
| 242 | 97 | names = append(names, n) |
| @@ -249,85 +104,51 @@ func expectedArgs(tool ai.Tool) string { | ||
| 249 | 104 | }) |
| 250 | 105 | parts := make([]string, 0, len(names)) |
| 251 | 106 | for _, n := range names { |
| 252 | - typ := "any" | |
| 253 | - if p, ok := props[n].(map[string]any); ok { | |
| 254 | - if t, ok := p["type"].(string); ok { | |
| 255 | - typ = t | |
| 256 | - } | |
| 257 | - } | |
| 258 | - if required[n] { | |
| 259 | - parts = append(parts, fmt.Sprintf("%s (%s, required)", n, typ)) | |
| 260 | - } else { | |
| 261 | - parts = append(parts, fmt.Sprintf("%s (%s)", n, typ)) | |
| 262 | - } | |
| 107 | + parts = append(parts, argLabel(n, props[n], required[n])) | |
| 263 | 108 | } |
| 264 | 109 | return strings.Join(parts, ", ") |
| 265 | 110 | } |
| 266 | 111 | |
| 267 | -// inputSchema is the tool's declared input schema, nil when it has none. | |
| 268 | -func inputSchema(tool ai.Tool) map[string]any { | |
| 269 | - if tool == nil || tool.Definition() == nil { | |
| 270 | - return nil | |
| 112 | +// requiredArgs is a schema's `required` list as a set, whether it was | |
| 113 | +// decoded as []any or written as []string. | |
| 114 | +func requiredArgs(schema map[string]any) map[string]bool { | |
| 115 | + required := map[string]bool{} | |
| 116 | + if req, ok := schema["required"].([]any); ok { | |
| 117 | + for _, r := range req { | |
| 118 | + if s, ok := r.(string); ok { | |
| 119 | + required[s] = true | |
| 120 | + } | |
| 121 | + } | |
| 271 | 122 | } |
| 272 | - return tool.Definition().InputSchema | |
| 123 | + if req, ok := schema["required"].([]string); ok { | |
| 124 | + for _, s := range req { | |
| 125 | + required[s] = true | |
| 126 | + } | |
| 127 | + } | |
| 128 | + return required | |
| 273 | 129 | } |
| 274 | 130 | |
| 275 | -// coerceScalars converts the top-level arguments a model sent as strings when | |
| 276 | -// the schema wants a boolean, an integer or a number, and the string reads | |
| 277 | -// unambiguously as one: "true"/"false" (any case), "8", "0.5". It reports | |
| 278 | -// whether it changed anything. Anything else — "yes", "8a", a string | |
| 279 | -// parameter — is left for the validation to report (ticket 237: Olala-v1.0-mini | |
| 280 | -// sent `"numbered": "true"`, `"start": "1"`, `"end": "8"` to read_file three | |
| 281 | -// times in a row, each refused, and never got the numbered lines it needed). | |
| 282 | -// | |
| 283 | -// coerceScalars(map[string]any{"path": "a.go", "numbered": "true", "start": "1"}, readFileSchema) | |
| 284 | -// // {"path": "a.go", "numbered": true, "start": 1}, true | |
| 285 | -func coerceScalars(input any, schema map[string]any) (any, bool) { | |
| 286 | - args, ok := input.(map[string]any) | |
| 287 | - props, _ := schema["properties"].(map[string]any) | |
| 288 | - if !ok || len(props) == 0 { | |
| 289 | - return input, false | |
| 290 | - } | |
| 291 | - out, changed := args, false | |
| 292 | - for name, value := range args { | |
| 293 | - s, isString := value.(string) | |
| 294 | - prop, _ := props[name].(map[string]any) | |
| 295 | - if !isString || prop == nil { | |
| 296 | - continue | |
| 297 | - } | |
| 298 | - converted, ok := convertScalar(strings.TrimSpace(s), prop["type"]) | |
| 299 | - if !ok { | |
| 300 | - continue | |
| 131 | +// argLabel is "name (type)" or "name (type, required)"; "any" when the | |
| 132 | +// property declares no type. | |
| 133 | +func argLabel(name string, prop any, required bool) string { | |
| 134 | + typ := "any" | |
| 135 | + if p, ok := prop.(map[string]any); ok { | |
| 136 | + if t, ok := p["type"].(string); ok { | |
| 137 | + typ = t | |
| 301 | 138 | } |
| 302 | - if !changed { | |
| 303 | - out, changed = copyMap(args), true | |
| 304 | - } | |
| 305 | - out[name] = converted | |
| 306 | 139 | } |
| 307 | - return out, changed | |
| 140 | + if required { | |
| 141 | + return fmt.Sprintf("%s (%s, required)", name, typ) | |
| 142 | + } | |
| 143 | + return fmt.Sprintf("%s (%s)", name, typ) | |
| 308 | 144 | } |
| 309 | 145 | |
| 310 | -// convertScalar reads s as the JSON schema type typ ("boolean", "integer", | |
| 311 | -// "number"), and reports whether it could. | |
| 312 | -func convertScalar(s string, typ any) (any, bool) { | |
| 313 | - switch typ { | |
| 314 | - case "boolean": | |
| 315 | - switch strings.ToLower(s) { | |
| 316 | - case "true": | |
| 317 | - return true, true | |
| 318 | - case "false": | |
| 319 | - return false, true | |
| 320 | - } | |
| 321 | - case "integer": | |
| 322 | - if n, err := strconv.ParseInt(s, 10, 64); err == nil { | |
| 323 | - return n, true | |
| 324 | - } | |
| 325 | - case "number": | |
| 326 | - if f, err := strconv.ParseFloat(s, 64); err == nil { | |
| 327 | - return f, true | |
| 328 | - } | |
| 146 | +// inputSchema is the tool's declared input schema, nil when it has none. | |
| 147 | +func inputSchema(tool ai.Tool) map[string]any { | |
| 148 | + if tool == nil || tool.Definition() == nil { | |
| 149 | + return nil | |
| 329 | 150 | } |
| 330 | - return nil, false | |
| 151 | + return tool.Definition().InputSchema | |
| 331 | 152 | } |
| 332 | 153 | |
| 333 | 154 | // callKey identifies a call by its tool and its arguments, to count the SAME |
| @@ -6,7 +6,6 @@ import ( | |||
| 6 | "encoding/json" | 6 | "encoding/json" |
| 7 | "fmt" | 7 | "fmt" |
| 8 | "sort" | 8 | "sort" |
| 9 | - "strconv" | ||
| 10 | "strings" | 9 | "strings" |
| 11 | "sync" | 10 | "sync" |
| 12 | 11 | ||
| @@ -47,138 +46,6 @@ var ( | |||
| 47 | newKeys = []string{"new", "new_text", "new_string", "newText", "newString", "replace", "replacement", "updated"} | 46 | newKeys = []string{"new", "new_text", "new_string", "newText", "newString", "replace", "replacement", "updated"} |
| 48 | ) | 47 | ) |
| 49 | 48 | ||
| 50 | -// normalizeToolInput repairs the arguments of a write_file or edit_file call | ||
| 51 | -// when the repair is unambiguous, and reports whether it changed anything. | ||
| 52 | -// Any other tool, or an input it cannot read, is returned as it is: the | ||
| 53 | -// schema validation then says what is wrong. | ||
| 54 | -// | ||
| 55 | -// in := map[string]any{"file_path": "a.go", "edits": []any{map[string]any{"old_text": "x", "new_text": "y"}}} | ||
| 56 | -// out, changed := normalizeToolInput("edit_file", in) | ||
| 57 | -// // out = {"path": "a.go", "edits": [{"old": "x", "new": "y"}]}, changed = true | ||
| 58 | -func normalizeToolInput(tool string, input any) (any, bool) { | ||
| 59 | - args, ok := input.(map[string]any) | ||
| 60 | - if !ok { | ||
| 61 | - return input, false | ||
| 62 | - } | ||
| 63 | - switch tool { | ||
| 64 | - case "write_file": | ||
| 65 | - return normalizeWrite(args) | ||
| 66 | - case "edit_file": | ||
| 67 | - return normalizeEdit(args) | ||
| 68 | - } | ||
| 69 | - return input, false | ||
| 70 | -} | ||
| 71 | - | ||
| 72 | -func normalizeWrite(args map[string]any) (any, bool) { | ||
| 73 | - out := copyMap(args) | ||
| 74 | - changed := rename(out, pathKeys) | ||
| 75 | - changed = rename(out, contentKeys) || changed | ||
| 76 | - return out, changed | ||
| 77 | -} | ||
| 78 | - | ||
| 79 | -func normalizeEdit(args map[string]any) (any, bool) { | ||
| 80 | - out := copyMap(args) | ||
| 81 | - changed := rename(out, pathKeys) | ||
| 82 | - | ||
| 83 | - edits := out["edits"] | ||
| 84 | - if s, ok := edits.(string); ok { // the list sent as a JSON string | ||
| 85 | - var decoded any | ||
| 86 | - if json.Unmarshal([]byte(s), &decoded) == nil { | ||
| 87 | - edits, changed = decoded, true | ||
| 88 | - } | ||
| 89 | - } | ||
| 90 | - if one, ok := edits.(map[string]any); ok { // one edit without the list | ||
| 91 | - edits, changed = []any{one}, true | ||
| 92 | - } | ||
| 93 | - if edits == nil && firstKey(out, oldKeys) != "" { // edit fields at the top level | ||
| 94 | - edit := map[string]any{} | ||
| 95 | - for _, k := range append(append([]string{}, oldKeys...), newKeys...) { | ||
| 96 | - if v, ok := out[k]; ok { | ||
| 97 | - edit[k] = v | ||
| 98 | - delete(out, k) | ||
| 99 | - } | ||
| 100 | - } | ||
| 101 | - edits, changed = []any{edit}, true | ||
| 102 | - } | ||
| 103 | - list, ok := edits.([]any) | ||
| 104 | - if !ok { | ||
| 105 | - return out, changed | ||
| 106 | - } | ||
| 107 | - fixed := make([]any, 0, len(list)) | ||
| 108 | - for _, item := range list { | ||
| 109 | - e, ok := item.(map[string]any) | ||
| 110 | - if !ok { | ||
| 111 | - fixed = append(fixed, item) | ||
| 112 | - continue | ||
| 113 | - } | ||
| 114 | - e = copyMap(e) | ||
| 115 | - if _, hasPath := out["path"]; !hasPath { // `path` inside an edit | ||
| 116 | - if k := firstKey(e, pathKeys); k != "" { | ||
| 117 | - out["path"] = e[k] | ||
| 118 | - changed = true | ||
| 119 | - } | ||
| 120 | - } | ||
| 121 | - changed = rename(e, oldKeys) || changed | ||
| 122 | - changed = rename(e, newKeys) || changed | ||
| 123 | - if fixed, ok := editLine(e["line"]); ok { // "8" or 8.0 → 8 (ticket 241) | ||
| 124 | - e["line"], changed = fixed, true | ||
| 125 | - } | ||
| 126 | - for k := range e { // the edit schema allows no other key | ||
| 127 | - if k != "old" && k != "new" && k != "line" { | ||
| 128 | - delete(e, k) | ||
| 129 | - changed = true | ||
| 130 | - } | ||
| 131 | - } | ||
| 132 | - fixed = append(fixed, e) | ||
| 133 | - } | ||
| 134 | - out["edits"] = fixed | ||
| 135 | - return out, changed | ||
| 136 | -} | ||
| 137 | - | ||
| 138 | -// editLine turns an edit's `line` sent as a string ("8") into an integer. | ||
| 139 | -// ok is false when there is nothing to change. | ||
| 140 | -func editLine(v any) (int64, bool) { | ||
| 141 | - s, isString := v.(string) | ||
| 142 | - if !isString { | ||
| 143 | - return 0, false | ||
| 144 | - } | ||
| 145 | - n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64) | ||
| 146 | - return n, err == nil | ||
| 147 | -} | ||
| 148 | - | ||
| 149 | -// rename moves the first alias found to the real key (keys[0]), when the real | ||
| 150 | -// key is absent. It reports whether it moved something. | ||
| 151 | -func rename(m map[string]any, keys []string) bool { | ||
| 152 | - if _, ok := m[keys[0]]; ok { | ||
| 153 | - return false | ||
| 154 | - } | ||
| 155 | - for _, k := range keys[1:] { | ||
| 156 | - if v, ok := m[k]; ok { | ||
| 157 | - m[keys[0]] = v | ||
| 158 | - delete(m, k) | ||
| 159 | - return true | ||
| 160 | - } | ||
| 161 | - } | ||
| 162 | - return false | ||
| 163 | -} | ||
| 164 | - | ||
| 165 | -func firstKey(m map[string]any, keys []string) string { | ||
| 166 | - for _, k := range keys { | ||
| 167 | - if _, ok := m[k]; ok { | ||
| 168 | - return k | ||
| 169 | - } | ||
| 170 | - } | ||
| 171 | - return "" | ||
| 172 | -} | ||
| 173 | - | ||
| 174 | -func copyMap(m map[string]any) map[string]any { | ||
| 175 | - out := make(map[string]any, len(m)) | ||
| 176 | - for k, v := range m { | ||
| 177 | - out[k] = v | ||
| 178 | - } | ||
| 179 | - return out | ||
| 180 | -} | ||
| 181 | - | ||
| 182 | // schemaFailure recognises Genkit's input-validation error and returns the | 49 | // schemaFailure recognises Genkit's input-validation error and returns the |
| 183 | // lines that say what is wrong ("- edits.0: old is required"). ok is false for | 50 | // lines that say what is wrong ("- edits.0: old is required"). ok is false for |
| 184 | // any other error. | 51 | // any other error. |
| @@ -224,19 +91,7 @@ func expectedArgs(tool ai.Tool) string { | |||
| 224 | if len(props) == 0 { | 91 | if len(props) == 0 { |
| 225 | return "" | 92 | return "" |
| 226 | } | 93 | } |
| 227 | - required := map[string]bool{} | 94 | + required := requiredArgs(schema) |
| 228 | - if req, ok := schema["required"].([]any); ok { | ||
| 229 | - for _, r := range req { | ||
| 230 | - if s, ok := r.(string); ok { | ||
| 231 | - required[s] = true | ||
| 232 | - } | ||
| 233 | - } | ||
| 234 | - } | ||
| 235 | - if req, ok := schema["required"].([]string); ok { | ||
| 236 | - for _, s := range req { | ||
| 237 | - required[s] = true | ||
| 238 | - } | ||
| 239 | - } | ||
| 240 | names := make([]string, 0, len(props)) | 95 | names := make([]string, 0, len(props)) |
| 241 | for n := range props { | 96 | for n := range props { |
| 242 | names = append(names, n) | 97 | names = append(names, n) |
| @@ -249,85 +104,51 @@ func expectedArgs(tool ai.Tool) string { | |||
| 249 | }) | 104 | }) |
| 250 | parts := make([]string, 0, len(names)) | 105 | parts := make([]string, 0, len(names)) |
| 251 | for _, n := range names { | 106 | for _, n := range names { |
| 252 | - typ := "any" | 107 | + parts = append(parts, argLabel(n, props[n], required[n])) |
| 253 | - if p, ok := props[n].(map[string]any); ok { | ||
| 254 | - if t, ok := p["type"].(string); ok { | ||
| 255 | - typ = t | ||
| 256 | - } | ||
| 257 | - } | ||
| 258 | - if required[n] { | ||
| 259 | - parts = append(parts, fmt.Sprintf("%s (%s, required)", n, typ)) | ||
| 260 | - } else { | ||
| 261 | - parts = append(parts, fmt.Sprintf("%s (%s)", n, typ)) | ||
| 262 | - } | ||
| 263 | } | 108 | } |
| 264 | return strings.Join(parts, ", ") | 109 | return strings.Join(parts, ", ") |
| 265 | } | 110 | } |
| 266 | 111 | ||
| 267 | -// inputSchema is the tool's declared input schema, nil when it has none. | 112 | +// requiredArgs is a schema's `required` list as a set, whether it was |
| 268 | -func inputSchema(tool ai.Tool) map[string]any { | 113 | +// decoded as []any or written as []string. |
| 269 | - if tool == nil || tool.Definition() == nil { | 114 | +func requiredArgs(schema map[string]any) map[string]bool { |
| 270 | - return nil | 115 | + required := map[string]bool{} |
| 116 | + if req, ok := schema["required"].([]any); ok { | ||
| 117 | + for _, r := range req { | ||
| 118 | + if s, ok := r.(string); ok { | ||
| 119 | + required[s] = true | ||
| 120 | + } | ||
| 121 | + } | ||
| 271 | } | 122 | } |
| 272 | - return tool.Definition().InputSchema | 123 | + if req, ok := schema["required"].([]string); ok { |
| 124 | + for _, s := range req { | ||
| 125 | + required[s] = true | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + return required | ||
| 273 | } | 129 | } |
| 274 | 130 | ||
| 275 | -// coerceScalars converts the top-level arguments a model sent as strings when | 131 | +// argLabel is "name (type)" or "name (type, required)"; "any" when the |
| 276 | -// the schema wants a boolean, an integer or a number, and the string reads | 132 | +// property declares no type. |
| 277 | -// unambiguously as one: "true"/"false" (any case), "8", "0.5". It reports | 133 | +func argLabel(name string, prop any, required bool) string { |
| 278 | -// whether it changed anything. Anything else — "yes", "8a", a string | 134 | + typ := "any" |
| 279 | -// parameter — is left for the validation to report (ticket 237: Olala-v1.0-mini | 135 | + if p, ok := prop.(map[string]any); ok { |
| 280 | -// sent `"numbered": "true"`, `"start": "1"`, `"end": "8"` to read_file three | 136 | + if t, ok := p["type"].(string); ok { |
| 281 | -// times in a row, each refused, and never got the numbered lines it needed). | 137 | + typ = t |
| 282 | -// | ||
| 283 | -// coerceScalars(map[string]any{"path": "a.go", "numbered": "true", "start": "1"}, readFileSchema) | ||
| 284 | -// // {"path": "a.go", "numbered": true, "start": 1}, true | ||
| 285 | -func coerceScalars(input any, schema map[string]any) (any, bool) { | ||
| 286 | - args, ok := input.(map[string]any) | ||
| 287 | - props, _ := schema["properties"].(map[string]any) | ||
| 288 | - if !ok || len(props) == 0 { | ||
| 289 | - return input, false | ||
| 290 | - } | ||
| 291 | - out, changed := args, false | ||
| 292 | - for name, value := range args { | ||
| 293 | - s, isString := value.(string) | ||
| 294 | - prop, _ := props[name].(map[string]any) | ||
| 295 | - if !isString || prop == nil { | ||
| 296 | - continue | ||
| 297 | - } | ||
| 298 | - converted, ok := convertScalar(strings.TrimSpace(s), prop["type"]) | ||
| 299 | - if !ok { | ||
| 300 | - continue | ||
| 301 | } | 138 | } |
| 302 | - if !changed { | ||
| 303 | - out, changed = copyMap(args), true | ||
| 304 | - } | ||
| 305 | - out[name] = converted | ||
| 306 | } | 139 | } |
| 307 | - return out, changed | 140 | + if required { |
| 141 | + return fmt.Sprintf("%s (%s, required)", name, typ) | ||
| 142 | + } | ||
| 143 | + return fmt.Sprintf("%s (%s)", name, typ) | ||
| 308 | } | 144 | } |
| 309 | 145 | ||
| 310 | -// convertScalar reads s as the JSON schema type typ ("boolean", "integer", | 146 | +// inputSchema is the tool's declared input schema, nil when it has none. |
| 311 | -// "number"), and reports whether it could. | 147 | +func inputSchema(tool ai.Tool) map[string]any { |
| 312 | -func convertScalar(s string, typ any) (any, bool) { | 148 | + if tool == nil || tool.Definition() == nil { |
| 313 | - switch typ { | 149 | + return nil |
| 314 | - case "boolean": | ||
| 315 | - switch strings.ToLower(s) { | ||
| 316 | - case "true": | ||
| 317 | - return true, true | ||
| 318 | - case "false": | ||
| 319 | - return false, true | ||
| 320 | - } | ||
| 321 | - case "integer": | ||
| 322 | - if n, err := strconv.ParseInt(s, 10, 64); err == nil { | ||
| 323 | - return n, true | ||
| 324 | - } | ||
| 325 | - case "number": | ||
| 326 | - if f, err := strconv.ParseFloat(s, 64); err == nil { | ||
| 327 | - return f, true | ||
| 328 | - } | ||
| 329 | } | 150 | } |
| 330 | - return nil, false | 151 | + return tool.Definition().InputSchema |
| 331 | } | 152 | } |
| 332 | 153 | ||
| 333 | // callKey identifies a call by its tool and its arguments, to count the SAME | 154 | // callKey identifies a call by its tool and its arguments, to count the SAME |
added
internal/engine/turn.go +413 -0 | new file mode 100644 | ||
| @@ -0,0 +1,413 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "fmt" | |
| 6 | + "slices" | |
| 7 | + | |
| 8 | + "mm/internal/config" | |
| 9 | + "mm/internal/spinner" | |
| 10 | + "mm/internal/ui" | |
| 11 | + | |
| 12 | + "github.com/firebase/genkit/go/ai" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// One turn of generate (engine.go): its state, and the steps Genkit calls | |
| 16 | +// back into — every model call (wrapModel, with the hand-backs: a looping | |
| 17 | +// stream, a broken stream, broken tool-call arguments, a reply cut while | |
| 18 | +// reasoning, an answer after a failed file change), every tool call | |
| 19 | +// (wrapTool), every streamed chunk (onChunk, emit). | |
| 20 | + | |
| 21 | +// turn is the state of one generation. | |
| 22 | +type turn struct { | |
| 23 | + e *Engine | |
| 24 | + // messages is the history the turn started from. | |
| 25 | + messages []*ai.Message | |
| 26 | + // full is the last request Genkit sent: Genkit only hands back the LAST | |
| 27 | + // message, the intermediate ones ("I am calling bash", "here is the | |
| 28 | + // output") exist only in the request it builds for the next call — so | |
| 29 | + // the last request seen holds the whole conversation. | |
| 30 | + full []*ai.Message | |
| 31 | + // reply is the model's latest message — for a tool, the one that called | |
| 32 | + // it (reply.go). | |
| 33 | + reply *ai.Message | |
| 34 | + // pl is the watchdog's pulse, set by watch; every model call restarts | |
| 35 | + // the wait for a first token (progress.go). | |
| 36 | + pl *pulse | |
| 37 | + // speed measures each call and the turn (speed.go, ticket 254); nil | |
| 38 | + // with showSpeed off. | |
| 39 | + speed *speedMeter | |
| 40 | + // think is the turn's thought block (reasoning.go, thoughts.go). | |
| 41 | + think *thoughts | |
| 42 | + // loops watches each call's stream for a sentence repeated over and over | |
| 43 | + // (textloop.go, ticket 235). | |
| 44 | + loops loopWatch | |
| 45 | + // gaps holds trailing whitespace back on a terminal (the gap type). | |
| 46 | + gaps gap | |
| 47 | + // invalid counts the tool calls that failed the schema (toolschema.go): | |
| 48 | + // the same invalid call repeated ends the turn. | |
| 49 | + invalid invalidCalls | |
| 50 | + // The hand-backs of this generation, each bounded by its max*Retries. | |
| 51 | + argRetries, cutRetries, loopRetries, editRetries int | |
| 52 | + // printed: some answer text reached the screen or the client. | |
| 53 | + printed bool | |
| 54 | +} | |
| 55 | + | |
| 56 | +func newTurn(e *Engine, messages []*ai.Message) *turn { | |
| 57 | + return &turn{e: e, messages: messages, speed: turnSpeedMeter(), think: &thoughts{}} | |
| 58 | +} | |
| 59 | + | |
| 60 | +// finishSpeed closes the turn's speed measure (deferred by generate). | |
| 61 | +func (t *turn) finishSpeed() { | |
| 62 | + if t.speed != nil { | |
| 63 | + t.speed.finish() | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +// options are the Genkit options of the turn, the middleware included. | |
| 68 | +func (t *turn) options(tools []ai.ToolRef) []ai.GenerateOption { | |
| 69 | + capture := ai.MiddlewareFunc(func(context.Context) (*ai.Hooks, error) { | |
| 70 | + return &ai.Hooks{WrapModel: t.wrapModel, WrapTool: t.wrapTool}, nil | |
| 71 | + }) | |
| 72 | + opts := []ai.GenerateOption{ | |
| 73 | + ai.WithModelName(t.e.Model), | |
| 74 | + ai.WithMessages(t.messages...), | |
| 75 | + ai.WithTools(tools...), | |
| 76 | + ai.WithMaxTurns(config.Cfg.MaxTurns), // max model ↔ tools round trips | |
| 77 | + ai.WithConfig(config.Cfg.Sampling), | |
| 78 | + ai.WithUse(capture), | |
| 79 | + } | |
| 80 | + // structuredOutput (ticket 80): the server constrains the answer to the | |
| 81 | + // schema, and Genkit checks it against the schema before handing it back. | |
| 82 | + if config.Cfg.OutputSchema != nil { | |
| 83 | + opts = append(opts, ai.WithOutputSchema(config.Cfg.OutputSchema)) | |
| 84 | + } | |
| 85 | + return opts | |
| 86 | +} | |
| 87 | + | |
| 88 | +// watch is the turn's context: a watchdog that cancels it when the server is | |
| 89 | +// silent too long — firstTokenTimeout while a model call reads its prompt, | |
| 90 | +// WatchdogTimeout between tokens (progress.go) — with the taps that beat it. | |
| 91 | +func (t *turn) watch(ctx context.Context) (context.Context, context.CancelFunc) { | |
| 92 | + genCtx, p, cancel := watchdog(ctx, config.Cfg.WatchdogTimeout, | |
| 93 | + firstTokenTimeout(config.Cfg.WatchdogTimeout, config.Cfg.FirstTokenTimeout)) | |
| 94 | + t.pl = p | |
| 95 | + genCtx = withHeartbeat(genCtx, p.beat) | |
| 96 | + // A thinking model streams its reasoning in a field Genkit drops, so the | |
| 97 | + // streaming callback never runs while it thinks (reasoning.go). The beat | |
| 98 | + // matters more than the display here: without it the watchdog kills a turn | |
| 99 | + // that is going perfectly well, and a model can reason for a long time | |
| 100 | + // before its first word — 38s measured. The display is a setting; the | |
| 101 | + // heartbeat never is. | |
| 102 | + genCtx = WithReasoning(genCtx, func(text string) { | |
| 103 | + p.beat() | |
| 104 | + t.loops.feed(text) | |
| 105 | + if config.Cfg.ShowThinking { | |
| 106 | + t.think.emit(text) | |
| 107 | + } | |
| 108 | + }) | |
| 109 | + // The error events a server streams, for the model calls to report | |
| 110 | + // (servererr.go; read back in wrapModel through the context). | |
| 111 | + genCtx, _ = withServerErrors(genCtx) | |
| 112 | + // While the server reads the prompt it says how far it got: proof of life | |
| 113 | + // for the watchdog, and something to show instead of "Thinking". | |
| 114 | + genCtx = withSpeed(genCtx, t.speed) | |
| 115 | + genCtx = withPromptProgress(genCtx, func(pp promptProgress) { | |
| 116 | + p.alive() | |
| 117 | + if p.waiting.Load() { | |
| 118 | + spinner.Start(progressLabel(pp)) | |
| 119 | + } | |
| 120 | + }) | |
| 121 | + return genCtx, cancel | |
| 122 | +} | |
| 123 | + | |
| 124 | +// onChunk is the streaming callback: it beats the watchdog, lets the guard | |
| 125 | +// watch tool-call arguments, and shows the text. | |
| 126 | +func (t *turn) onChunk(guard *toolCallGuard) ai.ModelStreamCallback { | |
| 127 | + return func(_ context.Context, chunk *ai.ModelResponseChunk) error { | |
| 128 | + t.pl.beat() | |
| 129 | + wasComposing := guard.composing | |
| 130 | + if err := guard.observe(chunk); err != nil { | |
| 131 | + return err | |
| 132 | + } | |
| 133 | + if guard.composing && !wasComposing { | |
| 134 | + spinner.Start("Composing a tool call") | |
| 135 | + } | |
| 136 | + // Since Genkit 1.13 a chunk may carry nothing but reasoning. The tap | |
| 137 | + // has already shown it (reasoning.go); handed to emit, its empty text | |
| 138 | + // would close the thought block after every token. | |
| 139 | + if onlyReasoning(chunk) { | |
| 140 | + return nil | |
| 141 | + } | |
| 142 | + t.loops.feed(chunk.Text()) | |
| 143 | + t.emit(chunk.Text()) | |
| 144 | + return nil | |
| 145 | + } | |
| 146 | +} | |
| 147 | + | |
| 148 | +// emit shows answer text. The prefix is printed by the first token rather | |
| 149 | +// than up front, so the spinner has a line to itself and vanishes without | |
| 150 | +// taking anything with it. | |
| 151 | +func (t *turn) emit(text string) { | |
| 152 | + // An event-consuming front end (ACP) takes the chunk raw: the editor | |
| 153 | + // renders Markdown and owns the layout, so the gap/squeeze machinery — | |
| 154 | + // which fights the terminal screen, not the text — stays out of the way. | |
| 155 | + // `printed` is still maintained: the no-streaming retry must know whether | |
| 156 | + // the client already saw part of an answer. | |
| 157 | + if s := ui.ActiveSink(); s != nil { | |
| 158 | + if text == "" { | |
| 159 | + return | |
| 160 | + } | |
| 161 | + t.think.done() | |
| 162 | + t.printed = true | |
| 163 | + s.Text(text) | |
| 164 | + return | |
| 165 | + } | |
| 166 | + // The answer has started: the thinking that led to it is over. | |
| 167 | + t.think.done() | |
| 168 | + // Trailing whitespace is held back, not printed: see the gap type. | |
| 169 | + out := t.gaps.next(text) | |
| 170 | + if out == "" { | |
| 171 | + return | |
| 172 | + } | |
| 173 | + // Stop BEFORE every print, not only the first one: a question can take | |
| 174 | + // several turns, and the tool restarts the spinner on its way back to the | |
| 175 | + // model; the text of the next turn then landed on the spinner's line, | |
| 176 | + // which erased it on the following frame (`\r\033[2K`). Stop() is | |
| 177 | + // idempotent and returns at once when nothing runs. | |
| 178 | + spinner.Stop() | |
| 179 | + if !t.printed { | |
| 180 | + fmt.Print("🤖 ") | |
| 181 | + t.printed = true | |
| 182 | + } | |
| 183 | + fmt.Print(out) | |
| 184 | +} | |
| 185 | + | |
| 186 | +// retryableWithoutStreaming tells whether a failed turn may be replayed | |
| 187 | +// without streaming. The retry is only worth it for an SSE stream cut before | |
| 188 | +// the first byte. Any other error (maxTurns exceeded, a failing tool, | |
| 189 | +// invalid arguments) happens AFTER commands have run, and replaying the turn | |
| 190 | +// would replay them: measured, an `echo >>` wrote itself twice. `full` grows | |
| 191 | +// as soon as a tool turn has happened, which tells the two apart. Never | |
| 192 | +// retried either: the loop detector's stop (the repeated tool would run once | |
| 193 | +// more), a tool call whose arguments did not parse (already handed back), a | |
| 194 | +// request larger than the server's window (ticket 233), a looping model | |
| 195 | +// (ticket 235). | |
| 196 | +func (t *turn) retryableWithoutStreaming(err error) bool { | |
| 197 | + if err == nil || t.printed || len(t.full) > len(t.messages) || contextOverflow(err) { | |
| 198 | + return false | |
| 199 | + } | |
| 200 | + _, stuck := stuckTurn(err) | |
| 201 | + truncated, malformed := argsError(err) | |
| 202 | + _, isLoop := looped(err) | |
| 203 | + return !stuck && !truncated && !malformed && !isLoop | |
| 204 | +} | |
| 205 | + | |
| 206 | +// wrapTool runs one tool call: the whitespace the previous text left | |
| 207 | +// pending is forgotten (the tool is about to print its 🛠️ line), the reply | |
| 208 | +// that called it is passed on, and schemaGuard (toolschema.go, ticket 225) | |
| 209 | +// wraps the hooks and the decision blocks: it repairs the file tools' | |
| 210 | +// arguments before the hooks see them, and turns a schema error left after | |
| 211 | +// them into a result the model reads. | |
| 212 | +func (t *turn) wrapTool(ctx context.Context, params *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error) { | |
| 213 | + t.gaps.drop() | |
| 214 | + ctx = withReply(ctx, t.reply) | |
| 215 | + return schemaGuard(ctx, params, &t.invalid, func(ctx context.Context, params *ai.ToolParams) (*ai.MultipartToolResponse, error) { | |
| 216 | + if !t.e.hooks.Enabled() && toolJudge == nil && resultJudge == nil { | |
| 217 | + return next(ctx, params) | |
| 218 | + } | |
| 219 | + return t.e.runToolHooks(ctx, params, next) | |
| 220 | + }) | |
| 221 | +} | |
| 222 | + | |
| 223 | +// modelCall runs ONE model call under its own context, which the loop watch | |
| 224 | +// cancels when the stream repeats itself — the call, not the generation. | |
| 225 | +type modelCall func(ctx context.Context) (*ai.ModelResponse, error) | |
| 226 | + | |
| 227 | +// wrapModel runs one model call of the turn, with its hand-backs. | |
| 228 | +func (t *turn) wrapModel(ctx context.Context, params *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) { | |
| 229 | + // Same tools, same order, on every call: the server's prompt cache | |
| 230 | + // depends on it (tooldefs.go, ticket 53). | |
| 231 | + params.Request.Tools = stableTools(params.Request.Tools) | |
| 232 | + // From the turn's second call on — tools have run — a history past the | |
| 233 | + // threshold is made smaller first (inturn.go, ticket 251). The wait | |
| 234 | + // counts as the call's: the summary is no beat. | |
| 235 | + if config.Cfg.Context.CompressInTurn && len(params.Request.Messages) > len(t.messages) { | |
| 236 | + t.pl.expect() | |
| 237 | + t.e.compactInTurn(ctx, params) | |
| 238 | + } | |
| 239 | + // Messages the user sent during the turn (ticket 265, steer.go) join the | |
| 240 | + // history after the tool results. | |
| 241 | + params.Request.Messages = takeSteer(ctx, params.Request.Messages) | |
| 242 | + t.full = slices.Clone(params.Request.Messages) | |
| 243 | + call := func(ctx context.Context) (*ai.ModelResponse, error) { | |
| 244 | + callCtx, cancel := context.WithCancel(ctx) | |
| 245 | + defer cancel() | |
| 246 | + t.loops.arm(cancel) | |
| 247 | + defer t.loops.disarm() | |
| 248 | + return next(callCtx, params) | |
| 249 | + } | |
| 250 | + t.pl.expect() | |
| 251 | + resp, err := call(ctx) | |
| 252 | + err = withServerMessage(ctx, err) | |
| 253 | + resp, err, stop := t.retryLoops(ctx, params, call, resp, err) | |
| 254 | + if stop { | |
| 255 | + return resp, err | |
| 256 | + } | |
| 257 | + resp, err = t.retryBrokenStream(ctx, call, resp, err) | |
| 258 | + resp, err = t.retryBrokenArgs(ctx, params, call, resp, err) | |
| 259 | + resp, err = t.retryCutReasoning(ctx, params, call, resp, err) | |
| 260 | + resp, err = t.retryFailedEdit(ctx, params, call, resp, err) | |
| 261 | + t.recordUsage(resp) | |
| 262 | + dropReasoning(resp) | |
| 263 | + if resp != nil { | |
| 264 | + t.reply = resp.Message | |
| 265 | + } | |
| 266 | + return resp, err | |
| 267 | +} | |
| 268 | + | |
| 269 | +// handBack runs the call again with notes appended to the request. The | |
| 270 | +// notes go into params.Request itself: Genkit builds the next call's | |
| 271 | +// request from that same value, so they stay in the conversation, and | |
| 272 | +// `full` carries them into the history. | |
| 273 | +func (t *turn) handBack(ctx context.Context, params *ai.ModelParams, call modelCall, notes ...*ai.Message) (*ai.ModelResponse, error) { | |
| 274 | + params.Request.Messages = append(slices.Clone(params.Request.Messages), notes...) | |
| 275 | + t.full = slices.Clone(params.Request.Messages) | |
| 276 | + t.pl.expect() | |
| 277 | + resp, err := call(ctx) | |
| 278 | + return resp, withServerMessage(ctx, err) | |
| 279 | +} | |
| 280 | + | |
| 281 | +// struggle stops the spinner, prints line on ui.Out (stderr in ACP mode, | |
| 282 | +// never the JSON-RPC stream) and reports the struggle. | |
| 283 | +func struggle(line, label string) { | |
| 284 | + spinner.Stop() | |
| 285 | + _, _ = fmt.Fprintf(ui.Out, "\n[%s]\n", line) | |
| 286 | + ui.ReportStruggle(ui.Struggle{Label: label}) | |
| 287 | +} | |
| 288 | + | |
| 289 | +// retryLoops hands back a call cut because the model was repeating itself, | |
| 290 | +// once with a note; looping again ends the turn (textloop.go, ticket 235): | |
| 291 | +// stop is then true and err a loopError. | |
| 292 | +func (t *turn) retryLoops(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error, bool) { | |
| 293 | + for ctx.Err() == nil { | |
| 294 | + sample, times, cut := t.loops.take() | |
| 295 | + if !cut { | |
| 296 | + break | |
| 297 | + } | |
| 298 | + t.think.done() | |
| 299 | + if t.loopRetries >= maxLoopRetries { | |
| 300 | + spinner.Stop() | |
| 301 | + return nil, loopError{sample: sample, times: times}, true | |
| 302 | + } | |
| 303 | + t.loopRetries++ | |
| 304 | + struggle(fmt.Sprintf("the model repeated %q %d times in a row — stopped it and asked for the answer, %d/%d", shorten(sample, 60), times, t.loopRetries, maxLoopRetries), | |
| 305 | + fmt.Sprintf("looped — handed back %d/%d", t.loopRetries, maxLoopRetries)) | |
| 306 | + resp, err = t.handBack(ctx, params, call, loopRetryNote(sample, times)) | |
| 307 | + } | |
| 308 | + return resp, err, false | |
| 309 | +} | |
| 310 | + | |
| 311 | +// retryBrokenStream retries ONCE a stream the server broke — an error event, | |
| 312 | +// a cut connection (servererr.go) — this model call only. The turn-level | |
| 313 | +// retry cannot help once a tool has run (it would replay the tools); this | |
| 314 | +// one replays nothing but the call that failed. Seen: a turn ended on | |
| 315 | +// "unexpected end of JSON input" after twenty tool calls and a written file. | |
| 316 | +// Text the broken attempt already streamed is not taken back. | |
| 317 | +func (t *turn) retryBrokenStream(ctx context.Context, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) { | |
| 318 | + if !streamBroken(err) || contextOverflow(err) || ctx.Err() != nil { | |
| 319 | + return resp, err | |
| 320 | + } | |
| 321 | + struggle(streamNotice(err)+" — retrying this model call once", "stream cut — retried") | |
| 322 | + t.pl.expect() | |
| 323 | + resp, err = call(ctx) | |
| 324 | + return resp, withServerMessage(ctx, err) | |
| 325 | +} | |
| 326 | + | |
| 327 | +// retryBrokenArgs hands back a tool call whose arguments did not parse — | |
| 328 | +// cut off by max_tokens, most of the time — with a note instead of ending | |
| 329 | +// the turn: the model needs the note again when it writes the second piece. | |
| 330 | +func (t *turn) retryBrokenArgs(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) { | |
| 331 | + for t.argRetries < maxArgRetries && ctx.Err() == nil { | |
| 332 | + truncated, malformed := argsError(err) | |
| 333 | + if !truncated && !malformed { | |
| 334 | + break | |
| 335 | + } | |
| 336 | + t.argRetries++ | |
| 337 | + what := "invalid JSON" | |
| 338 | + if truncated { | |
| 339 | + what = "cut off" | |
| 340 | + } | |
| 341 | + struggle(fmt.Sprintf("tool call arguments did not parse (%s: …%s) — handing it back to the model, %d/%d", what, lastRunes(err.Error(), 60), t.argRetries, maxArgRetries), | |
| 342 | + fmt.Sprintf("broken tool call (%s) %d/%d", what, t.argRetries, maxArgRetries)) | |
| 343 | + resp, err = t.handBack(ctx, params, call, argsRetryNote(truncated)) | |
| 344 | + } | |
| 345 | + return resp, err | |
| 346 | +} | |
| 347 | + | |
| 348 | +// retryCutReasoning hands back, once, a reply cut by the answer limit while | |
| 349 | +// the model was still reasoning — no text, no tool call (toolargs.go, | |
| 350 | +// ticket 232). | |
| 351 | +func (t *turn) retryCutReasoning(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) { | |
| 352 | + for t.cutRetries < maxCutRetries && ctx.Err() == nil && reasoningCut(resp, err) { | |
| 353 | + t.cutRetries++ | |
| 354 | + struggle(fmt.Sprintf("the model reasoned until the answer limit without answering — asking it to act now, %d/%d", t.cutRetries, maxCutRetries), | |
| 355 | + fmt.Sprintf("reasoning cut at the limit %d/%d", t.cutRetries, maxCutRetries)) | |
| 356 | + resp, err = t.handBack(ctx, params, call, cutRetryNote()) | |
| 357 | + } | |
| 358 | + return resp, err | |
| 359 | +} | |
| 360 | + | |
| 361 | +// retryFailedEdit hands back, once, an ANSWER given while the turn's last | |
| 362 | +// file change failed (toolargs.go, ticket 242): the model can still fix its | |
| 363 | +// call, or say it failed. The answer stays in the conversation, so the note | |
| 364 | +// can refer to it. | |
| 365 | +func (t *turn) retryFailedEdit(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) { | |
| 366 | + for t.editRetries < maxEditRetries && ctx.Err() == nil && isAnswer(resp, err) { | |
| 367 | + turn := params.Request.Messages[min(len(t.messages), len(params.Request.Messages)):] | |
| 368 | + tool, failure, failed := lastFailedFileChange(turn) | |
| 369 | + if !failed { | |
| 370 | + break | |
| 371 | + } | |
| 372 | + t.editRetries++ | |
| 373 | + t.think.done() | |
| 374 | + struggle(fmt.Sprintf("the last %s failed — the file was not changed; asking the model to fix the call or say so, %d/%d", tool, t.editRetries, maxEditRetries), | |
| 375 | + fmt.Sprintf("answer after a failed %s — handed back %d/%d", tool, t.editRetries, maxEditRetries)) | |
| 376 | + resp, err = t.handBack(ctx, params, call, ai.NewModelTextMessage(resp.Text()), failedEditNote(tool, failure)) | |
| 377 | + } | |
| 378 | + return resp, err | |
| 379 | +} | |
| 380 | + | |
| 381 | +// isAnswer tells whether a call ended with an answer: a message and no tool | |
| 382 | +// call. | |
| 383 | +func isAnswer(resp *ai.ModelResponse, err error) bool { | |
| 384 | + return err == nil && resp != nil && resp.Message != nil && len(resp.ToolRequests()) == 0 | |
| 385 | +} | |
| 386 | + | |
| 387 | +// recordUsage keeps the server's own count of what it just read — the one | |
| 388 | +// exact measure of the context size, for the compression trigger — settles | |
| 389 | +// the call's speed, and hands every call's counts to a front end that wants | |
| 390 | +// them (ACP: the context meter, the tokens a turn cost). | |
| 391 | +func (t *turn) recordUsage(resp *ai.ModelResponse) { | |
| 392 | + if resp == nil { | |
| 393 | + return | |
| 394 | + } | |
| 395 | + if resp.Usage != nil && resp.Usage.InputTokens > 0 { | |
| 396 | + t.e.lastInput.Store(int64(resp.Usage.InputTokens)) | |
| 397 | + } | |
| 398 | + if t.speed != nil { | |
| 399 | + out := 0 | |
| 400 | + if resp.Usage != nil { | |
| 401 | + out = resp.Usage.OutputTokens | |
| 402 | + } | |
| 403 | + t.speed.settle(out) | |
| 404 | + } | |
| 405 | + if s, ok := ui.ActiveSink().(ui.UsageSink); ok && resp.Usage != nil { | |
| 406 | + s.Usage(ui.Usage{ | |
| 407 | + InputTokens: resp.Usage.InputTokens, | |
| 408 | + OutputTokens: resp.Usage.OutputTokens, | |
| 409 | + ThoughtTokens: resp.Usage.ThoughtsTokens, | |
| 410 | + CachedReadTokens: resp.Usage.CachedContentTokens, | |
| 411 | + }) | |
| 412 | + } | |
| 413 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,413 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "fmt" | ||
| 6 | + "slices" | ||
| 7 | + | ||
| 8 | + "mm/internal/config" | ||
| 9 | + "mm/internal/spinner" | ||
| 10 | + "mm/internal/ui" | ||
| 11 | + | ||
| 12 | + "github.com/firebase/genkit/go/ai" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// One turn of generate (engine.go): its state, and the steps Genkit calls | ||
| 16 | +// back into — every model call (wrapModel, with the hand-backs: a looping | ||
| 17 | +// stream, a broken stream, broken tool-call arguments, a reply cut while | ||
| 18 | +// reasoning, an answer after a failed file change), every tool call | ||
| 19 | +// (wrapTool), every streamed chunk (onChunk, emit). | ||
| 20 | + | ||
| 21 | +// turn is the state of one generation. | ||
| 22 | +type turn struct { | ||
| 23 | + e *Engine | ||
| 24 | + // messages is the history the turn started from. | ||
| 25 | + messages []*ai.Message | ||
| 26 | + // full is the last request Genkit sent: Genkit only hands back the LAST | ||
| 27 | + // message, the intermediate ones ("I am calling bash", "here is the | ||
| 28 | + // output") exist only in the request it builds for the next call — so | ||
| 29 | + // the last request seen holds the whole conversation. | ||
| 30 | + full []*ai.Message | ||
| 31 | + // reply is the model's latest message — for a tool, the one that called | ||
| 32 | + // it (reply.go). | ||
| 33 | + reply *ai.Message | ||
| 34 | + // pl is the watchdog's pulse, set by watch; every model call restarts | ||
| 35 | + // the wait for a first token (progress.go). | ||
| 36 | + pl *pulse | ||
| 37 | + // speed measures each call and the turn (speed.go, ticket 254); nil | ||
| 38 | + // with showSpeed off. | ||
| 39 | + speed *speedMeter | ||
| 40 | + // think is the turn's thought block (reasoning.go, thoughts.go). | ||
| 41 | + think *thoughts | ||
| 42 | + // loops watches each call's stream for a sentence repeated over and over | ||
| 43 | + // (textloop.go, ticket 235). | ||
| 44 | + loops loopWatch | ||
| 45 | + // gaps holds trailing whitespace back on a terminal (the gap type). | ||
| 46 | + gaps gap | ||
| 47 | + // invalid counts the tool calls that failed the schema (toolschema.go): | ||
| 48 | + // the same invalid call repeated ends the turn. | ||
| 49 | + invalid invalidCalls | ||
| 50 | + // The hand-backs of this generation, each bounded by its max*Retries. | ||
| 51 | + argRetries, cutRetries, loopRetries, editRetries int | ||
| 52 | + // printed: some answer text reached the screen or the client. | ||
| 53 | + printed bool | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +func newTurn(e *Engine, messages []*ai.Message) *turn { | ||
| 57 | + return &turn{e: e, messages: messages, speed: turnSpeedMeter(), think: &thoughts{}} | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +// finishSpeed closes the turn's speed measure (deferred by generate). | ||
| 61 | +func (t *turn) finishSpeed() { | ||
| 62 | + if t.speed != nil { | ||
| 63 | + t.speed.finish() | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +// options are the Genkit options of the turn, the middleware included. | ||
| 68 | +func (t *turn) options(tools []ai.ToolRef) []ai.GenerateOption { | ||
| 69 | + capture := ai.MiddlewareFunc(func(context.Context) (*ai.Hooks, error) { | ||
| 70 | + return &ai.Hooks{WrapModel: t.wrapModel, WrapTool: t.wrapTool}, nil | ||
| 71 | + }) | ||
| 72 | + opts := []ai.GenerateOption{ | ||
| 73 | + ai.WithModelName(t.e.Model), | ||
| 74 | + ai.WithMessages(t.messages...), | ||
| 75 | + ai.WithTools(tools...), | ||
| 76 | + ai.WithMaxTurns(config.Cfg.MaxTurns), // max model ↔ tools round trips | ||
| 77 | + ai.WithConfig(config.Cfg.Sampling), | ||
| 78 | + ai.WithUse(capture), | ||
| 79 | + } | ||
| 80 | + // structuredOutput (ticket 80): the server constrains the answer to the | ||
| 81 | + // schema, and Genkit checks it against the schema before handing it back. | ||
| 82 | + if config.Cfg.OutputSchema != nil { | ||
| 83 | + opts = append(opts, ai.WithOutputSchema(config.Cfg.OutputSchema)) | ||
| 84 | + } | ||
| 85 | + return opts | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +// watch is the turn's context: a watchdog that cancels it when the server is | ||
| 89 | +// silent too long — firstTokenTimeout while a model call reads its prompt, | ||
| 90 | +// WatchdogTimeout between tokens (progress.go) — with the taps that beat it. | ||
| 91 | +func (t *turn) watch(ctx context.Context) (context.Context, context.CancelFunc) { | ||
| 92 | + genCtx, p, cancel := watchdog(ctx, config.Cfg.WatchdogTimeout, | ||
| 93 | + firstTokenTimeout(config.Cfg.WatchdogTimeout, config.Cfg.FirstTokenTimeout)) | ||
| 94 | + t.pl = p | ||
| 95 | + genCtx = withHeartbeat(genCtx, p.beat) | ||
| 96 | + // A thinking model streams its reasoning in a field Genkit drops, so the | ||
| 97 | + // streaming callback never runs while it thinks (reasoning.go). The beat | ||
| 98 | + // matters more than the display here: without it the watchdog kills a turn | ||
| 99 | + // that is going perfectly well, and a model can reason for a long time | ||
| 100 | + // before its first word — 38s measured. The display is a setting; the | ||
| 101 | + // heartbeat never is. | ||
| 102 | + genCtx = WithReasoning(genCtx, func(text string) { | ||
| 103 | + p.beat() | ||
| 104 | + t.loops.feed(text) | ||
| 105 | + if config.Cfg.ShowThinking { | ||
| 106 | + t.think.emit(text) | ||
| 107 | + } | ||
| 108 | + }) | ||
| 109 | + // The error events a server streams, for the model calls to report | ||
| 110 | + // (servererr.go; read back in wrapModel through the context). | ||
| 111 | + genCtx, _ = withServerErrors(genCtx) | ||
| 112 | + // While the server reads the prompt it says how far it got: proof of life | ||
| 113 | + // for the watchdog, and something to show instead of "Thinking". | ||
| 114 | + genCtx = withSpeed(genCtx, t.speed) | ||
| 115 | + genCtx = withPromptProgress(genCtx, func(pp promptProgress) { | ||
| 116 | + p.alive() | ||
| 117 | + if p.waiting.Load() { | ||
| 118 | + spinner.Start(progressLabel(pp)) | ||
| 119 | + } | ||
| 120 | + }) | ||
| 121 | + return genCtx, cancel | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +// onChunk is the streaming callback: it beats the watchdog, lets the guard | ||
| 125 | +// watch tool-call arguments, and shows the text. | ||
| 126 | +func (t *turn) onChunk(guard *toolCallGuard) ai.ModelStreamCallback { | ||
| 127 | + return func(_ context.Context, chunk *ai.ModelResponseChunk) error { | ||
| 128 | + t.pl.beat() | ||
| 129 | + wasComposing := guard.composing | ||
| 130 | + if err := guard.observe(chunk); err != nil { | ||
| 131 | + return err | ||
| 132 | + } | ||
| 133 | + if guard.composing && !wasComposing { | ||
| 134 | + spinner.Start("Composing a tool call") | ||
| 135 | + } | ||
| 136 | + // Since Genkit 1.13 a chunk may carry nothing but reasoning. The tap | ||
| 137 | + // has already shown it (reasoning.go); handed to emit, its empty text | ||
| 138 | + // would close the thought block after every token. | ||
| 139 | + if onlyReasoning(chunk) { | ||
| 140 | + return nil | ||
| 141 | + } | ||
| 142 | + t.loops.feed(chunk.Text()) | ||
| 143 | + t.emit(chunk.Text()) | ||
| 144 | + return nil | ||
| 145 | + } | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +// emit shows answer text. The prefix is printed by the first token rather | ||
| 149 | +// than up front, so the spinner has a line to itself and vanishes without | ||
| 150 | +// taking anything with it. | ||
| 151 | +func (t *turn) emit(text string) { | ||
| 152 | + // An event-consuming front end (ACP) takes the chunk raw: the editor | ||
| 153 | + // renders Markdown and owns the layout, so the gap/squeeze machinery — | ||
| 154 | + // which fights the terminal screen, not the text — stays out of the way. | ||
| 155 | + // `printed` is still maintained: the no-streaming retry must know whether | ||
| 156 | + // the client already saw part of an answer. | ||
| 157 | + if s := ui.ActiveSink(); s != nil { | ||
| 158 | + if text == "" { | ||
| 159 | + return | ||
| 160 | + } | ||
| 161 | + t.think.done() | ||
| 162 | + t.printed = true | ||
| 163 | + s.Text(text) | ||
| 164 | + return | ||
| 165 | + } | ||
| 166 | + // The answer has started: the thinking that led to it is over. | ||
| 167 | + t.think.done() | ||
| 168 | + // Trailing whitespace is held back, not printed: see the gap type. | ||
| 169 | + out := t.gaps.next(text) | ||
| 170 | + if out == "" { | ||
| 171 | + return | ||
| 172 | + } | ||
| 173 | + // Stop BEFORE every print, not only the first one: a question can take | ||
| 174 | + // several turns, and the tool restarts the spinner on its way back to the | ||
| 175 | + // model; the text of the next turn then landed on the spinner's line, | ||
| 176 | + // which erased it on the following frame (`\r\033[2K`). Stop() is | ||
| 177 | + // idempotent and returns at once when nothing runs. | ||
| 178 | + spinner.Stop() | ||
| 179 | + if !t.printed { | ||
| 180 | + fmt.Print("🤖 ") | ||
| 181 | + t.printed = true | ||
| 182 | + } | ||
| 183 | + fmt.Print(out) | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +// retryableWithoutStreaming tells whether a failed turn may be replayed | ||
| 187 | +// without streaming. The retry is only worth it for an SSE stream cut before | ||
| 188 | +// the first byte. Any other error (maxTurns exceeded, a failing tool, | ||
| 189 | +// invalid arguments) happens AFTER commands have run, and replaying the turn | ||
| 190 | +// would replay them: measured, an `echo >>` wrote itself twice. `full` grows | ||
| 191 | +// as soon as a tool turn has happened, which tells the two apart. Never | ||
| 192 | +// retried either: the loop detector's stop (the repeated tool would run once | ||
| 193 | +// more), a tool call whose arguments did not parse (already handed back), a | ||
| 194 | +// request larger than the server's window (ticket 233), a looping model | ||
| 195 | +// (ticket 235). | ||
| 196 | +func (t *turn) retryableWithoutStreaming(err error) bool { | ||
| 197 | + if err == nil || t.printed || len(t.full) > len(t.messages) || contextOverflow(err) { | ||
| 198 | + return false | ||
| 199 | + } | ||
| 200 | + _, stuck := stuckTurn(err) | ||
| 201 | + truncated, malformed := argsError(err) | ||
| 202 | + _, isLoop := looped(err) | ||
| 203 | + return !stuck && !truncated && !malformed && !isLoop | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +// wrapTool runs one tool call: the whitespace the previous text left | ||
| 207 | +// pending is forgotten (the tool is about to print its 🛠️ line), the reply | ||
| 208 | +// that called it is passed on, and schemaGuard (toolschema.go, ticket 225) | ||
| 209 | +// wraps the hooks and the decision blocks: it repairs the file tools' | ||
| 210 | +// arguments before the hooks see them, and turns a schema error left after | ||
| 211 | +// them into a result the model reads. | ||
| 212 | +func (t *turn) wrapTool(ctx context.Context, params *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error) { | ||
| 213 | + t.gaps.drop() | ||
| 214 | + ctx = withReply(ctx, t.reply) | ||
| 215 | + return schemaGuard(ctx, params, &t.invalid, func(ctx context.Context, params *ai.ToolParams) (*ai.MultipartToolResponse, error) { | ||
| 216 | + if !t.e.hooks.Enabled() && toolJudge == nil && resultJudge == nil { | ||
| 217 | + return next(ctx, params) | ||
| 218 | + } | ||
| 219 | + return t.e.runToolHooks(ctx, params, next) | ||
| 220 | + }) | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +// modelCall runs ONE model call under its own context, which the loop watch | ||
| 224 | +// cancels when the stream repeats itself — the call, not the generation. | ||
| 225 | +type modelCall func(ctx context.Context) (*ai.ModelResponse, error) | ||
| 226 | + | ||
| 227 | +// wrapModel runs one model call of the turn, with its hand-backs. | ||
| 228 | +func (t *turn) wrapModel(ctx context.Context, params *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) { | ||
| 229 | + // Same tools, same order, on every call: the server's prompt cache | ||
| 230 | + // depends on it (tooldefs.go, ticket 53). | ||
| 231 | + params.Request.Tools = stableTools(params.Request.Tools) | ||
| 232 | + // From the turn's second call on — tools have run — a history past the | ||
| 233 | + // threshold is made smaller first (inturn.go, ticket 251). The wait | ||
| 234 | + // counts as the call's: the summary is no beat. | ||
| 235 | + if config.Cfg.Context.CompressInTurn && len(params.Request.Messages) > len(t.messages) { | ||
| 236 | + t.pl.expect() | ||
| 237 | + t.e.compactInTurn(ctx, params) | ||
| 238 | + } | ||
| 239 | + // Messages the user sent during the turn (ticket 265, steer.go) join the | ||
| 240 | + // history after the tool results. | ||
| 241 | + params.Request.Messages = takeSteer(ctx, params.Request.Messages) | ||
| 242 | + t.full = slices.Clone(params.Request.Messages) | ||
| 243 | + call := func(ctx context.Context) (*ai.ModelResponse, error) { | ||
| 244 | + callCtx, cancel := context.WithCancel(ctx) | ||
| 245 | + defer cancel() | ||
| 246 | + t.loops.arm(cancel) | ||
| 247 | + defer t.loops.disarm() | ||
| 248 | + return next(callCtx, params) | ||
| 249 | + } | ||
| 250 | + t.pl.expect() | ||
| 251 | + resp, err := call(ctx) | ||
| 252 | + err = withServerMessage(ctx, err) | ||
| 253 | + resp, err, stop := t.retryLoops(ctx, params, call, resp, err) | ||
| 254 | + if stop { | ||
| 255 | + return resp, err | ||
| 256 | + } | ||
| 257 | + resp, err = t.retryBrokenStream(ctx, call, resp, err) | ||
| 258 | + resp, err = t.retryBrokenArgs(ctx, params, call, resp, err) | ||
| 259 | + resp, err = t.retryCutReasoning(ctx, params, call, resp, err) | ||
| 260 | + resp, err = t.retryFailedEdit(ctx, params, call, resp, err) | ||
| 261 | + t.recordUsage(resp) | ||
| 262 | + dropReasoning(resp) | ||
| 263 | + if resp != nil { | ||
| 264 | + t.reply = resp.Message | ||
| 265 | + } | ||
| 266 | + return resp, err | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +// handBack runs the call again with notes appended to the request. The | ||
| 270 | +// notes go into params.Request itself: Genkit builds the next call's | ||
| 271 | +// request from that same value, so they stay in the conversation, and | ||
| 272 | +// `full` carries them into the history. | ||
| 273 | +func (t *turn) handBack(ctx context.Context, params *ai.ModelParams, call modelCall, notes ...*ai.Message) (*ai.ModelResponse, error) { | ||
| 274 | + params.Request.Messages = append(slices.Clone(params.Request.Messages), notes...) | ||
| 275 | + t.full = slices.Clone(params.Request.Messages) | ||
| 276 | + t.pl.expect() | ||
| 277 | + resp, err := call(ctx) | ||
| 278 | + return resp, withServerMessage(ctx, err) | ||
| 279 | +} | ||
| 280 | + | ||
| 281 | +// struggle stops the spinner, prints line on ui.Out (stderr in ACP mode, | ||
| 282 | +// never the JSON-RPC stream) and reports the struggle. | ||
| 283 | +func struggle(line, label string) { | ||
| 284 | + spinner.Stop() | ||
| 285 | + _, _ = fmt.Fprintf(ui.Out, "\n[%s]\n", line) | ||
| 286 | + ui.ReportStruggle(ui.Struggle{Label: label}) | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +// retryLoops hands back a call cut because the model was repeating itself, | ||
| 290 | +// once with a note; looping again ends the turn (textloop.go, ticket 235): | ||
| 291 | +// stop is then true and err a loopError. | ||
| 292 | +func (t *turn) retryLoops(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error, bool) { | ||
| 293 | + for ctx.Err() == nil { | ||
| 294 | + sample, times, cut := t.loops.take() | ||
| 295 | + if !cut { | ||
| 296 | + break | ||
| 297 | + } | ||
| 298 | + t.think.done() | ||
| 299 | + if t.loopRetries >= maxLoopRetries { | ||
| 300 | + spinner.Stop() | ||
| 301 | + return nil, loopError{sample: sample, times: times}, true | ||
| 302 | + } | ||
| 303 | + t.loopRetries++ | ||
| 304 | + struggle(fmt.Sprintf("the model repeated %q %d times in a row — stopped it and asked for the answer, %d/%d", shorten(sample, 60), times, t.loopRetries, maxLoopRetries), | ||
| 305 | + fmt.Sprintf("looped — handed back %d/%d", t.loopRetries, maxLoopRetries)) | ||
| 306 | + resp, err = t.handBack(ctx, params, call, loopRetryNote(sample, times)) | ||
| 307 | + } | ||
| 308 | + return resp, err, false | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +// retryBrokenStream retries ONCE a stream the server broke — an error event, | ||
| 312 | +// a cut connection (servererr.go) — this model call only. The turn-level | ||
| 313 | +// retry cannot help once a tool has run (it would replay the tools); this | ||
| 314 | +// one replays nothing but the call that failed. Seen: a turn ended on | ||
| 315 | +// "unexpected end of JSON input" after twenty tool calls and a written file. | ||
| 316 | +// Text the broken attempt already streamed is not taken back. | ||
| 317 | +func (t *turn) retryBrokenStream(ctx context.Context, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) { | ||
| 318 | + if !streamBroken(err) || contextOverflow(err) || ctx.Err() != nil { | ||
| 319 | + return resp, err | ||
| 320 | + } | ||
| 321 | + struggle(streamNotice(err)+" — retrying this model call once", "stream cut — retried") | ||
| 322 | + t.pl.expect() | ||
| 323 | + resp, err = call(ctx) | ||
| 324 | + return resp, withServerMessage(ctx, err) | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +// retryBrokenArgs hands back a tool call whose arguments did not parse — | ||
| 328 | +// cut off by max_tokens, most of the time — with a note instead of ending | ||
| 329 | +// the turn: the model needs the note again when it writes the second piece. | ||
| 330 | +func (t *turn) retryBrokenArgs(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) { | ||
| 331 | + for t.argRetries < maxArgRetries && ctx.Err() == nil { | ||
| 332 | + truncated, malformed := argsError(err) | ||
| 333 | + if !truncated && !malformed { | ||
| 334 | + break | ||
| 335 | + } | ||
| 336 | + t.argRetries++ | ||
| 337 | + what := "invalid JSON" | ||
| 338 | + if truncated { | ||
| 339 | + what = "cut off" | ||
| 340 | + } | ||
| 341 | + struggle(fmt.Sprintf("tool call arguments did not parse (%s: …%s) — handing it back to the model, %d/%d", what, lastRunes(err.Error(), 60), t.argRetries, maxArgRetries), | ||
| 342 | + fmt.Sprintf("broken tool call (%s) %d/%d", what, t.argRetries, maxArgRetries)) | ||
| 343 | + resp, err = t.handBack(ctx, params, call, argsRetryNote(truncated)) | ||
| 344 | + } | ||
| 345 | + return resp, err | ||
| 346 | +} | ||
| 347 | + | ||
| 348 | +// retryCutReasoning hands back, once, a reply cut by the answer limit while | ||
| 349 | +// the model was still reasoning — no text, no tool call (toolargs.go, | ||
| 350 | +// ticket 232). | ||
| 351 | +func (t *turn) retryCutReasoning(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) { | ||
| 352 | + for t.cutRetries < maxCutRetries && ctx.Err() == nil && reasoningCut(resp, err) { | ||
| 353 | + t.cutRetries++ | ||
| 354 | + struggle(fmt.Sprintf("the model reasoned until the answer limit without answering — asking it to act now, %d/%d", t.cutRetries, maxCutRetries), | ||
| 355 | + fmt.Sprintf("reasoning cut at the limit %d/%d", t.cutRetries, maxCutRetries)) | ||
| 356 | + resp, err = t.handBack(ctx, params, call, cutRetryNote()) | ||
| 357 | + } | ||
| 358 | + return resp, err | ||
| 359 | +} | ||
| 360 | + | ||
| 361 | +// retryFailedEdit hands back, once, an ANSWER given while the turn's last | ||
| 362 | +// file change failed (toolargs.go, ticket 242): the model can still fix its | ||
| 363 | +// call, or say it failed. The answer stays in the conversation, so the note | ||
| 364 | +// can refer to it. | ||
| 365 | +func (t *turn) retryFailedEdit(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) { | ||
| 366 | + for t.editRetries < maxEditRetries && ctx.Err() == nil && isAnswer(resp, err) { | ||
| 367 | + turn := params.Request.Messages[min(len(t.messages), len(params.Request.Messages)):] | ||
| 368 | + tool, failure, failed := lastFailedFileChange(turn) | ||
| 369 | + if !failed { | ||
| 370 | + break | ||
| 371 | + } | ||
| 372 | + t.editRetries++ | ||
| 373 | + t.think.done() | ||
| 374 | + struggle(fmt.Sprintf("the last %s failed — the file was not changed; asking the model to fix the call or say so, %d/%d", tool, t.editRetries, maxEditRetries), | ||
| 375 | + fmt.Sprintf("answer after a failed %s — handed back %d/%d", tool, t.editRetries, maxEditRetries)) | ||
| 376 | + resp, err = t.handBack(ctx, params, call, ai.NewModelTextMessage(resp.Text()), failedEditNote(tool, failure)) | ||
| 377 | + } | ||
| 378 | + return resp, err | ||
| 379 | +} | ||
| 380 | + | ||
| 381 | +// isAnswer tells whether a call ended with an answer: a message and no tool | ||
| 382 | +// call. | ||
| 383 | +func isAnswer(resp *ai.ModelResponse, err error) bool { | ||
| 384 | + return err == nil && resp != nil && resp.Message != nil && len(resp.ToolRequests()) == 0 | ||
| 385 | +} | ||
| 386 | + | ||
| 387 | +// recordUsage keeps the server's own count of what it just read — the one | ||
| 388 | +// exact measure of the context size, for the compression trigger — settles | ||
| 389 | +// the call's speed, and hands every call's counts to a front end that wants | ||
| 390 | +// them (ACP: the context meter, the tokens a turn cost). | ||
| 391 | +func (t *turn) recordUsage(resp *ai.ModelResponse) { | ||
| 392 | + if resp == nil { | ||
| 393 | + return | ||
| 394 | + } | ||
| 395 | + if resp.Usage != nil && resp.Usage.InputTokens > 0 { | ||
| 396 | + t.e.lastInput.Store(int64(resp.Usage.InputTokens)) | ||
| 397 | + } | ||
| 398 | + if t.speed != nil { | ||
| 399 | + out := 0 | ||
| 400 | + if resp.Usage != nil { | ||
| 401 | + out = resp.Usage.OutputTokens | ||
| 402 | + } | ||
| 403 | + t.speed.settle(out) | ||
| 404 | + } | ||
| 405 | + if s, ok := ui.ActiveSink().(ui.UsageSink); ok && resp.Usage != nil { | ||
| 406 | + s.Usage(ui.Usage{ | ||
| 407 | + InputTokens: resp.Usage.InputTokens, | ||
| 408 | + OutputTokens: resp.Usage.OutputTokens, | ||
| 409 | + ThoughtTokens: resp.Usage.ThoughtsTokens, | ||
| 410 | + CachedReadTokens: resp.Usage.CachedContentTokens, | ||
| 411 | + }) | ||
| 412 | + } | ||
| 413 | +} | ||
modified
internal/engine/unload.go +35 -17 | @@ -107,23 +107,32 @@ func UnloadAgent(ctx context.Context, configPath string) string { | ||
| 107 | 107 | if err != nil { |
| 108 | 108 | return fmt.Sprintf("cannot unload the model of %s: %v", configPath, err) |
| 109 | 109 | } |
| 110 | + u, b, err := agentUnloader(cfg) | |
| 111 | + if err == nil { | |
| 112 | + var line string | |
| 113 | + if line, err = u.Unload(ctx, b, cfg.Model); err == nil { | |
| 114 | + return line | |
| 115 | + } | |
| 116 | + } | |
| 117 | + return fmt.Sprintf("cannot unload %s: %v", cfg.Model, err) | |
| 118 | +} | |
| 119 | + | |
| 120 | +// agentUnloader is the provider of another agent's file, as an Unloader, and | |
| 121 | +// the server it resolves to (ResolveDecider: never AGENT_BASE_URL). | |
| 122 | +func agentUnloader(cfg config.Config) (Unloader, Backend, error) { | |
| 110 | 123 | p, err := Lookup(cfg.Provider) |
| 111 | 124 | if err != nil { |
| 112 | - return fmt.Sprintf("cannot unload %s: %v", cfg.Model, err) | |
| 125 | + return nil, Backend{}, err | |
| 113 | 126 | } |
| 114 | 127 | b, err := ResolveDecider(cfg) |
| 115 | 128 | if err != nil { |
| 116 | - return fmt.Sprintf("cannot unload %s: %v", cfg.Model, err) | |
| 129 | + return nil, Backend{}, err | |
| 117 | 130 | } |
| 118 | 131 | u, ok := p.(Unloader) |
| 119 | 132 | if !ok { |
| 120 | - return fmt.Sprintf("cannot unload %s: the %s provider cannot unload a model", cfg.Model, cfg.Provider) | |
| 121 | - } | |
| 122 | - line, err := u.Unload(ctx, b, cfg.Model) | |
| 123 | - if err != nil { | |
| 124 | - return fmt.Sprintf("cannot unload %s: %v", cfg.Model, err) | |
| 133 | + return nil, Backend{}, fmt.Errorf("the %s provider cannot unload a model", cfg.Provider) | |
| 125 | 134 | } |
| 126 | - return line | |
| 135 | + return u, b, nil | |
| 127 | 136 | } |
| 128 | 137 | |
| 129 | 138 | // Unload implements Unloader with the server's own way, when it has one. |
| @@ -153,20 +162,29 @@ func unloadKeepAlive(ctx context.Context, b Backend, model string) (string, erro | ||
| 153 | 162 | if !slices.Contains(loaded, model) { |
| 154 | 163 | return notLoaded(model), nil |
| 155 | 164 | } |
| 165 | + if err := keepAliveZero(ctx, b, root, model); err != nil { | |
| 166 | + return "", err | |
| 167 | + } | |
| 168 | + return "unloaded " + model, nil | |
| 169 | +} | |
| 170 | + | |
| 171 | +// keepAliveZero asks the server to drop model now (a generate with | |
| 172 | +// keep_alive 0) and checks that it says it did. | |
| 173 | +func keepAliveZero(ctx context.Context, b Backend, root, model string) error { | |
| 156 | 174 | var reply struct { |
| 157 | 175 | DoneReason string `json:"done_reason"` |
| 158 | 176 | Error string `json:"error"` |
| 159 | 177 | } |
| 160 | - if err := postJSON(ctx, b, root+"/api/generate", map[string]any{"model": model, "keep_alive": 0}, &reply); err != nil { | |
| 161 | - return "", err | |
| 162 | - } | |
| 163 | - if reply.Error != "" { | |
| 164 | - return "", fmt.Errorf("the server says: %s", reply.Error) | |
| 165 | - } | |
| 166 | - if reply.DoneReason != "unload" { | |
| 167 | - return "", fmt.Errorf("the server did not confirm (done_reason %q)", reply.DoneReason) | |
| 178 | + err := postJSON(ctx, b, root+"/api/generate", map[string]any{"model": model, "keep_alive": 0}, &reply) | |
| 179 | + switch { | |
| 180 | + case err != nil: | |
| 181 | + return err | |
| 182 | + case reply.Error != "": | |
| 183 | + return fmt.Errorf("the server says: %s", reply.Error) | |
| 184 | + case reply.DoneReason != "unload": | |
| 185 | + return fmt.Errorf("the server did not confirm (done_reason %q)", reply.DoneReason) | |
| 168 | 186 | } |
| 169 | - return "unloaded " + model, nil | |
| 187 | + return nil | |
| 170 | 188 | } |
| 171 | 189 | |
| 172 | 190 | // loadedModels lists the names /api/ps reports as loaded. |
| @@ -107,23 +107,32 @@ func UnloadAgent(ctx context.Context, configPath string) string { | |||
| 107 | if err != nil { | 107 | if err != nil { |
| 108 | return fmt.Sprintf("cannot unload the model of %s: %v", configPath, err) | 108 | return fmt.Sprintf("cannot unload the model of %s: %v", configPath, err) |
| 109 | } | 109 | } |
| 110 | + u, b, err := agentUnloader(cfg) | ||
| 111 | + if err == nil { | ||
| 112 | + var line string | ||
| 113 | + if line, err = u.Unload(ctx, b, cfg.Model); err == nil { | ||
| 114 | + return line | ||
| 115 | + } | ||
| 116 | + } | ||
| 117 | + return fmt.Sprintf("cannot unload %s: %v", cfg.Model, err) | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +// agentUnloader is the provider of another agent's file, as an Unloader, and | ||
| 121 | +// the server it resolves to (ResolveDecider: never AGENT_BASE_URL). | ||
| 122 | +func agentUnloader(cfg config.Config) (Unloader, Backend, error) { | ||
| 110 | p, err := Lookup(cfg.Provider) | 123 | p, err := Lookup(cfg.Provider) |
| 111 | if err != nil { | 124 | if err != nil { |
| 112 | - return fmt.Sprintf("cannot unload %s: %v", cfg.Model, err) | 125 | + return nil, Backend{}, err |
| 113 | } | 126 | } |
| 114 | b, err := ResolveDecider(cfg) | 127 | b, err := ResolveDecider(cfg) |
| 115 | if err != nil { | 128 | if err != nil { |
| 116 | - return fmt.Sprintf("cannot unload %s: %v", cfg.Model, err) | 129 | + return nil, Backend{}, err |
| 117 | } | 130 | } |
| 118 | u, ok := p.(Unloader) | 131 | u, ok := p.(Unloader) |
| 119 | if !ok { | 132 | if !ok { |
| 120 | - return fmt.Sprintf("cannot unload %s: the %s provider cannot unload a model", cfg.Model, cfg.Provider) | 133 | + return nil, Backend{}, fmt.Errorf("the %s provider cannot unload a model", cfg.Provider) |
| 121 | - } | ||
| 122 | - line, err := u.Unload(ctx, b, cfg.Model) | ||
| 123 | - if err != nil { | ||
| 124 | - return fmt.Sprintf("cannot unload %s: %v", cfg.Model, err) | ||
| 125 | } | 134 | } |
| 126 | - return line | 135 | + return u, b, nil |
| 127 | } | 136 | } |
| 128 | 137 | ||
| 129 | // Unload implements Unloader with the server's own way, when it has one. | 138 | // Unload implements Unloader with the server's own way, when it has one. |
| @@ -153,20 +162,29 @@ func unloadKeepAlive(ctx context.Context, b Backend, model string) (string, erro | |||
| 153 | if !slices.Contains(loaded, model) { | 162 | if !slices.Contains(loaded, model) { |
| 154 | return notLoaded(model), nil | 163 | return notLoaded(model), nil |
| 155 | } | 164 | } |
| 165 | + if err := keepAliveZero(ctx, b, root, model); err != nil { | ||
| 166 | + return "", err | ||
| 167 | + } | ||
| 168 | + return "unloaded " + model, nil | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +// keepAliveZero asks the server to drop model now (a generate with | ||
| 172 | +// keep_alive 0) and checks that it says it did. | ||
| 173 | +func keepAliveZero(ctx context.Context, b Backend, root, model string) error { | ||
| 156 | var reply struct { | 174 | var reply struct { |
| 157 | DoneReason string `json:"done_reason"` | 175 | DoneReason string `json:"done_reason"` |
| 158 | Error string `json:"error"` | 176 | Error string `json:"error"` |
| 159 | } | 177 | } |
| 160 | - if err := postJSON(ctx, b, root+"/api/generate", map[string]any{"model": model, "keep_alive": 0}, &reply); err != nil { | 178 | + err := postJSON(ctx, b, root+"/api/generate", map[string]any{"model": model, "keep_alive": 0}, &reply) |
| 161 | - return "", err | 179 | + switch { |
| 162 | - } | 180 | + case err != nil: |
| 163 | - if reply.Error != "" { | 181 | + return err |
| 164 | - return "", fmt.Errorf("the server says: %s", reply.Error) | 182 | + case reply.Error != "": |
| 165 | - } | 183 | + return fmt.Errorf("the server says: %s", reply.Error) |
| 166 | - if reply.DoneReason != "unload" { | 184 | + case reply.DoneReason != "unload": |
| 167 | - return "", fmt.Errorf("the server did not confirm (done_reason %q)", reply.DoneReason) | 185 | + return fmt.Errorf("the server did not confirm (done_reason %q)", reply.DoneReason) |
| 168 | } | 186 | } |
| 169 | - return "unloaded " + model, nil | 187 | + return nil |
| 170 | } | 188 | } |
| 171 | 189 | ||
| 172 | // loadedModels lists the names /api/ps reports as loaded. | 190 | // loadedModels lists the names /api/ps reports as loaded. |
added
internal/engine/xmlcalls.go +150 -0 | new file mode 100644 | ||
| @@ -0,0 +1,150 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "encoding/json" | |
| 5 | + "fmt" | |
| 6 | + "regexp" | |
| 7 | + "strings" | |
| 8 | + "sync/atomic" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// xmlCall is a tool call read from the text. | |
| 12 | +type xmlCall struct { | |
| 13 | + Name string | |
| 14 | + Arguments string // JSON, or the broken text the model wrote | |
| 15 | +} | |
| 16 | + | |
| 17 | +var callName = regexp.MustCompile(`"name"\s*:\s*"([^"]+)"`) | |
| 18 | + | |
| 19 | +// parseCall reads the inside of a <tool_call> block. A block that is not | |
| 20 | +// JSON still makes a call when its name can be read — its arguments are the | |
| 21 | +// broken text, which Genkit refuses and toolargs.go hands back to the model. | |
| 22 | +func parseCall(inside string) (xmlCall, bool) { | |
| 23 | + inside = strings.TrimSpace(inside) | |
| 24 | + var v struct { | |
| 25 | + Name string `json:"name"` | |
| 26 | + Arguments json.RawMessage `json:"arguments"` | |
| 27 | + } | |
| 28 | + if json.Unmarshal([]byte(inside), &v) == nil && v.Name != "" { | |
| 29 | + args := string(v.Arguments) | |
| 30 | + var quoted string | |
| 31 | + if json.Unmarshal(v.Arguments, "ed) == nil { | |
| 32 | + args = quoted // arguments written as a JSON string | |
| 33 | + } | |
| 34 | + if strings.TrimSpace(args) == "" || args == "null" { | |
| 35 | + args = "{}" | |
| 36 | + } | |
| 37 | + return xmlCall{Name: v.Name, Arguments: args}, true | |
| 38 | + } | |
| 39 | + m := callName.FindStringSubmatch(inside) | |
| 40 | + if m == nil { | |
| 41 | + return xmlCall{}, false | |
| 42 | + } | |
| 43 | + args := inside | |
| 44 | + if _, after, found := strings.Cut(inside, `"arguments"`); found { | |
| 45 | + args = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(after), ":")) | |
| 46 | + } | |
| 47 | + return xmlCall{Name: m[1], Arguments: args}, true | |
| 48 | +} | |
| 49 | + | |
| 50 | +// callParser takes the answer's text piece by piece and separates the | |
| 51 | +// <tool_call> blocks from the rest. It holds back what could be the start | |
| 52 | +// of a block, so no "<tool_c" reaches the screen before it is known. | |
| 53 | +type callParser struct { | |
| 54 | + buf string | |
| 55 | + inBlock bool | |
| 56 | +} | |
| 57 | + | |
| 58 | +// feed takes the next piece of text; it returns the text to show and the | |
| 59 | +// calls completed by this piece. | |
| 60 | +func (p *callParser) feed(s string) (string, []xmlCall) { | |
| 61 | + p.buf += s | |
| 62 | + var out strings.Builder | |
| 63 | + var calls []xmlCall | |
| 64 | + for { | |
| 65 | + if p.inBlock { | |
| 66 | + end := strings.Index(p.buf, toolCallClose) | |
| 67 | + if end < 0 { | |
| 68 | + break | |
| 69 | + } | |
| 70 | + inside := p.buf[:end] | |
| 71 | + p.buf, p.inBlock = p.buf[end+len(toolCallClose):], false | |
| 72 | + if c, ok := parseCall(inside); ok { | |
| 73 | + calls = append(calls, c) | |
| 74 | + } else { | |
| 75 | + out.WriteString(toolCallOpen + inside + toolCallClose) | |
| 76 | + } | |
| 77 | + continue | |
| 78 | + } | |
| 79 | + if start := strings.Index(p.buf, toolCallOpen); start >= 0 { | |
| 80 | + out.WriteString(p.buf[:start]) | |
| 81 | + p.buf, p.inBlock = p.buf[start+len(toolCallOpen):], true | |
| 82 | + continue | |
| 83 | + } | |
| 84 | + hold := partialOpen(p.buf) | |
| 85 | + out.WriteString(p.buf[:len(p.buf)-hold]) | |
| 86 | + p.buf = p.buf[len(p.buf)-hold:] | |
| 87 | + break | |
| 88 | + } | |
| 89 | + return out.String(), calls | |
| 90 | +} | |
| 91 | + | |
| 92 | +// flush ends the answer: what was held back is shown, and a block cut by | |
| 93 | +// the end (max_tokens) still makes a call when its name can be read. | |
| 94 | +func (p *callParser) flush() (string, []xmlCall) { | |
| 95 | + rest, inBlock := p.buf, p.inBlock | |
| 96 | + p.buf, p.inBlock = "", false | |
| 97 | + if !inBlock { | |
| 98 | + return rest, nil | |
| 99 | + } | |
| 100 | + if c, ok := parseCall(rest); ok { | |
| 101 | + return "", []xmlCall{c} | |
| 102 | + } | |
| 103 | + return toolCallOpen + rest, nil | |
| 104 | +} | |
| 105 | + | |
| 106 | +// partialOpen is the length of the longest end of s that begins "<tool_call>". | |
| 107 | +func partialOpen(s string) int { | |
| 108 | + for n := min(len(toolCallOpen)-1, len(s)); n > 0; n-- { | |
| 109 | + if strings.HasSuffix(s, toolCallOpen[:n]) { | |
| 110 | + return n | |
| 111 | + } | |
| 112 | + } | |
| 113 | + return 0 | |
| 114 | +} | |
| 115 | + | |
| 116 | +// callIDs numbers the calls of one answer; the prefix keeps two answers' | |
| 117 | +// ids apart in the history. | |
| 118 | +type callIDs struct { | |
| 119 | + prefix string | |
| 120 | + next int | |
| 121 | +} | |
| 122 | + | |
| 123 | +var answerCount atomic.Uint64 | |
| 124 | + | |
| 125 | +func newCallIDs() *callIDs { | |
| 126 | + return &callIDs{prefix: fmt.Sprintf("call_xml%d", answerCount.Add(1))} | |
| 127 | +} | |
| 128 | + | |
| 129 | +func (c *callIDs) id() string { | |
| 130 | + c.next++ | |
| 131 | + return fmt.Sprintf("%s_%d", c.prefix, c.next) | |
| 132 | +} | |
| 133 | + | |
| 134 | +// openaiCall is a tool call in the OpenAI API's shape; Index is set in a | |
| 135 | +// streamed delta only. | |
| 136 | +type openaiCall struct { | |
| 137 | + Index *int `json:"index,omitempty"` | |
| 138 | + ID string `json:"id"` | |
| 139 | + Type string `json:"type"` | |
| 140 | + Function struct { | |
| 141 | + Name string `json:"name"` | |
| 142 | + Arguments string `json:"arguments"` | |
| 143 | + } `json:"function"` | |
| 144 | +} | |
| 145 | + | |
| 146 | +func toOpenAI(c xmlCall, id string, index *int) openaiCall { | |
| 147 | + o := openaiCall{Index: index, ID: id, Type: "function"} | |
| 148 | + o.Function.Name, o.Function.Arguments = c.Name, c.Arguments | |
| 149 | + return o | |
| 150 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,150 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "encoding/json" | ||
| 5 | + "fmt" | ||
| 6 | + "regexp" | ||
| 7 | + "strings" | ||
| 8 | + "sync/atomic" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// xmlCall is a tool call read from the text. | ||
| 12 | +type xmlCall struct { | ||
| 13 | + Name string | ||
| 14 | + Arguments string // JSON, or the broken text the model wrote | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +var callName = regexp.MustCompile(`"name"\s*:\s*"([^"]+)"`) | ||
| 18 | + | ||
| 19 | +// parseCall reads the inside of a <tool_call> block. A block that is not | ||
| 20 | +// JSON still makes a call when its name can be read — its arguments are the | ||
| 21 | +// broken text, which Genkit refuses and toolargs.go hands back to the model. | ||
| 22 | +func parseCall(inside string) (xmlCall, bool) { | ||
| 23 | + inside = strings.TrimSpace(inside) | ||
| 24 | + var v struct { | ||
| 25 | + Name string `json:"name"` | ||
| 26 | + Arguments json.RawMessage `json:"arguments"` | ||
| 27 | + } | ||
| 28 | + if json.Unmarshal([]byte(inside), &v) == nil && v.Name != "" { | ||
| 29 | + args := string(v.Arguments) | ||
| 30 | + var quoted string | ||
| 31 | + if json.Unmarshal(v.Arguments, "ed) == nil { | ||
| 32 | + args = quoted // arguments written as a JSON string | ||
| 33 | + } | ||
| 34 | + if strings.TrimSpace(args) == "" || args == "null" { | ||
| 35 | + args = "{}" | ||
| 36 | + } | ||
| 37 | + return xmlCall{Name: v.Name, Arguments: args}, true | ||
| 38 | + } | ||
| 39 | + m := callName.FindStringSubmatch(inside) | ||
| 40 | + if m == nil { | ||
| 41 | + return xmlCall{}, false | ||
| 42 | + } | ||
| 43 | + args := inside | ||
| 44 | + if _, after, found := strings.Cut(inside, `"arguments"`); found { | ||
| 45 | + args = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(after), ":")) | ||
| 46 | + } | ||
| 47 | + return xmlCall{Name: m[1], Arguments: args}, true | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +// callParser takes the answer's text piece by piece and separates the | ||
| 51 | +// <tool_call> blocks from the rest. It holds back what could be the start | ||
| 52 | +// of a block, so no "<tool_c" reaches the screen before it is known. | ||
| 53 | +type callParser struct { | ||
| 54 | + buf string | ||
| 55 | + inBlock bool | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +// feed takes the next piece of text; it returns the text to show and the | ||
| 59 | +// calls completed by this piece. | ||
| 60 | +func (p *callParser) feed(s string) (string, []xmlCall) { | ||
| 61 | + p.buf += s | ||
| 62 | + var out strings.Builder | ||
| 63 | + var calls []xmlCall | ||
| 64 | + for { | ||
| 65 | + if p.inBlock { | ||
| 66 | + end := strings.Index(p.buf, toolCallClose) | ||
| 67 | + if end < 0 { | ||
| 68 | + break | ||
| 69 | + } | ||
| 70 | + inside := p.buf[:end] | ||
| 71 | + p.buf, p.inBlock = p.buf[end+len(toolCallClose):], false | ||
| 72 | + if c, ok := parseCall(inside); ok { | ||
| 73 | + calls = append(calls, c) | ||
| 74 | + } else { | ||
| 75 | + out.WriteString(toolCallOpen + inside + toolCallClose) | ||
| 76 | + } | ||
| 77 | + continue | ||
| 78 | + } | ||
| 79 | + if start := strings.Index(p.buf, toolCallOpen); start >= 0 { | ||
| 80 | + out.WriteString(p.buf[:start]) | ||
| 81 | + p.buf, p.inBlock = p.buf[start+len(toolCallOpen):], true | ||
| 82 | + continue | ||
| 83 | + } | ||
| 84 | + hold := partialOpen(p.buf) | ||
| 85 | + out.WriteString(p.buf[:len(p.buf)-hold]) | ||
| 86 | + p.buf = p.buf[len(p.buf)-hold:] | ||
| 87 | + break | ||
| 88 | + } | ||
| 89 | + return out.String(), calls | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +// flush ends the answer: what was held back is shown, and a block cut by | ||
| 93 | +// the end (max_tokens) still makes a call when its name can be read. | ||
| 94 | +func (p *callParser) flush() (string, []xmlCall) { | ||
| 95 | + rest, inBlock := p.buf, p.inBlock | ||
| 96 | + p.buf, p.inBlock = "", false | ||
| 97 | + if !inBlock { | ||
| 98 | + return rest, nil | ||
| 99 | + } | ||
| 100 | + if c, ok := parseCall(rest); ok { | ||
| 101 | + return "", []xmlCall{c} | ||
| 102 | + } | ||
| 103 | + return toolCallOpen + rest, nil | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +// partialOpen is the length of the longest end of s that begins "<tool_call>". | ||
| 107 | +func partialOpen(s string) int { | ||
| 108 | + for n := min(len(toolCallOpen)-1, len(s)); n > 0; n-- { | ||
| 109 | + if strings.HasSuffix(s, toolCallOpen[:n]) { | ||
| 110 | + return n | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + return 0 | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +// callIDs numbers the calls of one answer; the prefix keeps two answers' | ||
| 117 | +// ids apart in the history. | ||
| 118 | +type callIDs struct { | ||
| 119 | + prefix string | ||
| 120 | + next int | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +var answerCount atomic.Uint64 | ||
| 124 | + | ||
| 125 | +func newCallIDs() *callIDs { | ||
| 126 | + return &callIDs{prefix: fmt.Sprintf("call_xml%d", answerCount.Add(1))} | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +func (c *callIDs) id() string { | ||
| 130 | + c.next++ | ||
| 131 | + return fmt.Sprintf("%s_%d", c.prefix, c.next) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +// openaiCall is a tool call in the OpenAI API's shape; Index is set in a | ||
| 135 | +// streamed delta only. | ||
| 136 | +type openaiCall struct { | ||
| 137 | + Index *int `json:"index,omitempty"` | ||
| 138 | + ID string `json:"id"` | ||
| 139 | + Type string `json:"type"` | ||
| 140 | + Function struct { | ||
| 141 | + Name string `json:"name"` | ||
| 142 | + Arguments string `json:"arguments"` | ||
| 143 | + } `json:"function"` | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +func toOpenAI(c xmlCall, id string, index *int) openaiCall { | ||
| 147 | + o := openaiCall{Index: index, ID: id, Type: "function"} | ||
| 148 | + o.Function.Name, o.Function.Arguments = c.Name, c.Arguments | ||
| 149 | + return o | ||
| 150 | +} | ||
added
internal/engine/xmlresponse.go +154 -0 | new file mode 100644 | ||
| @@ -0,0 +1,154 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "bytes" | |
| 5 | + "encoding/json" | |
| 6 | + "io" | |
| 7 | + "strings" | |
| 8 | +) | |
| 9 | + | |
| 10 | +// xmlToolsResponse rewrites a whole (not streamed) answer. | |
| 11 | +func xmlToolsResponse(data []byte, ids *callIDs) []byte { | |
| 12 | + var m map[string]json.RawMessage | |
| 13 | + if json.Unmarshal(data, &m) != nil { | |
| 14 | + return data | |
| 15 | + } | |
| 16 | + var choices []map[string]json.RawMessage | |
| 17 | + if json.Unmarshal(m["choices"], &choices) != nil { | |
| 18 | + return data | |
| 19 | + } | |
| 20 | + changed := false | |
| 21 | + for _, choice := range choices { | |
| 22 | + var msg map[string]json.RawMessage | |
| 23 | + if json.Unmarshal(choice["message"], &msg) != nil { | |
| 24 | + continue | |
| 25 | + } | |
| 26 | + var p callParser | |
| 27 | + text, calls := p.feed(contentText(msg["content"])) | |
| 28 | + rest, more := p.flush() | |
| 29 | + text, calls = text+rest, append(calls, more...) | |
| 30 | + if len(calls) == 0 { | |
| 31 | + continue | |
| 32 | + } | |
| 33 | + list := make([]openaiCall, 0, len(calls)) | |
| 34 | + for _, c := range calls { | |
| 35 | + list = append(list, toOpenAI(c, ids.id(), nil)) | |
| 36 | + } | |
| 37 | + msg["content"], _ = json.Marshal(strings.TrimSpace(text)) | |
| 38 | + msg["tool_calls"], _ = json.Marshal(list) | |
| 39 | + choice["message"], _ = json.Marshal(msg) | |
| 40 | + choice["finish_reason"] = json.RawMessage(`"tool_calls"`) | |
| 41 | + changed = true | |
| 42 | + } | |
| 43 | + if !changed { | |
| 44 | + return data | |
| 45 | + } | |
| 46 | + m["choices"], _ = json.Marshal(choices) | |
| 47 | + out, err := json.Marshal(m) | |
| 48 | + if err != nil { | |
| 49 | + return data | |
| 50 | + } | |
| 51 | + return out | |
| 52 | +} | |
| 53 | + | |
| 54 | +// sseCalls rewrites a streamed answer line by line: the content of the | |
| 55 | +// first choice goes through a callParser, and each completed block is sent | |
| 56 | +// as a tool_calls delta in the chunk that completed it. | |
| 57 | +type sseCalls struct { | |
| 58 | + rc io.ReadCloser | |
| 59 | + ids *callIDs | |
| 60 | + parser callParser | |
| 61 | + calls int // calls sent so far: the next delta index | |
| 62 | + in []byte | |
| 63 | + out bytes.Buffer | |
| 64 | + eof bool | |
| 65 | + err error | |
| 66 | +} | |
| 67 | + | |
| 68 | +func (s *sseCalls) Close() error { return s.rc.Close() } | |
| 69 | + | |
| 70 | +func (s *sseCalls) Read(p []byte) (int, error) { | |
| 71 | + for s.out.Len() == 0 && !s.eof { | |
| 72 | + chunk := make([]byte, 4096) | |
| 73 | + n, err := s.rc.Read(chunk) | |
| 74 | + s.in = append(s.in, chunk[:n]...) | |
| 75 | + for { | |
| 76 | + i := bytes.IndexByte(s.in, '\n') | |
| 77 | + if i < 0 { | |
| 78 | + break | |
| 79 | + } | |
| 80 | + s.line(string(s.in[:i])) | |
| 81 | + s.in = s.in[i+1:] | |
| 82 | + } | |
| 83 | + if err != nil { | |
| 84 | + if len(s.in) > 0 { | |
| 85 | + s.line(string(s.in)) | |
| 86 | + s.in = nil | |
| 87 | + } | |
| 88 | + s.eof, s.err = true, err | |
| 89 | + } | |
| 90 | + } | |
| 91 | + if s.out.Len() > 0 { | |
| 92 | + return s.out.Read(p) | |
| 93 | + } | |
| 94 | + return 0, s.err | |
| 95 | +} | |
| 96 | + | |
| 97 | +// line rewrites one SSE line; anything but a data chunk goes through. | |
| 98 | +func (s *sseCalls) line(line string) { | |
| 99 | + data, ok := strings.CutPrefix(strings.TrimRight(line, "\r"), "data:") | |
| 100 | + data = strings.TrimSpace(data) | |
| 101 | + if !ok || data == "" || data == "[DONE]" { | |
| 102 | + s.out.WriteString(line + "\n") | |
| 103 | + return | |
| 104 | + } | |
| 105 | + rewritten, err := s.chunk([]byte(data)) | |
| 106 | + if err != nil { | |
| 107 | + s.out.WriteString(line + "\n") | |
| 108 | + return | |
| 109 | + } | |
| 110 | + s.out.WriteString("data: " + string(rewritten) + "\n") | |
| 111 | +} | |
| 112 | + | |
| 113 | +// chunk rewrites one streamed chunk's first choice. | |
| 114 | +func (s *sseCalls) chunk(data []byte) ([]byte, error) { | |
| 115 | + var m map[string]json.RawMessage | |
| 116 | + if err := json.Unmarshal(data, &m); err != nil { | |
| 117 | + return nil, err | |
| 118 | + } | |
| 119 | + var choices []map[string]json.RawMessage | |
| 120 | + if err := json.Unmarshal(m["choices"], &choices); err != nil || len(choices) == 0 { | |
| 121 | + return data, nil | |
| 122 | + } | |
| 123 | + choice := choices[0] | |
| 124 | + delta := map[string]json.RawMessage{} | |
| 125 | + if raw, ok := choice["delta"]; ok { | |
| 126 | + if err := json.Unmarshal(raw, &delta); err != nil { | |
| 127 | + return nil, err | |
| 128 | + } | |
| 129 | + } | |
| 130 | + text, calls := s.parser.feed(contentText(delta["content"])) | |
| 131 | + finished := len(choice["finish_reason"]) > 0 && string(choice["finish_reason"]) != "null" | |
| 132 | + if finished { | |
| 133 | + rest, more := s.parser.flush() | |
| 134 | + text, calls = text+rest, append(calls, more...) | |
| 135 | + } | |
| 136 | + if _, had := delta["content"]; had || text != "" { | |
| 137 | + delta["content"], _ = json.Marshal(text) | |
| 138 | + } | |
| 139 | + if len(calls) > 0 { | |
| 140 | + list := make([]openaiCall, 0, len(calls)) | |
| 141 | + for _, c := range calls { | |
| 142 | + index := s.calls | |
| 143 | + s.calls++ | |
| 144 | + list = append(list, toOpenAI(c, s.ids.id(), &index)) | |
| 145 | + } | |
| 146 | + delta["tool_calls"], _ = json.Marshal(list) | |
| 147 | + } | |
| 148 | + if finished && s.calls > 0 { | |
| 149 | + choice["finish_reason"] = json.RawMessage(`"tool_calls"`) | |
| 150 | + } | |
| 151 | + choice["delta"], _ = json.Marshal(delta) | |
| 152 | + m["choices"], _ = json.Marshal(choices) | |
| 153 | + return json.Marshal(m) | |
| 154 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,154 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "bytes" | ||
| 5 | + "encoding/json" | ||
| 6 | + "io" | ||
| 7 | + "strings" | ||
| 8 | +) | ||
| 9 | + | ||
| 10 | +// xmlToolsResponse rewrites a whole (not streamed) answer. | ||
| 11 | +func xmlToolsResponse(data []byte, ids *callIDs) []byte { | ||
| 12 | + var m map[string]json.RawMessage | ||
| 13 | + if json.Unmarshal(data, &m) != nil { | ||
| 14 | + return data | ||
| 15 | + } | ||
| 16 | + var choices []map[string]json.RawMessage | ||
| 17 | + if json.Unmarshal(m["choices"], &choices) != nil { | ||
| 18 | + return data | ||
| 19 | + } | ||
| 20 | + changed := false | ||
| 21 | + for _, choice := range choices { | ||
| 22 | + var msg map[string]json.RawMessage | ||
| 23 | + if json.Unmarshal(choice["message"], &msg) != nil { | ||
| 24 | + continue | ||
| 25 | + } | ||
| 26 | + var p callParser | ||
| 27 | + text, calls := p.feed(contentText(msg["content"])) | ||
| 28 | + rest, more := p.flush() | ||
| 29 | + text, calls = text+rest, append(calls, more...) | ||
| 30 | + if len(calls) == 0 { | ||
| 31 | + continue | ||
| 32 | + } | ||
| 33 | + list := make([]openaiCall, 0, len(calls)) | ||
| 34 | + for _, c := range calls { | ||
| 35 | + list = append(list, toOpenAI(c, ids.id(), nil)) | ||
| 36 | + } | ||
| 37 | + msg["content"], _ = json.Marshal(strings.TrimSpace(text)) | ||
| 38 | + msg["tool_calls"], _ = json.Marshal(list) | ||
| 39 | + choice["message"], _ = json.Marshal(msg) | ||
| 40 | + choice["finish_reason"] = json.RawMessage(`"tool_calls"`) | ||
| 41 | + changed = true | ||
| 42 | + } | ||
| 43 | + if !changed { | ||
| 44 | + return data | ||
| 45 | + } | ||
| 46 | + m["choices"], _ = json.Marshal(choices) | ||
| 47 | + out, err := json.Marshal(m) | ||
| 48 | + if err != nil { | ||
| 49 | + return data | ||
| 50 | + } | ||
| 51 | + return out | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +// sseCalls rewrites a streamed answer line by line: the content of the | ||
| 55 | +// first choice goes through a callParser, and each completed block is sent | ||
| 56 | +// as a tool_calls delta in the chunk that completed it. | ||
| 57 | +type sseCalls struct { | ||
| 58 | + rc io.ReadCloser | ||
| 59 | + ids *callIDs | ||
| 60 | + parser callParser | ||
| 61 | + calls int // calls sent so far: the next delta index | ||
| 62 | + in []byte | ||
| 63 | + out bytes.Buffer | ||
| 64 | + eof bool | ||
| 65 | + err error | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +func (s *sseCalls) Close() error { return s.rc.Close() } | ||
| 69 | + | ||
| 70 | +func (s *sseCalls) Read(p []byte) (int, error) { | ||
| 71 | + for s.out.Len() == 0 && !s.eof { | ||
| 72 | + chunk := make([]byte, 4096) | ||
| 73 | + n, err := s.rc.Read(chunk) | ||
| 74 | + s.in = append(s.in, chunk[:n]...) | ||
| 75 | + for { | ||
| 76 | + i := bytes.IndexByte(s.in, '\n') | ||
| 77 | + if i < 0 { | ||
| 78 | + break | ||
| 79 | + } | ||
| 80 | + s.line(string(s.in[:i])) | ||
| 81 | + s.in = s.in[i+1:] | ||
| 82 | + } | ||
| 83 | + if err != nil { | ||
| 84 | + if len(s.in) > 0 { | ||
| 85 | + s.line(string(s.in)) | ||
| 86 | + s.in = nil | ||
| 87 | + } | ||
| 88 | + s.eof, s.err = true, err | ||
| 89 | + } | ||
| 90 | + } | ||
| 91 | + if s.out.Len() > 0 { | ||
| 92 | + return s.out.Read(p) | ||
| 93 | + } | ||
| 94 | + return 0, s.err | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +// line rewrites one SSE line; anything but a data chunk goes through. | ||
| 98 | +func (s *sseCalls) line(line string) { | ||
| 99 | + data, ok := strings.CutPrefix(strings.TrimRight(line, "\r"), "data:") | ||
| 100 | + data = strings.TrimSpace(data) | ||
| 101 | + if !ok || data == "" || data == "[DONE]" { | ||
| 102 | + s.out.WriteString(line + "\n") | ||
| 103 | + return | ||
| 104 | + } | ||
| 105 | + rewritten, err := s.chunk([]byte(data)) | ||
| 106 | + if err != nil { | ||
| 107 | + s.out.WriteString(line + "\n") | ||
| 108 | + return | ||
| 109 | + } | ||
| 110 | + s.out.WriteString("data: " + string(rewritten) + "\n") | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +// chunk rewrites one streamed chunk's first choice. | ||
| 114 | +func (s *sseCalls) chunk(data []byte) ([]byte, error) { | ||
| 115 | + var m map[string]json.RawMessage | ||
| 116 | + if err := json.Unmarshal(data, &m); err != nil { | ||
| 117 | + return nil, err | ||
| 118 | + } | ||
| 119 | + var choices []map[string]json.RawMessage | ||
| 120 | + if err := json.Unmarshal(m["choices"], &choices); err != nil || len(choices) == 0 { | ||
| 121 | + return data, nil | ||
| 122 | + } | ||
| 123 | + choice := choices[0] | ||
| 124 | + delta := map[string]json.RawMessage{} | ||
| 125 | + if raw, ok := choice["delta"]; ok { | ||
| 126 | + if err := json.Unmarshal(raw, &delta); err != nil { | ||
| 127 | + return nil, err | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + text, calls := s.parser.feed(contentText(delta["content"])) | ||
| 131 | + finished := len(choice["finish_reason"]) > 0 && string(choice["finish_reason"]) != "null" | ||
| 132 | + if finished { | ||
| 133 | + rest, more := s.parser.flush() | ||
| 134 | + text, calls = text+rest, append(calls, more...) | ||
| 135 | + } | ||
| 136 | + if _, had := delta["content"]; had || text != "" { | ||
| 137 | + delta["content"], _ = json.Marshal(text) | ||
| 138 | + } | ||
| 139 | + if len(calls) > 0 { | ||
| 140 | + list := make([]openaiCall, 0, len(calls)) | ||
| 141 | + for _, c := range calls { | ||
| 142 | + index := s.calls | ||
| 143 | + s.calls++ | ||
| 144 | + list = append(list, toOpenAI(c, s.ids.id(), &index)) | ||
| 145 | + } | ||
| 146 | + delta["tool_calls"], _ = json.Marshal(list) | ||
| 147 | + } | ||
| 148 | + if finished && s.calls > 0 { | ||
| 149 | + choice["finish_reason"] = json.RawMessage(`"tool_calls"`) | ||
| 150 | + } | ||
| 151 | + choice["delta"], _ = json.Marshal(delta) | ||
| 152 | + m["choices"], _ = json.Marshal(choices) | ||
| 153 | + return json.Marshal(m) | ||
| 154 | +} | ||
modified
internal/engine/xmltools.go +6 -290 | @@ -3,12 +3,9 @@ package engine | ||
| 3 | 3 | import ( |
| 4 | 4 | "bytes" |
| 5 | 5 | "encoding/json" |
| 6 | - "fmt" | |
| 7 | 6 | "io" |
| 8 | 7 | "net/http" |
| 9 | - "regexp" | |
| 10 | 8 | "strings" |
| 11 | - "sync/atomic" | |
| 12 | 9 | |
| 13 | 10 | "github.com/openai/openai-go/option" |
| 14 | 11 | ) |
| @@ -58,6 +55,12 @@ func xmlTools(req *http.Request, next option.MiddlewareNext) (*http.Response, er | ||
| 58 | 55 | if err != nil || resp == nil || resp.Body == nil || resp.StatusCode != http.StatusOK { |
| 59 | 56 | return resp, err |
| 60 | 57 | } |
| 58 | + return xmlToolsReply(resp) | |
| 59 | +} | |
| 60 | + | |
| 61 | +// xmlToolsReply turns the XML tool calls of a successful answer into OpenAI | |
| 62 | +// ones: a stream as it is read (sseCalls), a whole body at once. | |
| 63 | +func xmlToolsReply(resp *http.Response) (*http.Response, error) { | |
| 61 | 64 | if strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { |
| 62 | 65 | resp.Body = &sseCalls{rc: resp.Body, ids: newCallIDs()} |
| 63 | 66 | return resp, nil |
| @@ -184,290 +187,3 @@ func callText(name, args string) string { | ||
| 184 | 187 | }{name, arguments}) |
| 185 | 188 | return "\n" + toolCallOpen + "\n" + string(call) + "\n" + toolCallClose |
| 186 | 189 | } |
| 187 | - | |
| 188 | -// xmlCall is a tool call read from the text. | |
| 189 | -type xmlCall struct { | |
| 190 | - Name string | |
| 191 | - Arguments string // JSON, or the broken text the model wrote | |
| 192 | -} | |
| 193 | - | |
| 194 | -var callName = regexp.MustCompile(`"name"\s*:\s*"([^"]+)"`) | |
| 195 | - | |
| 196 | -// parseCall reads the inside of a <tool_call> block. A block that is not | |
| 197 | -// JSON still makes a call when its name can be read — its arguments are the | |
| 198 | -// broken text, which Genkit refuses and toolargs.go hands back to the model. | |
| 199 | -func parseCall(inside string) (xmlCall, bool) { | |
| 200 | - inside = strings.TrimSpace(inside) | |
| 201 | - var v struct { | |
| 202 | - Name string `json:"name"` | |
| 203 | - Arguments json.RawMessage `json:"arguments"` | |
| 204 | - } | |
| 205 | - if json.Unmarshal([]byte(inside), &v) == nil && v.Name != "" { | |
| 206 | - args := string(v.Arguments) | |
| 207 | - var quoted string | |
| 208 | - if json.Unmarshal(v.Arguments, "ed) == nil { | |
| 209 | - args = quoted // arguments written as a JSON string | |
| 210 | - } | |
| 211 | - if strings.TrimSpace(args) == "" || args == "null" { | |
| 212 | - args = "{}" | |
| 213 | - } | |
| 214 | - return xmlCall{Name: v.Name, Arguments: args}, true | |
| 215 | - } | |
| 216 | - m := callName.FindStringSubmatch(inside) | |
| 217 | - if m == nil { | |
| 218 | - return xmlCall{}, false | |
| 219 | - } | |
| 220 | - args := inside | |
| 221 | - if _, after, found := strings.Cut(inside, `"arguments"`); found { | |
| 222 | - args = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(after), ":")) | |
| 223 | - } | |
| 224 | - return xmlCall{Name: m[1], Arguments: args}, true | |
| 225 | -} | |
| 226 | - | |
| 227 | -// callParser takes the answer's text piece by piece and separates the | |
| 228 | -// <tool_call> blocks from the rest. It holds back what could be the start | |
| 229 | -// of a block, so no "<tool_c" reaches the screen before it is known. | |
| 230 | -type callParser struct { | |
| 231 | - buf string | |
| 232 | - inBlock bool | |
| 233 | -} | |
| 234 | - | |
| 235 | -// feed takes the next piece of text; it returns the text to show and the | |
| 236 | -// calls completed by this piece. | |
| 237 | -func (p *callParser) feed(s string) (string, []xmlCall) { | |
| 238 | - p.buf += s | |
| 239 | - var out strings.Builder | |
| 240 | - var calls []xmlCall | |
| 241 | - for { | |
| 242 | - if p.inBlock { | |
| 243 | - end := strings.Index(p.buf, toolCallClose) | |
| 244 | - if end < 0 { | |
| 245 | - break | |
| 246 | - } | |
| 247 | - inside := p.buf[:end] | |
| 248 | - p.buf, p.inBlock = p.buf[end+len(toolCallClose):], false | |
| 249 | - if c, ok := parseCall(inside); ok { | |
| 250 | - calls = append(calls, c) | |
| 251 | - } else { | |
| 252 | - out.WriteString(toolCallOpen + inside + toolCallClose) | |
| 253 | - } | |
| 254 | - continue | |
| 255 | - } | |
| 256 | - if start := strings.Index(p.buf, toolCallOpen); start >= 0 { | |
| 257 | - out.WriteString(p.buf[:start]) | |
| 258 | - p.buf, p.inBlock = p.buf[start+len(toolCallOpen):], true | |
| 259 | - continue | |
| 260 | - } | |
| 261 | - hold := partialOpen(p.buf) | |
| 262 | - out.WriteString(p.buf[:len(p.buf)-hold]) | |
| 263 | - p.buf = p.buf[len(p.buf)-hold:] | |
| 264 | - break | |
| 265 | - } | |
| 266 | - return out.String(), calls | |
| 267 | -} | |
| 268 | - | |
| 269 | -// flush ends the answer: what was held back is shown, and a block cut by | |
| 270 | -// the end (max_tokens) still makes a call when its name can be read. | |
| 271 | -func (p *callParser) flush() (string, []xmlCall) { | |
| 272 | - rest, inBlock := p.buf, p.inBlock | |
| 273 | - p.buf, p.inBlock = "", false | |
| 274 | - if !inBlock { | |
| 275 | - return rest, nil | |
| 276 | - } | |
| 277 | - if c, ok := parseCall(rest); ok { | |
| 278 | - return "", []xmlCall{c} | |
| 279 | - } | |
| 280 | - return toolCallOpen + rest, nil | |
| 281 | -} | |
| 282 | - | |
| 283 | -// partialOpen is the length of the longest end of s that begins "<tool_call>". | |
| 284 | -func partialOpen(s string) int { | |
| 285 | - for n := min(len(toolCallOpen)-1, len(s)); n > 0; n-- { | |
| 286 | - if strings.HasSuffix(s, toolCallOpen[:n]) { | |
| 287 | - return n | |
| 288 | - } | |
| 289 | - } | |
| 290 | - return 0 | |
| 291 | -} | |
| 292 | - | |
| 293 | -// callIDs numbers the calls of one answer; the prefix keeps two answers' | |
| 294 | -// ids apart in the history. | |
| 295 | -type callIDs struct { | |
| 296 | - prefix string | |
| 297 | - next int | |
| 298 | -} | |
| 299 | - | |
| 300 | -var answerCount atomic.Uint64 | |
| 301 | - | |
| 302 | -func newCallIDs() *callIDs { | |
| 303 | - return &callIDs{prefix: fmt.Sprintf("call_xml%d", answerCount.Add(1))} | |
| 304 | -} | |
| 305 | - | |
| 306 | -func (c *callIDs) id() string { | |
| 307 | - c.next++ | |
| 308 | - return fmt.Sprintf("%s_%d", c.prefix, c.next) | |
| 309 | -} | |
| 310 | - | |
| 311 | -// openaiCall is a tool call in the OpenAI API's shape; Index is set in a | |
| 312 | -// streamed delta only. | |
| 313 | -type openaiCall struct { | |
| 314 | - Index *int `json:"index,omitempty"` | |
| 315 | - ID string `json:"id"` | |
| 316 | - Type string `json:"type"` | |
| 317 | - Function struct { | |
| 318 | - Name string `json:"name"` | |
| 319 | - Arguments string `json:"arguments"` | |
| 320 | - } `json:"function"` | |
| 321 | -} | |
| 322 | - | |
| 323 | -func toOpenAI(c xmlCall, id string, index *int) openaiCall { | |
| 324 | - o := openaiCall{Index: index, ID: id, Type: "function"} | |
| 325 | - o.Function.Name, o.Function.Arguments = c.Name, c.Arguments | |
| 326 | - return o | |
| 327 | -} | |
| 328 | - | |
| 329 | -// xmlToolsResponse rewrites a whole (not streamed) answer. | |
| 330 | -func xmlToolsResponse(data []byte, ids *callIDs) []byte { | |
| 331 | - var m map[string]json.RawMessage | |
| 332 | - if json.Unmarshal(data, &m) != nil { | |
| 333 | - return data | |
| 334 | - } | |
| 335 | - var choices []map[string]json.RawMessage | |
| 336 | - if json.Unmarshal(m["choices"], &choices) != nil { | |
| 337 | - return data | |
| 338 | - } | |
| 339 | - changed := false | |
| 340 | - for _, choice := range choices { | |
| 341 | - var msg map[string]json.RawMessage | |
| 342 | - if json.Unmarshal(choice["message"], &msg) != nil { | |
| 343 | - continue | |
| 344 | - } | |
| 345 | - var p callParser | |
| 346 | - text, calls := p.feed(contentText(msg["content"])) | |
| 347 | - rest, more := p.flush() | |
| 348 | - text, calls = text+rest, append(calls, more...) | |
| 349 | - if len(calls) == 0 { | |
| 350 | - continue | |
| 351 | - } | |
| 352 | - list := make([]openaiCall, 0, len(calls)) | |
| 353 | - for _, c := range calls { | |
| 354 | - list = append(list, toOpenAI(c, ids.id(), nil)) | |
| 355 | - } | |
| 356 | - msg["content"], _ = json.Marshal(strings.TrimSpace(text)) | |
| 357 | - msg["tool_calls"], _ = json.Marshal(list) | |
| 358 | - choice["message"], _ = json.Marshal(msg) | |
| 359 | - choice["finish_reason"] = json.RawMessage(`"tool_calls"`) | |
| 360 | - changed = true | |
| 361 | - } | |
| 362 | - if !changed { | |
| 363 | - return data | |
| 364 | - } | |
| 365 | - m["choices"], _ = json.Marshal(choices) | |
| 366 | - out, err := json.Marshal(m) | |
| 367 | - if err != nil { | |
| 368 | - return data | |
| 369 | - } | |
| 370 | - return out | |
| 371 | -} | |
| 372 | - | |
| 373 | -// sseCalls rewrites a streamed answer line by line: the content of the | |
| 374 | -// first choice goes through a callParser, and each completed block is sent | |
| 375 | -// as a tool_calls delta in the chunk that completed it. | |
| 376 | -type sseCalls struct { | |
| 377 | - rc io.ReadCloser | |
| 378 | - ids *callIDs | |
| 379 | - parser callParser | |
| 380 | - calls int // calls sent so far: the next delta index | |
| 381 | - in []byte | |
| 382 | - out bytes.Buffer | |
| 383 | - eof bool | |
| 384 | - err error | |
| 385 | -} | |
| 386 | - | |
| 387 | -func (s *sseCalls) Close() error { return s.rc.Close() } | |
| 388 | - | |
| 389 | -func (s *sseCalls) Read(p []byte) (int, error) { | |
| 390 | - for s.out.Len() == 0 && !s.eof { | |
| 391 | - chunk := make([]byte, 4096) | |
| 392 | - n, err := s.rc.Read(chunk) | |
| 393 | - s.in = append(s.in, chunk[:n]...) | |
| 394 | - for { | |
| 395 | - i := bytes.IndexByte(s.in, '\n') | |
| 396 | - if i < 0 { | |
| 397 | - break | |
| 398 | - } | |
| 399 | - s.line(string(s.in[:i])) | |
| 400 | - s.in = s.in[i+1:] | |
| 401 | - } | |
| 402 | - if err != nil { | |
| 403 | - if len(s.in) > 0 { | |
| 404 | - s.line(string(s.in)) | |
| 405 | - s.in = nil | |
| 406 | - } | |
| 407 | - s.eof, s.err = true, err | |
| 408 | - } | |
| 409 | - } | |
| 410 | - if s.out.Len() > 0 { | |
| 411 | - return s.out.Read(p) | |
| 412 | - } | |
| 413 | - return 0, s.err | |
| 414 | -} | |
| 415 | - | |
| 416 | -// line rewrites one SSE line; anything but a data chunk goes through. | |
| 417 | -func (s *sseCalls) line(line string) { | |
| 418 | - data, ok := strings.CutPrefix(strings.TrimRight(line, "\r"), "data:") | |
| 419 | - data = strings.TrimSpace(data) | |
| 420 | - if !ok || data == "" || data == "[DONE]" { | |
| 421 | - s.out.WriteString(line + "\n") | |
| 422 | - return | |
| 423 | - } | |
| 424 | - rewritten, err := s.chunk([]byte(data)) | |
| 425 | - if err != nil { | |
| 426 | - s.out.WriteString(line + "\n") | |
| 427 | - return | |
| 428 | - } | |
| 429 | - s.out.WriteString("data: " + string(rewritten) + "\n") | |
| 430 | -} | |
| 431 | - | |
| 432 | -// chunk rewrites one streamed chunk's first choice. | |
| 433 | -func (s *sseCalls) chunk(data []byte) ([]byte, error) { | |
| 434 | - var m map[string]json.RawMessage | |
| 435 | - if err := json.Unmarshal(data, &m); err != nil { | |
| 436 | - return nil, err | |
| 437 | - } | |
| 438 | - var choices []map[string]json.RawMessage | |
| 439 | - if err := json.Unmarshal(m["choices"], &choices); err != nil || len(choices) == 0 { | |
| 440 | - return data, nil | |
| 441 | - } | |
| 442 | - choice := choices[0] | |
| 443 | - delta := map[string]json.RawMessage{} | |
| 444 | - if raw, ok := choice["delta"]; ok { | |
| 445 | - if err := json.Unmarshal(raw, &delta); err != nil { | |
| 446 | - return nil, err | |
| 447 | - } | |
| 448 | - } | |
| 449 | - text, calls := s.parser.feed(contentText(delta["content"])) | |
| 450 | - finished := len(choice["finish_reason"]) > 0 && string(choice["finish_reason"]) != "null" | |
| 451 | - if finished { | |
| 452 | - rest, more := s.parser.flush() | |
| 453 | - text, calls = text+rest, append(calls, more...) | |
| 454 | - } | |
| 455 | - if _, had := delta["content"]; had || text != "" { | |
| 456 | - delta["content"], _ = json.Marshal(text) | |
| 457 | - } | |
| 458 | - if len(calls) > 0 { | |
| 459 | - list := make([]openaiCall, 0, len(calls)) | |
| 460 | - for _, c := range calls { | |
| 461 | - index := s.calls | |
| 462 | - s.calls++ | |
| 463 | - list = append(list, toOpenAI(c, s.ids.id(), &index)) | |
| 464 | - } | |
| 465 | - delta["tool_calls"], _ = json.Marshal(list) | |
| 466 | - } | |
| 467 | - if finished && s.calls > 0 { | |
| 468 | - choice["finish_reason"] = json.RawMessage(`"tool_calls"`) | |
| 469 | - } | |
| 470 | - choice["delta"], _ = json.Marshal(delta) | |
| 471 | - m["choices"], _ = json.Marshal(choices) | |
| 472 | - return json.Marshal(m) | |
| 473 | -} | |
| @@ -3,12 +3,9 @@ package engine | |||
| 3 | import ( | 3 | import ( |
| 4 | "bytes" | 4 | "bytes" |
| 5 | "encoding/json" | 5 | "encoding/json" |
| 6 | - "fmt" | ||
| 7 | "io" | 6 | "io" |
| 8 | "net/http" | 7 | "net/http" |
| 9 | - "regexp" | ||
| 10 | "strings" | 8 | "strings" |
| 11 | - "sync/atomic" | ||
| 12 | 9 | ||
| 13 | "github.com/openai/openai-go/option" | 10 | "github.com/openai/openai-go/option" |
| 14 | ) | 11 | ) |
| @@ -58,6 +55,12 @@ func xmlTools(req *http.Request, next option.MiddlewareNext) (*http.Response, er | |||
| 58 | if err != nil || resp == nil || resp.Body == nil || resp.StatusCode != http.StatusOK { | 55 | if err != nil || resp == nil || resp.Body == nil || resp.StatusCode != http.StatusOK { |
| 59 | return resp, err | 56 | return resp, err |
| 60 | } | 57 | } |
| 58 | + return xmlToolsReply(resp) | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +// xmlToolsReply turns the XML tool calls of a successful answer into OpenAI | ||
| 62 | +// ones: a stream as it is read (sseCalls), a whole body at once. | ||
| 63 | +func xmlToolsReply(resp *http.Response) (*http.Response, error) { | ||
| 61 | if strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { | 64 | if strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { |
| 62 | resp.Body = &sseCalls{rc: resp.Body, ids: newCallIDs()} | 65 | resp.Body = &sseCalls{rc: resp.Body, ids: newCallIDs()} |
| 63 | return resp, nil | 66 | return resp, nil |
| @@ -184,290 +187,3 @@ func callText(name, args string) string { | |||
| 184 | }{name, arguments}) | 187 | }{name, arguments}) |
| 185 | return "\n" + toolCallOpen + "\n" + string(call) + "\n" + toolCallClose | 188 | return "\n" + toolCallOpen + "\n" + string(call) + "\n" + toolCallClose |
| 186 | } | 189 | } |
| 187 | - | ||
| 188 | -// xmlCall is a tool call read from the text. | ||
| 189 | -type xmlCall struct { | ||
| 190 | - Name string | ||
| 191 | - Arguments string // JSON, or the broken text the model wrote | ||
| 192 | -} | ||
| 193 | - | ||
| 194 | -var callName = regexp.MustCompile(`"name"\s*:\s*"([^"]+)"`) | ||
| 195 | - | ||
| 196 | -// parseCall reads the inside of a <tool_call> block. A block that is not | ||
| 197 | -// JSON still makes a call when its name can be read — its arguments are the | ||
| 198 | -// broken text, which Genkit refuses and toolargs.go hands back to the model. | ||
| 199 | -func parseCall(inside string) (xmlCall, bool) { | ||
| 200 | - inside = strings.TrimSpace(inside) | ||
| 201 | - var v struct { | ||
| 202 | - Name string `json:"name"` | ||
| 203 | - Arguments json.RawMessage `json:"arguments"` | ||
| 204 | - } | ||
| 205 | - if json.Unmarshal([]byte(inside), &v) == nil && v.Name != "" { | ||
| 206 | - args := string(v.Arguments) | ||
| 207 | - var quoted string | ||
| 208 | - if json.Unmarshal(v.Arguments, "ed) == nil { | ||
| 209 | - args = quoted // arguments written as a JSON string | ||
| 210 | - } | ||
| 211 | - if strings.TrimSpace(args) == "" || args == "null" { | ||
| 212 | - args = "{}" | ||
| 213 | - } | ||
| 214 | - return xmlCall{Name: v.Name, Arguments: args}, true | ||
| 215 | - } | ||
| 216 | - m := callName.FindStringSubmatch(inside) | ||
| 217 | - if m == nil { | ||
| 218 | - return xmlCall{}, false | ||
| 219 | - } | ||
| 220 | - args := inside | ||
| 221 | - if _, after, found := strings.Cut(inside, `"arguments"`); found { | ||
| 222 | - args = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(after), ":")) | ||
| 223 | - } | ||
| 224 | - return xmlCall{Name: m[1], Arguments: args}, true | ||
| 225 | -} | ||
| 226 | - | ||
| 227 | -// callParser takes the answer's text piece by piece and separates the | ||
| 228 | -// <tool_call> blocks from the rest. It holds back what could be the start | ||
| 229 | -// of a block, so no "<tool_c" reaches the screen before it is known. | ||
| 230 | -type callParser struct { | ||
| 231 | - buf string | ||
| 232 | - inBlock bool | ||
| 233 | -} | ||
| 234 | - | ||
| 235 | -// feed takes the next piece of text; it returns the text to show and the | ||
| 236 | -// calls completed by this piece. | ||
| 237 | -func (p *callParser) feed(s string) (string, []xmlCall) { | ||
| 238 | - p.buf += s | ||
| 239 | - var out strings.Builder | ||
| 240 | - var calls []xmlCall | ||
| 241 | - for { | ||
| 242 | - if p.inBlock { | ||
| 243 | - end := strings.Index(p.buf, toolCallClose) | ||
| 244 | - if end < 0 { | ||
| 245 | - break | ||
| 246 | - } | ||
| 247 | - inside := p.buf[:end] | ||
| 248 | - p.buf, p.inBlock = p.buf[end+len(toolCallClose):], false | ||
| 249 | - if c, ok := parseCall(inside); ok { | ||
| 250 | - calls = append(calls, c) | ||
| 251 | - } else { | ||
| 252 | - out.WriteString(toolCallOpen + inside + toolCallClose) | ||
| 253 | - } | ||
| 254 | - continue | ||
| 255 | - } | ||
| 256 | - if start := strings.Index(p.buf, toolCallOpen); start >= 0 { | ||
| 257 | - out.WriteString(p.buf[:start]) | ||
| 258 | - p.buf, p.inBlock = p.buf[start+len(toolCallOpen):], true | ||
| 259 | - continue | ||
| 260 | - } | ||
| 261 | - hold := partialOpen(p.buf) | ||
| 262 | - out.WriteString(p.buf[:len(p.buf)-hold]) | ||
| 263 | - p.buf = p.buf[len(p.buf)-hold:] | ||
| 264 | - break | ||
| 265 | - } | ||
| 266 | - return out.String(), calls | ||
| 267 | -} | ||
| 268 | - | ||
| 269 | -// flush ends the answer: what was held back is shown, and a block cut by | ||
| 270 | -// the end (max_tokens) still makes a call when its name can be read. | ||
| 271 | -func (p *callParser) flush() (string, []xmlCall) { | ||
| 272 | - rest, inBlock := p.buf, p.inBlock | ||
| 273 | - p.buf, p.inBlock = "", false | ||
| 274 | - if !inBlock { | ||
| 275 | - return rest, nil | ||
| 276 | - } | ||
| 277 | - if c, ok := parseCall(rest); ok { | ||
| 278 | - return "", []xmlCall{c} | ||
| 279 | - } | ||
| 280 | - return toolCallOpen + rest, nil | ||
| 281 | -} | ||
| 282 | - | ||
| 283 | -// partialOpen is the length of the longest end of s that begins "<tool_call>". | ||
| 284 | -func partialOpen(s string) int { | ||
| 285 | - for n := min(len(toolCallOpen)-1, len(s)); n > 0; n-- { | ||
| 286 | - if strings.HasSuffix(s, toolCallOpen[:n]) { | ||
| 287 | - return n | ||
| 288 | - } | ||
| 289 | - } | ||
| 290 | - return 0 | ||
| 291 | -} | ||
| 292 | - | ||
| 293 | -// callIDs numbers the calls of one answer; the prefix keeps two answers' | ||
| 294 | -// ids apart in the history. | ||
| 295 | -type callIDs struct { | ||
| 296 | - prefix string | ||
| 297 | - next int | ||
| 298 | -} | ||
| 299 | - | ||
| 300 | -var answerCount atomic.Uint64 | ||
| 301 | - | ||
| 302 | -func newCallIDs() *callIDs { | ||
| 303 | - return &callIDs{prefix: fmt.Sprintf("call_xml%d", answerCount.Add(1))} | ||
| 304 | -} | ||
| 305 | - | ||
| 306 | -func (c *callIDs) id() string { | ||
| 307 | - c.next++ | ||
| 308 | - return fmt.Sprintf("%s_%d", c.prefix, c.next) | ||
| 309 | -} | ||
| 310 | - | ||
| 311 | -// openaiCall is a tool call in the OpenAI API's shape; Index is set in a | ||
| 312 | -// streamed delta only. | ||
| 313 | -type openaiCall struct { | ||
| 314 | - Index *int `json:"index,omitempty"` | ||
| 315 | - ID string `json:"id"` | ||
| 316 | - Type string `json:"type"` | ||
| 317 | - Function struct { | ||
| 318 | - Name string `json:"name"` | ||
| 319 | - Arguments string `json:"arguments"` | ||
| 320 | - } `json:"function"` | ||
| 321 | -} | ||
| 322 | - | ||
| 323 | -func toOpenAI(c xmlCall, id string, index *int) openaiCall { | ||
| 324 | - o := openaiCall{Index: index, ID: id, Type: "function"} | ||
| 325 | - o.Function.Name, o.Function.Arguments = c.Name, c.Arguments | ||
| 326 | - return o | ||
| 327 | -} | ||
| 328 | - | ||
| 329 | -// xmlToolsResponse rewrites a whole (not streamed) answer. | ||
| 330 | -func xmlToolsResponse(data []byte, ids *callIDs) []byte { | ||
| 331 | - var m map[string]json.RawMessage | ||
| 332 | - if json.Unmarshal(data, &m) != nil { | ||
| 333 | - return data | ||
| 334 | - } | ||
| 335 | - var choices []map[string]json.RawMessage | ||
| 336 | - if json.Unmarshal(m["choices"], &choices) != nil { | ||
| 337 | - return data | ||
| 338 | - } | ||
| 339 | - changed := false | ||
| 340 | - for _, choice := range choices { | ||
| 341 | - var msg map[string]json.RawMessage | ||
| 342 | - if json.Unmarshal(choice["message"], &msg) != nil { | ||
| 343 | - continue | ||
| 344 | - } | ||
| 345 | - var p callParser | ||
| 346 | - text, calls := p.feed(contentText(msg["content"])) | ||
| 347 | - rest, more := p.flush() | ||
| 348 | - text, calls = text+rest, append(calls, more...) | ||
| 349 | - if len(calls) == 0 { | ||
| 350 | - continue | ||
| 351 | - } | ||
| 352 | - list := make([]openaiCall, 0, len(calls)) | ||
| 353 | - for _, c := range calls { | ||
| 354 | - list = append(list, toOpenAI(c, ids.id(), nil)) | ||
| 355 | - } | ||
| 356 | - msg["content"], _ = json.Marshal(strings.TrimSpace(text)) | ||
| 357 | - msg["tool_calls"], _ = json.Marshal(list) | ||
| 358 | - choice["message"], _ = json.Marshal(msg) | ||
| 359 | - choice["finish_reason"] = json.RawMessage(`"tool_calls"`) | ||
| 360 | - changed = true | ||
| 361 | - } | ||
| 362 | - if !changed { | ||
| 363 | - return data | ||
| 364 | - } | ||
| 365 | - m["choices"], _ = json.Marshal(choices) | ||
| 366 | - out, err := json.Marshal(m) | ||
| 367 | - if err != nil { | ||
| 368 | - return data | ||
| 369 | - } | ||
| 370 | - return out | ||
| 371 | -} | ||
| 372 | - | ||
| 373 | -// sseCalls rewrites a streamed answer line by line: the content of the | ||
| 374 | -// first choice goes through a callParser, and each completed block is sent | ||
| 375 | -// as a tool_calls delta in the chunk that completed it. | ||
| 376 | -type sseCalls struct { | ||
| 377 | - rc io.ReadCloser | ||
| 378 | - ids *callIDs | ||
| 379 | - parser callParser | ||
| 380 | - calls int // calls sent so far: the next delta index | ||
| 381 | - in []byte | ||
| 382 | - out bytes.Buffer | ||
| 383 | - eof bool | ||
| 384 | - err error | ||
| 385 | -} | ||
| 386 | - | ||
| 387 | -func (s *sseCalls) Close() error { return s.rc.Close() } | ||
| 388 | - | ||
| 389 | -func (s *sseCalls) Read(p []byte) (int, error) { | ||
| 390 | - for s.out.Len() == 0 && !s.eof { | ||
| 391 | - chunk := make([]byte, 4096) | ||
| 392 | - n, err := s.rc.Read(chunk) | ||
| 393 | - s.in = append(s.in, chunk[:n]...) | ||
| 394 | - for { | ||
| 395 | - i := bytes.IndexByte(s.in, '\n') | ||
| 396 | - if i < 0 { | ||
| 397 | - break | ||
| 398 | - } | ||
| 399 | - s.line(string(s.in[:i])) | ||
| 400 | - s.in = s.in[i+1:] | ||
| 401 | - } | ||
| 402 | - if err != nil { | ||
| 403 | - if len(s.in) > 0 { | ||
| 404 | - s.line(string(s.in)) | ||
| 405 | - s.in = nil | ||
| 406 | - } | ||
| 407 | - s.eof, s.err = true, err | ||
| 408 | - } | ||
| 409 | - } | ||
| 410 | - if s.out.Len() > 0 { | ||
| 411 | - return s.out.Read(p) | ||
| 412 | - } | ||
| 413 | - return 0, s.err | ||
| 414 | -} | ||
| 415 | - | ||
| 416 | -// line rewrites one SSE line; anything but a data chunk goes through. | ||
| 417 | -func (s *sseCalls) line(line string) { | ||
| 418 | - data, ok := strings.CutPrefix(strings.TrimRight(line, "\r"), "data:") | ||
| 419 | - data = strings.TrimSpace(data) | ||
| 420 | - if !ok || data == "" || data == "[DONE]" { | ||
| 421 | - s.out.WriteString(line + "\n") | ||
| 422 | - return | ||
| 423 | - } | ||
| 424 | - rewritten, err := s.chunk([]byte(data)) | ||
| 425 | - if err != nil { | ||
| 426 | - s.out.WriteString(line + "\n") | ||
| 427 | - return | ||
| 428 | - } | ||
| 429 | - s.out.WriteString("data: " + string(rewritten) + "\n") | ||
| 430 | -} | ||
| 431 | - | ||
| 432 | -// chunk rewrites one streamed chunk's first choice. | ||
| 433 | -func (s *sseCalls) chunk(data []byte) ([]byte, error) { | ||
| 434 | - var m map[string]json.RawMessage | ||
| 435 | - if err := json.Unmarshal(data, &m); err != nil { | ||
| 436 | - return nil, err | ||
| 437 | - } | ||
| 438 | - var choices []map[string]json.RawMessage | ||
| 439 | - if err := json.Unmarshal(m["choices"], &choices); err != nil || len(choices) == 0 { | ||
| 440 | - return data, nil | ||
| 441 | - } | ||
| 442 | - choice := choices[0] | ||
| 443 | - delta := map[string]json.RawMessage{} | ||
| 444 | - if raw, ok := choice["delta"]; ok { | ||
| 445 | - if err := json.Unmarshal(raw, &delta); err != nil { | ||
| 446 | - return nil, err | ||
| 447 | - } | ||
| 448 | - } | ||
| 449 | - text, calls := s.parser.feed(contentText(delta["content"])) | ||
| 450 | - finished := len(choice["finish_reason"]) > 0 && string(choice["finish_reason"]) != "null" | ||
| 451 | - if finished { | ||
| 452 | - rest, more := s.parser.flush() | ||
| 453 | - text, calls = text+rest, append(calls, more...) | ||
| 454 | - } | ||
| 455 | - if _, had := delta["content"]; had || text != "" { | ||
| 456 | - delta["content"], _ = json.Marshal(text) | ||
| 457 | - } | ||
| 458 | - if len(calls) > 0 { | ||
| 459 | - list := make([]openaiCall, 0, len(calls)) | ||
| 460 | - for _, c := range calls { | ||
| 461 | - index := s.calls | ||
| 462 | - s.calls++ | ||
| 463 | - list = append(list, toOpenAI(c, s.ids.id(), &index)) | ||
| 464 | - } | ||
| 465 | - delta["tool_calls"], _ = json.Marshal(list) | ||
| 466 | - } | ||
| 467 | - if finished && s.calls > 0 { | ||
| 468 | - choice["finish_reason"] = json.RawMessage(`"tool_calls"`) | ||
| 469 | - } | ||
| 470 | - choice["delta"], _ = json.Marshal(delta) | ||
| 471 | - m["choices"], _ = json.Marshal(choices) | ||
| 472 | - return json.Marshal(m) | ||
| 473 | -} | ||