diff --git a/.upstreamer/upstreamer.md b/.upstreamer/upstreamer.md index dc1fd9b..37cf4e7 100644 --- a/.upstreamer/upstreamer.md +++ b/.upstreamer/upstreamer.md @@ -29,7 +29,7 @@ Explicitly out of scope: The port sits on the official OpenRouter Go SDK and must not reimplement HTTP, auth, retries, or generated model types. -- Target: `github.com/OpenRouterTeam/go-sdk v0.5.4` (current `go.mod` pin). +- Target: `github.com/OpenRouterTeam/go-sdk v0.5.10` (current `go.mod` pin). - `CallModel` sends through `client.Beta.Responses.Send` — the Responses API. - Request, response, item, stream, usage, and tool union types alias the generated SDK's component types where possible. @@ -42,6 +42,15 @@ Known workaround to preserve: the Responses request pins `service_tier` to invalid `service_tier` token. Do not remove this until the SDK pin moves past the fix. +Known constraint, do not regress: response output items are carried into the next +turn's input **unchanged**, as upstream does with `response.output`. Assistant +`message` items keep their `content` array, including `output_text` annotations +such as `url_citation`. `v0.5.10` is the floor for this: below it, `InputsUnion1` +panics when it decodes array content. The port used to work around that panic by +flattening content to a string, which silently dropped annotations from every +follow-up request. Do not move the pin below `v0.5.10`, and do not reintroduce +content flattening or any other rewrite of output items before re-sending them. + ## Module Version Go modules version by git tag, not by a manifest field. Do not invent a version diff --git a/flatten_message_content_test.go b/flatten_message_content_test.go deleted file mode 100644 index 1f47b1a..0000000 --- a/flatten_message_content_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package agent - -// Deterministic regression guard for flattenMessageContentForUnion, the -// workaround for go-sdk v0.5.4's InputsUnion1 unmarshaller panicking on -// array-content assistant messages. The live e2e suite exercises it against -// real traffic; these hardcoded shapes make regressions in the workaround -// itself visible on every PR without spending API credits. - -import ( - "encoding/json" - "testing" - - "github.com/OpenRouterTeam/go-sdk/models/components" -) - -func TestFlattenMessageContentForUnion(t *testing.T) { - cases := []struct { - name string - in string - want string - }{ - { - name: "array of output_text blocks flattens to concatenated string", - in: `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hello, ","annotations":[]},{"type":"output_text","text":"world"}],"id":"msg_1","status":"completed"}`, - want: `{"content":"Hello, world","id":"msg_1","role":"assistant","status":"completed","type":"message"}`, - }, - { - name: "string content passes through untouched", - in: `{"type":"message","role":"assistant","content":"hi","id":"msg_1"}`, - want: `{"type":"message","role":"assistant","content":"hi","id":"msg_1"}`, - }, - { - name: "non-message type passes through untouched", - in: `{"type":"function_call","id":"fc_1","call_id":"call_1","name":"t","arguments":"{}"}`, - want: `{"type":"function_call","id":"fc_1","call_id":"call_1","name":"t","arguments":"{}"}`, - }, - { - name: "non-output_text block bails and returns original", - in: `{"type":"message","role":"user","content":[{"type":"input_image","image_url":"https://example.com/x.png"}],"id":"msg_2"}`, - want: `{"type":"message","role":"user","content":[{"type":"input_image","image_url":"https://example.com/x.png"}],"id":"msg_2"}`, - }, - { - name: "invalid JSON returns original bytes", - in: `{not json`, - want: `{not json`, - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got := string(flattenMessageContentForUnion([]byte(tc.in))) - // Compare semantically where both sides are JSON; byte-for-byte otherwise. - var gotAny, wantAny any - if json.Unmarshal([]byte(got), &gotAny) == nil && json.Unmarshal([]byte(tc.want), &wantAny) == nil { - gb, _ := json.Marshal(gotAny) - wb, _ := json.Marshal(wantAny) - if string(gb) != string(wb) { - t.Fatalf("got %s, want %s", gb, wb) - } - return - } - if got != tc.want { - t.Fatalf("got %q, want %q", got, tc.want) - } - }) - } -} - -// The end-to-end property the workaround exists for: an array-content -// assistant message, after flattening, decodes into InputsUnion1 without -// panicking. (Without the flatten this exact shape reflect-panics in -// go-sdk v0.5.4 — the reason every live tool round crashed.) -func TestFlattenedMessageDecodesIntoInputsUnion(t *testing.T) { - raw := []byte(`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi","annotations":[]}],"id":"msg_1","status":"completed"}`) - flattened := flattenMessageContentForUnion(raw) - var u components.InputsUnion1 - if err := json.Unmarshal(flattened, &u); err != nil { - t.Fatalf("flattened message failed to decode into InputsUnion1: %v", err) - } -} diff --git a/go.mod b/go.mod index a6406e2..9924112 100644 --- a/go.mod +++ b/go.mod @@ -1,9 +1,9 @@ module github.com/OpenRouterTeam/go-agent -go 1.25 +go 1.25.10 require ( - github.com/OpenRouterTeam/go-sdk v0.5.4 + github.com/OpenRouterTeam/go-sdk v0.5.10 github.com/invopop/jsonschema v0.13.0 ) diff --git a/go.sum b/go.sum index 2a6b58c..f45c74a 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -github.com/OpenRouterTeam/go-sdk v0.5.4 h1:3prD1aYTheQgaZlIBIjbDdSi0Ep4tYMyaWJg6MMsMQU= -github.com/OpenRouterTeam/go-sdk v0.5.4/go.mod h1:GRqEs3Twjnq1GekyuZCxHi55X8rBiHYK860wc3IvyUE= +github.com/OpenRouterTeam/go-sdk v0.5.10 h1:YmeWHYbkwoXfHod4hIBA93T6oUihFMVbCfUmswu8b9Q= +github.com/OpenRouterTeam/go-sdk v0.5.10/go.mod h1:8ZRHxPEBG2Lu7BXRGbcoTdhRQnXGFZ+y0jKVpCAQR8c= github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= diff --git a/model_result.go b/model_result.go index 35dd14f..88257e9 100644 --- a/model_result.go +++ b/model_result.go @@ -1382,7 +1382,6 @@ func responseInputItemsWithError(resp components.OpenResponsesResult) ([]compone if err != nil { return nil, fmt.Errorf("marshal response output item: %w", err) } - b = flattenMessageContentForUnion(b) var input components.InputsUnion1 if err := json.Unmarshal(b, &input); err != nil { return nil, fmt.Errorf("convert response output item to input item: %w", err) @@ -1392,47 +1391,6 @@ func responseInputItemsWithError(resp components.OpenResponsesResult) ([]compone return items, nil } -// flattenMessageContentForUnion rewrites a marshaled `message` item whose -// content is an array of output_text blocks into the equivalent -// string-content form. go-sdk v0.5.4's InputsUnion1 unmarshaller panics -// (reflect on slice value) on array-content assistant messages — the exact -// shape every live response echoes back on follow-up turns — but accepts the -// same message with string content. Text is preserved; annotations are not -// (they are response-side metadata the next request does not need). Remove -// once the pinned go-sdk's union decoding handles array content. -func flattenMessageContentForUnion(b []byte) []byte { - var raw map[string]any - if err := json.Unmarshal(b, &raw); err != nil { - return b - } - if raw["type"] != "message" { - return b - } - blocks, ok := raw["content"].([]any) - if !ok { - return b - } - var text strings.Builder - for _, block := range blocks { - m, ok := block.(map[string]any) - if !ok { - return b // unknown block shape: leave untouched - } - if m["type"] != "output_text" { - return b // non-text content: leave untouched - } - if s, ok := m["text"].(string); ok { - text.WriteString(s) - } - } - raw["content"] = text.String() - flattened, err := json.Marshal(raw) - if err != nil { - return b - } - return flattened -} - func appendResponseItemsToState(state ConversationState, resp components.OpenResponsesResult, items []components.InputsUnion1) ConversationState { state = AppendToMessages(state, items...) if resp.ID != "" { diff --git a/response_input_items_test.go b/response_input_items_test.go new file mode 100644 index 0000000..f72ca27 --- /dev/null +++ b/response_input_items_test.go @@ -0,0 +1,139 @@ +package agent + +// Regression guard for carrying a response's output into the next turn's input. +// Upstream appends response.output to the conversation unchanged, so an assistant +// message keeps its content array, including url_citation annotations from the +// web-search server tool. Before go-sdk v0.5.10, InputsUnion1 panicked when it +// decoded array content, and the port worked around that by flattening the +// content to a string, which dropped the annotations from every follow-up +// request. + +import ( + "context" + "encoding/json" + "strings" + "testing" + + openrouter "github.com/OpenRouterTeam/go-sdk" + "github.com/OpenRouterTeam/go-sdk/models/components" +) + +const annotatedAssistantMessage = `{ + "type": "message", "role": "assistant", "id": "msg_1", "status": "completed", + "content": [ + {"type": "output_text", "text": "Apple announced X [apple.com](https://www.apple.com/newsroom/x).", + "annotations": [{"type": "url_citation", "url": "https://www.apple.com/newsroom/x", + "title": "Newsroom", "start_index": 18, "end_index": 63}]}, + {"type": "output_text", "text": " More.", "annotations": []} + ] +}` + +func annotatedResponse(t *testing.T, extra ...string) components.OpenResponsesResult { + t.Helper() + items := append([]string{annotatedAssistantMessage}, extra...) + raw := `{"id":"resp_1","object":"response","status":"completed","model":"openai/test","output":[` + strings.Join(items, ",") + `]}` + var resp components.OpenResponsesResult + if err := json.Unmarshal([]byte(raw), &resp); err != nil { + t.Fatalf("decode fixture response: %v", err) + } + return resp +} + +// assertAnnotatedMessage checks that the marshaled input message still holds +// both content blocks, in order, and the url_citation annotation. +func assertAnnotatedMessage(t *testing.T, item json.RawMessage) { + t.Helper() + var msg struct { + Type string `json:"type"` + Role string `json:"role"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + Annotations []struct { + Type string `json:"type"` + URL string `json:"url"` + Title string `json:"title"` + StartIndex int `json:"start_index"` + EndIndex int `json:"end_index"` + } `json:"annotations"` + } `json:"content"` + } + if err := json.Unmarshal(item, &msg); err != nil { + t.Fatalf("assistant message content is not the upstream array shape: %v\n%s", err, item) + } + if msg.Type != "message" || msg.Role != "assistant" { + t.Fatalf("expected assistant message, got type=%q role=%q", msg.Type, msg.Role) + } + if len(msg.Content) != 2 || msg.Content[0].Type != "output_text" || msg.Content[1].Text != " More." { + t.Fatalf("content blocks not preserved as-is: %s", item) + } + anns := msg.Content[0].Annotations + if len(anns) != 1 { + t.Fatalf("expected 1 annotation on the first block, got %d: %s", len(anns), item) + } + a := anns[0] + if a.Type != "url_citation" || a.URL != "https://www.apple.com/newsroom/x" || a.Title != "Newsroom" || a.StartIndex != 18 || a.EndIndex != 63 { + t.Fatalf("url_citation annotation not preserved: %+v", a) + } +} + +func TestResponseInputItemsPreservesURLCitationAnnotations(t *testing.T) { + items, err := responseInputItemsWithError(annotatedResponse(t)) + if err != nil { + t.Fatal(err) + } + if len(items) != 1 { + t.Fatalf("expected 1 input item, got %d", len(items)) + } + b, err := json.Marshal(items[0]) + if err != nil { + t.Fatal(err) + } + assertAnnotatedMessage(t, b) +} + +// End to end: an annotated assistant message followed by a function call. The +// follow-up request must echo the message back with its annotations intact. +func TestFollowUpRequestCarriesURLCitationAnnotations(t *testing.T) { + call := `{"type":"function_call","id":"fc_1","call_id":"call_1","name":"search","arguments":"{\"query\":\"go\"}","status":"completed"}` + first := annotatedResponse(t, call) + second := components.OpenResponsesResult{ID: "resp_2", OutputText: openrouter.String("done")} + sender := twoTurnSender(first, second) + + result, err := CallModel(context.Background(), sender, CallModelInput{ + Model: "openai/test", Input: "hi", Tools: []Tool{searchTool(t)}, + }) + if err != nil { + t.Fatal(err) + } + if _, err := result.Text(context.Background()); err != nil { + t.Fatal(err) + } + if len(sender.requests) != 2 { + t.Fatalf("expected 2 requests, got %d", len(sender.requests)) + } + + b, err := json.Marshal(sender.requests[1].Input) + if err != nil { + t.Fatal(err) + } + var input []json.RawMessage + if err := json.Unmarshal(b, &input); err != nil { + t.Fatalf("follow-up input is not an item array: %v\n%s", err, b) + } + var found bool + for _, item := range input { + var head struct { + Type string `json:"type"` + Role string `json:"role"` + } + _ = json.Unmarshal(item, &head) + if head.Type == "message" && head.Role == "assistant" { + assertAnnotatedMessage(t, item) + found = true + } + } + if !found { + t.Fatalf("follow-up input dropped the assistant message: %s", b) + } +}