Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion .upstreamer/upstreamer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
80 changes: 0 additions & 80 deletions flatten_message_content_test.go

This file was deleted.

4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -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
)

Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
Expand Down
42 changes: 0 additions & 42 deletions model_result.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 != "" {
Expand Down
139 changes: 139 additions & 0 deletions response_input_items_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading