diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index 1c51f4167..b7c86efa7 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -559,7 +559,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov return writeError(w, from, 502, failed), failed } } else { - dec := decoderFor(p, actual) + dec := carryReasoning(decoderFor(p, actual), from, actual) attemptSee := see if names := textCallNames(request.Tools); names != nil { t := &textCallSee{names: names, see: see} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2350c8de5..7b1fb68ec 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -7325,6 +7325,8 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr // a glm-5.3-flash* replica's CR stitched into a call's arguments // (tool_args_cr.go, #4256) request.CR = glmServed(wiresOf(r.Context()), p, model) + // Grok's reasoning, carried in its calls' ids (reasoning_carry.go) + askSealedReasoning(p, from, request) // a model's 2500.0 in a call's arguments, which Codex turns away, is // rewritten at the encoder and at render (grok_integral.go, #1431, // #3152) @@ -7380,7 +7382,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr } return writeVendorError(w, from, res.StatusCode, msg, b), msg } - dec := decoderFor(p, actual) + dec := carryReasoning(decoderFor(p, actual), from, actual) rd, sse := eventStream(res) if !sse { // the provider ignored stream:true; read the whole reply as one @@ -7607,6 +7609,9 @@ func parseRequest(proto provider.Protocol, body []byte, facts, keepInstructions func afterParse(proto provider.Protocol, body []byte, req *Request) (*Request, error) { // a call's id may carry Gemini's thought signature (gemini_signature.go) unsignCalls(req) + // and the sealed reasoning a Responses upstream gave before it + // (reasoning_carry.go) + unreasonCalls(req) req.LastIsTurn = proto == provider.Chat || proto == provider.Responses if req.ToolChoice == "required" && len(req.Tools) == 0 && !req.WebSearch && requiredAllowlist(proto, body) { return nil, fmt.Errorf("required tool choice has no callable tools after filtering") diff --git a/internal/gateway/reasoning_carry.go b/internal/gateway/reasoning_carry.go new file mode 100644 index 000000000..e7543f8ba --- /dev/null +++ b/internal/gateway/reasoning_carry.go @@ -0,0 +1,155 @@ +package gateway + +import ( + "encoding/json" + "slices" + "strconv" + + "github.com/yetone/magpie/internal/provider" +) + +// A Responses upstream's sealed reasoning across a client of another API +// (jenryai on X: Grok through Claude Desktop repeats itself and writes +// broken calls, where Grok Build doesn't). A model that reasons between +// tool calls reads the step's reasoning back on the next request: Grok +// Build sends every reasoning item it was given, encrypted_content and +// all, before the calls it led to. A Messages, Chat or Gemini client +// keeps no such item, so each step of its tool loop reached Grok with +// none of the reasoning that made the calls before it. +// +// So the reasoning items that come before a step's first call ride in +// that call's id, as Gemini's signatures do (gemini_signature.go): they +// are kept in magpie's folder (keepSignature, by their hash) and the id +// carries the key, __rk16__. Every client sends a call's id back +// as it was given, and on the way back the items go in front of the +// assistant turn that made the call, and the id is the call's own again. +// A key magpie no longer has (or an id a client shortened) is no +// reasoning: the step goes as before. + +const ( + reasonMark = "__rk" + reasonEnd = "__" +) + +// reasonKeyLen is a kept item's key's length in an id. +var reasonKeyLen = len(sigKey("")) + +// reasonTail is what an id carrying reasoning ends with before its key. +var reasonTail = reasonMark + strconv.Itoa(reasonKeyLen) + reasonEnd + +// asksSealedReasoning says whether a request from a client of from is +// made to ask p for its sealed reasoning, to carry it in the calls' ids: +// a Grok subscription's plugin, asked as Grok Build asks it. A Responses +// client asks for itself, and keeps the items it is given. +func asksSealedReasoning(p provider.Provider, from provider.Protocol) bool { + return from != provider.Responses && p.PluginProvider() == "grok" +} + +// askSealedReasoning adds reasoning.encrypted_content to r's include when +// asksSealedReasoning says so (buildResponses sends it only with reasoning). +func askSealedReasoning(p provider.Provider, from provider.Protocol, r *Request) { + const v = "reasoning.encrypted_content" + if asksSealedReasoning(p, from) && !slices.Contains(r.Include, v) { + r.Include = append(slices.Clip(r.Include), v) + } +} + +// reasonedID is a call's id carrying the reasoning items before it, or the +// id as it was when they couldn't be kept. +func reasonedID(id string, items []json.RawMessage) string { + if len(items) == 0 { + return id + } + b, err := json.Marshal(items) + if err != nil { + return id + } + key := keepSignature(string(b)) + if key == "" { + return id + } + if id == "" { + id = "call_" + newID() + } + return id + reasonTail + key +} + +// unreasonedID splits an id reasonedID made into the call's own id and +// the reasoning items it refers to (none when magpie no longer has them). +// Any other id comes back as it is. +func unreasonedID(id string) (string, []json.RawMessage) { + at := len(id) - reasonKeyLen - len(reasonTail) + if at < 1 || id[at:at+len(reasonTail)] != reasonTail { + return id, nil + } + own, key := id[:at], id[at+len(reasonTail):] + var items []json.RawMessage + if kept := keptSignature(key); kept != "" { + if json.Unmarshal([]byte(kept), &items) != nil { + items = nil + } + } + return own, items +} + +// carryReasoning is dec for a client of from, with the sealed reasoning a +// Responses upstream gives before a call carried in that call's id, when +// the client is of another API. +func carryReasoning(dec func(string, func(Event)) error, from, actual provider.Protocol) func(string, func(Event)) error { + if from == provider.Responses || actual != provider.Responses { + return dec + } + var held []json.RawMessage + return func(data string, emit func(Event)) error { + return dec(data, func(ev Event) { + switch { + case ev.Kind == KSealed && ev.Name == sealResponses && ev.Text != "": + held = append(held, json.RawMessage(ev.Text)) + case ev.Kind == KToolStart && len(held) > 0: + ev.ID = reasonedID(ev.ID, held) + held = nil + } + emit(ev) + }) + } +} + +// unreasonCalls takes the reasoning off a parsed request's call ids: each +// assistant turn leads with the items its calls carried, sealed as the +// Responses upstream gave them (buildResponses sends them back; another +// API's build leaves them out), and a call and its result have the call's +// own id. Messages are copied before they change. +func unreasonCalls(r *Request) { + for i, m := range r.Messages { + var parts, lead []Part + for j, p := range m.Parts { + var items []json.RawMessage + switch p.Kind { + case ToolCall: + id, its := unreasonedID(p.ID) + if id == p.ID { + continue + } + p.ID, items = id, its + case ToolResult: + id, _ := unreasonedID(p.CallID) + if id == p.CallID { + continue + } + p.CallID = id + default: + continue + } + if parts == nil { + parts = slices.Clone(m.Parts) + } + parts[j] = p + for _, it := range items { + lead = append(lead, Part{Kind: Thinking, Sealed: it, SealedBy: sealResponses}) + } + } + if parts != nil { + r.Messages[i].Parts = append(lead, parts...) + } + } +} diff --git a/internal/gateway/reasoning_carry_test.go b/internal/gateway/reasoning_carry_test.go new file mode 100644 index 000000000..610fde163 --- /dev/null +++ b/internal/gateway/reasoning_carry_test.go @@ -0,0 +1,297 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// grokReasonedCall is a real Grok reply (Grok Build 1.0.67's session title +// request, grok-4.6-build): a sealed reasoning item, a message, and a +// function call that ends before the message does. +const grokReasonedCallFile = "testdata/grok_reasoning_then_call.sse" + +const grokReasonedCallID = "call-b35b8754-d11f-46c5-9c64-fed82640a7f7-0" + +// grokReasoningItem is the sealed reasoning item of grokReasonedCallFile, +// as its output_item.done gives it. +func grokReasoningItem(t *testing.T, stream []byte) map[string]any { + t.Helper() + for _, ev := range sseData(t, stream) { + if ev["type"] != "response.output_item.done" { + continue + } + if it := ev["item"].(map[string]any); it["type"] == "reasoning" { + if it["encrypted_content"] == "" || it["encrypted_content"] == nil { + t.Fatal("the fixture's reasoning isn't sealed") + } + return it + } + } + t.Fatal("no reasoning item in the fixture") + return nil +} + +// grokCallUp answers a request with no tool output with the real Grok +// reply, and one with an output with a line of text, keeping each body. +type grokCallUp struct { + mu sync.Mutex + sent []map[string]any + reply []byte +} + +func (u *grokCallUp) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + u.mu.Lock() + u.sent = append(u.sent, q) + u.mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + if !bytes.Contains(b, []byte(`"function_call_output"`)) { + w.Write(u.reply) + return + } + done := `{"id":"r2","object":"response","status":"completed","output":[{"type":"message","id":"m2","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Titled.","annotations":[]}]}],"usage":{"input_tokens":5,"output_tokens":1}}` + io.WriteString(w, sse( + `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r2","object":"response","status":"in_progress","output":[]}}`, + `event: response.output_item.added`+"\n"+`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"m2","role":"assistant","status":"in_progress","content":[]}}`, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","item_id":"m2","output_index":0,"content_index":0,"delta":"Titled."}`, + `event: response.output_item.done`+"\n"+`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m2","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Titled.","annotations":[]}]}}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`)) +} + +// askedCallID is the id of the one call a client of from was given in +// body, streamed or whole. +func askedCallID(t *testing.T, from provider.Protocol, body []byte, stream bool) string { + t.Helper() + var ids []string + switch { + case from == provider.Anthropic && stream: + for _, ev := range sseData(t, body) { + if cb, ok := ev["content_block"].(map[string]any); ok && cb["type"] == "tool_use" { + ids = append(ids, cb["id"].(string)) + } + } + case from == provider.Anthropic: + var m struct { + Content []struct{ Type, ID string } + } + json.Unmarshal(body, &m) + for _, c := range m.Content { + if c.Type == "tool_use" { + ids = append(ids, c.ID) + } + } + case stream: + for _, ev := range sseData(t, body) { + for _, c := range ev["choices"].([]any) { + d, _ := c.(map[string]any)["delta"].(map[string]any) + tcs, _ := d["tool_calls"].([]any) + for _, tc := range tcs { + if id, _ := tc.(map[string]any)["id"].(string); id != "" { + ids = append(ids, id) + } + } + } + } + default: + var m struct { + Choices []struct { + Message struct { + ToolCalls []struct{ ID string } `json:"tool_calls"` + } + } + } + json.Unmarshal(body, &m) + for _, c := range m.Choices { + for _, tc := range c.Message.ToolCalls { + ids = append(ids, tc.ID) + } + } + } + if len(ids) != 1 { + t.Fatalf("%s client was given calls %v: %s", from, ids, body) + } + return ids[0] +} + +// grokAsk is a request of from's API as Claude Desktop (Messages, thinking +// on) or a Chat client (reasoning_effort) sends one to a Grok model, with +// the call it was given answered when id isn't "". +func grokAsk(from provider.Protocol, model, id string, stream bool) string { + s := "false" + if stream { + s = "true" + } + tool := `{"name":"session_title","description":"Generate the session_title","input_schema":{"type":"object","properties":{"session_title":{"type":"string"}},"required":["session_title"]}}` + if from == provider.Anthropic { + msgs := `{"role":"user","content":"Sum a.txt and b.txt into c.txt"}` + if id != "" { + msgs += `,{"role":"assistant","content":[{"type":"text","text":"I'll create a short, descriptive session title from that request."},{"type":"tool_use","id":"` + id + `","name":"session_title","input":{"session_title":"Sum a.txt and b.txt numbers into c.txt"}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":"ok"}]}` + } + return `{"model":"` + model + `","max_tokens":32000,"stream":` + s + `,"thinking":{"type":"adaptive"},"output_config":{"effort":"high"},"tools":[` + tool + `],"messages":[` + msgs + `]}` + } + msgs := `{"role":"user","content":"Sum a.txt and b.txt into c.txt"}` + if id != "" { + msgs += `,{"role":"assistant","content":"I'll create a short, descriptive session title from that request.","tool_calls":[{"id":"` + id + `","type":"function","function":{"name":"session_title","arguments":"{\"session_title\":\"Sum a.txt and b.txt numbers into c.txt\"}"}}]},` + + `{"role":"tool","tool_call_id":"` + id + `","content":"ok"}` + } + return `{"model":"` + model + `","stream":` + s + `,"reasoning_effort":"high","tools":[{"type":"function","function":{"name":"session_title","description":"Generate the session_title","parameters":{"type":"object","properties":{"session_title":{"type":"string"}},"required":["session_title"]}}}],"messages":[` + msgs + `]}` +} + +// Grok through Claude Desktop, or a Chat client, gets its reasoning back +// on each step of a tool loop, as Grok Build sends it (jenryai on X): the +// first request asks for it sealed, the call the client is given carries +// it, and the next request has the reasoning item, as Grok wrote it, +// before the call, under the call's own id. Streamed or whole. +func TestGrokReasoningGoesBackThroughOtherAPIs(t *testing.T) { + reply, err := os.ReadFile(grokReasonedCallFile) + if err != nil { + t.Fatal(err) + } + item := grokReasoningItem(t, reply) + up := &grokCallUp{reply: reply} + pid := besideFake(t, "grok", up) + paths := map[provider.Protocol]string{provider.Anthropic: "/v1/messages", provider.Chat: "/v1/chat/completions"} + for _, from := range []provider.Protocol{provider.Anthropic, provider.Chat} { + for _, stream := range []bool{true, false} { + up.mu.Lock() + up.sent = nil + up.mu.Unlock() + ask := func(id string) []byte { + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", paths[from], strings.NewReader(grokAsk(from, pid+"/fake-resp", id, stream)))) + if rec.Code != 200 { + t.Fatalf("%s stream=%v: %d %s", from, stream, rec.Code, rec.Body) + } + return rec.Body.Bytes() + } + id := askedCallID(t, from, ask(""), stream) + if own, items := unreasonedID(id); own != grokReasonedCallID || len(items) != 1 { + t.Fatalf("%s stream=%v: the call's id %q carries %d items for %q", from, stream, id, len(items), own) + } + ask(id) + up.mu.Lock() + sent := up.sent + up.mu.Unlock() + if len(sent) != 2 { + t.Fatalf("%s stream=%v: Grok was asked %d times", from, stream, len(sent)) + } + inc, _ := json.Marshal(sent[0]["include"]) + if !strings.Contains(string(inc), `"reasoning.encrypted_content"`) { + t.Fatalf("%s stream=%v: Grok wasn't asked for its sealed reasoning: include %s", from, stream, inc) + } + var kinds []string + var got map[string]any + for _, it := range sent[1]["input"].([]any) { + m := it.(map[string]any) + k, _ := m["type"].(string) + if k == "" { + k = "message" + } + if k == "message" { + k += ":" + m["role"].(string) + } + if c, _ := m["call_id"].(string); c != "" { + if c != grokReasonedCallID { + t.Fatalf("%s stream=%v: %s went to Grok as %q", from, stream, k, c) + } + } + if k == "reasoning" { + got = m + } + kinds = append(kinds, k) + } + if want := "message:user,reasoning,message:assistant,function_call,function_call_output"; strings.Join(kinds, ",") != want { + t.Fatalf("%s stream=%v: Grok was given %v, want %s", from, stream, kinds, want) + } + if got["encrypted_content"] != item["encrypted_content"] || got["id"] != item["id"] { + t.Fatalf("%s stream=%v: the reasoning went back as %v", from, stream, got) + } + } + } +} + +// Only Grok's plugin is asked for sealed reasoning by a client of another +// API, and a Responses client keeps its own include and its calls' ids. +func TestSealedReasoningAskedOfGrokAlone(t *testing.T) { + grok := provider.PluginForTest("grok", "grok") + other := provider.PluginForTest("kiro", "kiro") + for _, c := range []struct { + p provider.Provider + from provider.Protocol + want bool + }{ + {grok, provider.Anthropic, true}, + {grok, provider.Chat, true}, + {grok, provider.Gemini, true}, + {grok, provider.Responses, false}, + {other, provider.Anthropic, false}, + {provider.Provider{ID: "openai"}, provider.Anthropic, false}, + } { + r := &Request{} + askSealedReasoning(c.p, c.from, r) + if got := len(r.Include) == 1; got != c.want { + t.Errorf("%s from %s: include %v", c.p.ID, c.from, r.Include) + } + } + reply, err := os.ReadFile(grokReasonedCallFile) + if err != nil { + t.Fatal(err) + } + var ids []string + dec := carryReasoning(decoder(provider.Responses), provider.Responses, provider.Responses) + for _, l := range strings.Split(string(reply), "\n") { + if d, ok := strings.CutPrefix(l, "data: "); ok { + dec(d, func(ev Event) { + if ev.Kind == KToolStart { + ids = append(ids, ev.ID) + } + }) + } + } + if len(ids) != 1 || ids[0] != grokReasonedCallID { + t.Fatalf("a Responses client was given %v", ids) + } +} + +// An id whose kept reasoning magpie no longer has goes back as the call's +// own, with no reasoning; one a client cut short, or any other id, goes as +// it came. +func TestReasonedIDWithoutItsReasoning(t *testing.T) { + fresh(t) + id := reasonedID("call_1", []json.RawMessage{json.RawMessage(`{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"e"}`)}) + if own, items := unreasonedID(id); own != "call_1" || len(items) != 1 { + t.Fatalf("%q: %q %v", id, own, items) + } + if own, items := unreasonedID(id[:len(id)-1]); own != id[:len(id)-1] || items != nil { + t.Fatalf("cut short: %q %v", own, items) + } + os.RemoveAll(sigDir()) + if own, items := unreasonedID(id); own != "call_1" || items != nil { + t.Fatalf("forgotten: %q %v", own, items) + } + for _, plain := range []string{"toolu_01", grokReasonedCallID, "call__rk16__"} { + if own, items := unreasonedID(plain); own != plain || items != nil { + t.Fatalf("%q came back %q %v", plain, own, items) + } + } + r := &Request{Messages: []Message{ + {Role: "assistant", Parts: []Part{{Kind: Text, Text: "hi"}, {Kind: ToolCall, ID: id, Name: "f"}}}, + {Role: "user", Parts: []Part{{Kind: ToolResult, CallID: id, Text: "ok"}}}, + }} + unreasonCalls(r) + if p := r.Messages[0].Parts; len(p) != 2 || p[1].ID != "call_1" || r.Messages[1].Parts[0].CallID != "call_1" { + t.Fatalf("forgotten reasoning: %+v", r.Messages) + } +} diff --git a/internal/gateway/testdata/grok_reasoning_then_call.sse b/internal/gateway/testdata/grok_reasoning_then_call.sse new file mode 100644 index 000000000..f7491a3ee --- /dev/null +++ b/internal/gateway/testdata/grok_reasoning_then_call.sse @@ -0,0 +1,123 @@ +event: response.created +data: {"sequence_number":0,"type":"response.created","response":{"created_at":1793540079,"completed_at":null,"id":"9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","max_output_tokens":100,"model":"grok-4.6-build","object":"response","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":"concise"},"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":{"type":"function","name":"session_title"},"tools":[{"type":"function","description":"Generate the session_title which we use for the user_message","name":"session_title","parameters":{"type":"object","required":["session_title"],"properties":{"session_title":{"type":"string","description":"Final session title, just 5-10 word descriptive title for the session. Super info dense, no filler."}},"additionalProperties":false},"strict":null}],"top_p":0.95,"usage":null,"user":null,"incomplete_details":null,"status":"in_progress","store":false,"metadata":{"system_fingerprint":"fp_21c045be27"},"background":false,"service_tier":"default","truncation":"disabled","top_logprobs":0,"presence_penalty":0.0,"frequency_penalty":0.0,"prompt_cache_key":null,"max_tool_calls":null,"safety_identifier":null,"error":null,"instructions":null}} + +event: response.in_progress +data: {"sequence_number":1,"type":"response.in_progress","response":{"created_at":1793540079,"completed_at":null,"id":"9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","max_output_tokens":100,"model":"grok-4.6-build","object":"response","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":"concise"},"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":{"type":"function","name":"session_title"},"tools":[{"type":"function","description":"Generate the session_title which we use for the user_message","name":"session_title","parameters":{"type":"object","required":["session_title"],"properties":{"session_title":{"type":"string","description":"Final session title, just 5-10 word descriptive title for the session. Super info dense, no filler."}},"additionalProperties":false},"strict":null}],"top_p":0.95,"usage":null,"user":null,"incomplete_details":null,"status":"in_progress","store":false,"metadata":{"system_fingerprint":"fp_21c045be27"},"background":false,"service_tier":"default","truncation":"disabled","top_logprobs":0,"presence_penalty":0.0,"frequency_penalty":0.0,"prompt_cache_key":null,"max_tool_calls":null,"safety_identifier":null,"error":null,"instructions":null}} + +event: response.output_item.added +data: {"sequence_number":2,"type":"response.output_item.added","item":{"id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","summary":[],"type":"reasoning","status":"in_progress"},"output_index":0} + +event: response.reasoning_summary_part.added +data: {"sequence_number":3,"type":"response.reasoning_summary_part.added","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"part":{"text":"","type":"summary_text"},"summary_index":0} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":4,"type":"response.reasoning_summary_text.delta","delta":"I will read a.txt and","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +: xai-usage {"input_tokens":472,"input_tokens_details":{"cached_tokens":384},"output_tokens":75,"output_tokens_details":{"reasoning_tokens":75},"total_tokens":0,"num_sources_used":0,"num_server_side_tools_used":0,"cost_in_usd_ticks":8180000,"context_details":{"input_tokens":472,"output_tokens":75}} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":5,"type":"response.reasoning_summary_text.delta","delta":" b.txt, sum all numbers,","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":6,"type":"response.reasoning_summary_text.delta","delta":" write the result to","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":7,"type":"response.reasoning_summary_text.delta","delta":" c.txt, and report the","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":8,"type":"response.reasoning_summary_text.delta","delta":" total.","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":9,"type":"response.reasoning_summary_text.delta","delta":"\n\nI am generating a ","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +: xai-usage {"input_tokens":472,"input_tokens_details":{"cached_tokens":384},"output_tokens":190,"output_tokens_details":{"reasoning_tokens":190},"total_tokens":0,"num_sources_used":0,"num_server_side_tools_used":0,"cost_in_usd_ticks":15080000,"context_details":{"input_tokens":472,"output_tokens":190}} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":10,"type":"response.reasoning_summary_text.delta","delta":"session title for this","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":11,"type":"response.reasoning_summary_text.delta","delta":" task.","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":12,"type":"response.reasoning_summary_text.delta","delta":"\n\nI will generate a ","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +: xai-usage {"input_tokens":472,"input_tokens_details":{"cached_tokens":384},"output_tokens":338,"output_tokens_details":{"reasoning_tokens":338},"total_tokens":0,"num_sources_used":0,"num_server_side_tools_used":0,"cost_in_usd_ticks":23960000,"context_details":{"input_tokens":472,"output_tokens":338}} + +event: response.reasoning_summary_text.delta +data: {"sequence_number":13,"type":"response.reasoning_summary_text.delta","delta":"session title using the `session_title` tool. I do not need to read or write files.","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0} + +event: response.reasoning_summary_text.done +data: {"sequence_number":14,"type":"response.reasoning_summary_text.done","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"summary_index":0,"text":"I will read a.txt and b.txt, sum all numbers, write the result to c.txt, and report the total.\n\nI am generating a session title for this task.\n\nI will generate a session title using the `session_title` tool. I do not need to read or write files."} + +event: response.reasoning_summary_part.done +data: {"sequence_number":15,"type":"response.reasoning_summary_part.done","item_id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":0,"part":{"text":"I will read a.txt and b.txt, sum all numbers, write the result to c.txt, and report the total.\n\nI am generating a session title for this task.\n\nI will generate a session title using the `session_title` tool. I do not need to read or write files.","type":"summary_text"},"summary_index":0} + +event: response.output_item.done +data: {"sequence_number":16,"type":"response.output_item.done","item":{"id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","summary":[{"text":"I will read a.txt and b.txt, sum all numbers, write the result to c.txt, and report the total.\n\nI am generating a session title for this task.\n\nI will generate a session title using the `session_title` tool. I do not need to read or write files.","type":"summary_text"}],"type":"reasoning","status":"completed","encrypted_content":"IeheMCJfUzv1OoYVvraxUKikvuQ2TmTBkNZRf2NVuthBc1Fg3fV5Wn5XcO6YLDE2lutAkET/XbWRuOlL7BHThdo26qqk7FY6LdTDKQJ284n0iSEfFYOtxFrGs0uW57hYvKLckNAEjoHFflXGjWd6nlJr246LfTpdFEFl/GWPEJBm4PahKbwLNxpQaNZOt2tWDq3RbFjGabxHKKJvSsXxPNbycRgKLKjzF+kOjF6ynbIWlMcDkOm92lurmd8sglev7rX2EixWYaV+WLW6w2HM4x5yCzBg+WQrAkXk3BQIlm8rJpaX8fwyhvwZTKaW4VsblyDRtEYWxITtqJnEFXA+dxtzCNMEUlFpIl2n6jLSVRoxrBnissYxJzVxRSiFBl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skw/PAomcWQX+Wa3SK+BstWp0vG2dvRI+1UOZUaf5hdKCXJNKCHO6ETRCRPaTVweJP3CQb0D2LePrxAupYSuMdARfHnJaf9WTufBAa9HV4I/bgZtX7piG+Tb47kxRG5No2+JZLZlRLnjyDIm2+BuJMpSR+xXAVM8GjBQM8WqNhRTAVGosAFIpTctg4+TbZfttygJNjDL1tP5fKOKkCte51vsWEmaW6p7i0RuQ7yqKy/4rG80yvDStZ87Ed/DaBHALNdmzPtU5e93r3LV3XAujSSsrvi1FMmwJQmOpMOAHUPWeZL3hecd0e/uJhmmJKfyHqt3MDT7/w66rHudK0a/Yq4+JjP9OhT/XZ9Ry6ih/2+OI4onMuySjflcgg2wGTtOsq7Ng6Zb7bPPZ8f77W6j2QnnO9Yi+CalF9/PP3jSrNQxl8wpRhxXmZ3XDqvUitLcOVzGPMHiuaseZX4lCu51umueTcHSDmf9YpX0hx7iJhBehebhe/gbfytSX8qYb0g2gKoqTC8pJgvHnkqvUKr3mwzUk"},"output_index":0} + +event: response.output_item.added +data: {"sequence_number":17,"type":"response.output_item.added","item":{"content":[],"id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","role":"assistant","type":"message","status":"in_progress"},"output_index":1} + +event: response.content_part.added +data: {"sequence_number":18,"type":"response.content_part.added","content_index":0,"item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"part":{"type":"output_text","text":"","logprobs":[],"annotations":[]}} + +event: response.output_text.delta +data: {"sequence_number":19,"type":"response.output_text.delta","content_index":0,"delta":"I'll","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":20,"type":"response.output_text.delta","content_index":0,"delta":" create","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":21,"type":"response.output_text.delta","content_index":0,"delta":" a","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":22,"type":"response.output_text.delta","content_index":0,"delta":" short","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":23,"type":"response.output_text.delta","content_index":0,"delta":",","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":24,"type":"response.output_text.delta","content_index":0,"delta":" descriptive","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":25,"type":"response.output_text.delta","content_index":0,"delta":" session","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":26,"type":"response.output_text.delta","content_index":0,"delta":" title","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":27,"type":"response.output_text.delta","content_index":0,"delta":" from","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":28,"type":"response.output_text.delta","content_index":0,"delta":" that","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":29,"type":"response.output_text.delta","content_index":0,"delta":" request","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_text.delta +data: {"sequence_number":30,"type":"response.output_text.delta","content_index":0,"delta":".","item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"logprobs":[]} + +event: response.output_item.added +data: {"sequence_number":31,"type":"response.output_item.added","item":{"arguments":"","call_id":"call-b35b8754-d11f-46c5-9c64-fed82640a7f7-0","name":"session_title","type":"function_call","id":"fc_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874_0","status":"in_progress"},"output_index":2} + +event: response.function_call_arguments.delta +data: {"sequence_number":32,"type":"response.function_call_arguments.delta","delta":"{\"session_title\":\"Sum a.txt and b.txt numbers into c.txt\"}","item_id":"fc_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874_0","output_index":2} + +event: response.function_call_arguments.done +data: {"sequence_number":33,"type":"response.function_call_arguments.done","arguments":"{\"session_title\":\"Sum a.txt and b.txt numbers into c.txt\"}","item_id":"fc_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874_0","name":"session_title","output_index":2} + +event: response.output_item.done +data: {"sequence_number":34,"type":"response.output_item.done","item":{"arguments":"{\"session_title\":\"Sum a.txt and b.txt numbers into c.txt\"}","call_id":"call-b35b8754-d11f-46c5-9c64-fed82640a7f7-0","name":"session_title","type":"function_call","id":"fc_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874_0","status":"completed"},"output_index":2} + +event: response.output_text.done +data: {"sequence_number":35,"type":"response.output_text.done","content_index":0,"item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"text":"I'll create a short, descriptive session title from that request.","logprobs":[]} + +event: response.content_part.done +data: {"sequence_number":36,"type":"response.content_part.done","content_index":0,"item_id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","output_index":1,"part":{"type":"output_text","text":"I'll create a short, descriptive session title from that request.","logprobs":[],"annotations":[]}} + +event: response.output_item.done +data: {"sequence_number":37,"type":"response.output_item.done","item":{"content":[{"type":"output_text","text":"I'll create a short, descriptive session title from that request.","logprobs":[],"annotations":[]}],"id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","role":"assistant","type":"message","status":"completed"},"output_index":1} + +event: response.completed +data: {"sequence_number":38,"type":"response.completed","response":{"created_at":1793540079,"completed_at":1793540083,"id":"9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","max_output_tokens":100,"model":"grok-4.6-build","object":"response","output":[{"id":"rs_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","summary":[{"text":"I will read a.txt and b.txt, sum all numbers, write the result to c.txt, and report the total.\n\nI am generating a session title for this task.\n\nI will generate a session title using the `session_title` tool. I do not need to read or write files.","type":"summary_text"}],"type":"reasoning","status":"completed","encrypted_content":"IeheMCJfUzv1OoYVvraxUKikvuQ2TmTBkNZRf2NVuthBc1Fg3fV5Wn5XcO6YLDE2lutAkET/XbWRuOlL7BHThdo26qqk7FY6LdTDKQJ284n0iSEfFYOtxFrGs0uW57hYvKLckNAEjoHFflXGjWd6nlJr246LfTpdFEFl/GWPEJBm4PahKbwLNxpQaNZOt2tWDq3RbFjGabxHKKJvSsXxPNbycRgKLKjzF+kOjF6ynbIWlMcDkOm92lurmd8sglev7rX2EixWYaV+WLW6w2HM4x5yCzBg+WQrAkXk3BQIlm8rJpaX8fwyhvwZTKaW4VsblyDRtEYWxITtqJnEFXA+dxtzCNMEUlFpIl2n6jLSVRoxrBnissYxJzVxRSiFBlFWV7ws+zvuO+zeLf9koMjaGGJ/kO+dXO+cJq1S2tJwJu5uQMvztCsGg70B6+xvsN+vQLORfDPRxc+9IvNplIbqLRDzUWSrB7KW2ZlK7R8vfxucKtTE6moyg2XObRw5nV5M9H+qhexIHob4P35EpBovJstiB1T7Y2NdNfQi+MEmwI7LQNsGTt94yz5sql8a/i4Yeu63+H7TRQCqr3DJlujEPihCRISfnwOjGo8/tl/J8KHK0L3681JE1b2/Jt0o9ViLC+Uk5L4XHFBKm/F2GD6jOefeAxha4q0BHAhpYIhRuOqfbMwAmYaPS9X9ubr2Tds1xmFViAdM0q2CQrA0tW5WzkBv3DT+Nalk3YaR2A+rMhiue8rKQaDJBbh2CSrzRVcIubpkw3J6imBWlHgG2uWgmsQDFYf9o59WCi1iQpQQ9vi+hK1voui6eYJqC7nzZOjr116TMzHc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PMHiuaseZX4lCu51umueTcHSDmf9YpX0hx7iJhBehebhe/gbfytSX8qYb0g2gKoqTC8pJgvHnkqvUKr3mwzUk"},{"content":[{"type":"output_text","text":"I'll create a short, descriptive session title from that request.","logprobs":[],"annotations":[]}],"id":"msg_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874","role":"assistant","type":"message","status":"completed"},{"arguments":"{\"session_title\":\"Sum a.txt and b.txt numbers into c.txt\"}","call_id":"call-b35b8754-d11f-46c5-9c64-fed82640a7f7-0","name":"session_title","type":"function_call","id":"fc_9ce0c0aa-ec8c-9b9b-af10-50b60ef9c874_0","status":"completed"}],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":"concise"},"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":{"type":"function","name":"session_title"},"tools":[{"type":"function","description":"Generate the session_title which we use for the user_message","name":"session_title","parameters":{"type":"object","required":["session_title"],"properties":{"session_title":{"type":"string","description":"Final session title, just 5-10 word descriptive title for the session. Super info dense, no filler."}},"additionalProperties":false},"strict":null}],"top_p":0.95,"usage":{"input_tokens":472,"input_tokens_details":{"cached_tokens":384},"output_tokens":373,"output_tokens_details":{"reasoning_tokens":339},"total_tokens":845,"num_sources_used":0,"num_server_side_tools_used":0,"cost_in_usd_ticks":26060000,"context_details":{"input_tokens":472,"output_tokens":379}},"user":null,"incomplete_details":null,"status":"completed","store":false,"metadata":{"system_fingerprint":"fp_21c045be27"},"background":false,"service_tier":"default","truncation":"disabled","top_logprobs":0,"presence_penalty":0.0,"frequency_penalty":0.0,"prompt_cache_key":null,"max_tool_calls":null,"safety_identifier":null,"error":null,"instructions":null}} +