Skip to content
Open
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
52 changes: 52 additions & 0 deletions active_tools.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package agent

// filterToolsByActiveNames reproduces upstream callModel's `activeTools`
// narrowing (packages/agent/src/inner-loop/call-model.ts):
//
// const activeSet = activeTools ? new Set(activeTools) : undefined;
// const activeFilteredTools = activeSet
// ? tools?.filter((t) => isServerTool(t) || activeSet.has(t.function.name))
// : tools;
// const filteredTools = activeFilteredTools?.length ? activeFilteredTools : undefined;
//
// Semantics:
// - activeTools == nil: no filter (upstream `activeTools` omitted).
// - activeTools non-nil (even empty): only client tools whose ToolName is
// listed survive; an empty slice therefore drops every client tool.
// - Server tools always survive — activeTools is a client-name list;
// tool-set snapshots omit server ids from it.
// - Unknown names in activeTools are silently ignored; duplicates are
// irrelevant. Construction order of tools is preserved.
// - An empty result (filtered to nothing, or tools empty/nil to begin
// with) collapses to nil so the request omits `tools` entirely and the
// engine's tool-execution machinery stays disabled.
//
// The result must replace the tool list everywhere downstream — API
// conversion AND execution registration — so the model can neither see nor
// call a filtered tool. Upstream never errors here.
func filterToolsByActiveNames(tools []Tool, activeTools []string) []Tool {
filtered := tools
if activeTools != nil {
active := make(map[string]struct{}, len(activeTools))
for _, n := range activeTools {
active[n] = struct{}{}
}
filtered = make([]Tool, 0, len(tools))
for _, t := range tools {
if t == nil {
continue
}
if IsServerTool(t) {
filtered = append(filtered, t)
continue
}
if _, ok := active[t.ToolName()]; ok {
filtered = append(filtered, t)
}
}
}
if len(filtered) == 0 {
return nil
}
return filtered
}
74 changes: 74 additions & 0 deletions active_tools_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package agent

import (
"context"
"testing"
)

// Ports the pure-filter parts of
// packages/agent/tests/unit/call-model-active-tools.test.ts (upstream
// observes the outbound request's `tools`; here the filter's output is the
// list CallModel converts to API tools and registers for execution).
func TestFilterToolsByActiveNames(t *testing.T) {
a, b := makeSetTool("a"), makeSetTool("b")
webSearch := NewServerTool(ServerToolConfig{Name: "web_search", Config: webSearchServerTool()})
background := MustNewTool(ToolConfig[emptyInput]{
Name: "background",
Execute: func(context.Context, emptyInput, ToolExecuteContext) (any, error) { return nil, nil },
})

cases := []struct {
name string
tools []Tool
activeTools []string
want []string // nil => expect nil result
}{
{"sends only active tools", []Tool{a, b}, []string{"a"}, []string{"a"}},
{"silently ignores unknown names", []Tool{a, b}, []string{"a", "missing"}, []string{"a"}},
{"nil activeTools sends all tools", []Tool{a, b}, nil, []string{"a", "b"}},
{"preserves tool order, not activeTools order", []Tool{a, b}, []string{"b", "a"}, []string{"a", "b"}},
{"duplicate active names are harmless", []Tool{a, b}, []string{"b", "b"}, []string{"b"}},
{"filtered-out tool is dropped (background/task case)", []Tool{background, a}, []string{"a"}, []string{"a"}},
{"explicitly empty tools collapses to nil", []Tool{}, nil, nil},
{"nil tools stays nil", nil, []string{"a"}, nil},
{"filtering out every tool collapses to nil", []Tool{a, b}, []string{"missing"}, nil},
{"empty non-nil activeTools drops every client tool", []Tool{a, b}, []string{}, nil},
{"server tools always pass", []Tool{a, webSearch, b}, []string{"b"}, []string{"server:web_search_2025_08_26", "b"}},
{"server tools pass even with empty activeTools", []Tool{a, webSearch}, []string{}, []string{"server:web_search_2025_08_26"}},
{"server tool Name is not matched as a client name", []Tool{webSearch}, []string{"web_search"}, []string{"server:web_search_2025_08_26"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := filterToolsByActiveNames(tc.tools, tc.activeTools)
if tc.want == nil {
if got != nil {
t.Fatalf("got %v, want nil", toolIDs(got))
}
return
}
eq(t, "tools", toolIDs(got), tc.want)
})
}
}

func TestFilterToolsByActiveNamesDoesNotMutateInput(t *testing.T) {
a, b := makeSetTool("a"), makeSetTool("b")
in := []Tool{a, b}
_ = filterToolsByActiveNames(in, []string{"b"})
eq(t, "input", toolIDs(in), []string{"a", "b"})
}

// The documented pairing: a tool-set snapshot's CallModel fields fed back
// through the engine filter produce exactly the snapshot's active tools.
func TestFilterToolsByActiveNamesWithToolSetSnapshot(t *testing.T) {
a, b, c := makeSetTool("a"), makeSetTool("b"), makeSetTool("c")
webSearch := NewServerTool(ServerToolConfig{Config: webSearchServerTool()})
ts := newSet(t, false, a, webSearch, b, c)
ts = must(ts.Deactivate("b"))
snap := ts.Resolve(none)

eq(t, "from snapshot tools", toolIDs(filterToolsByActiveNames(snap.CallModel.Tools, snap.CallModel.ActiveTools)), snap.Enabled)
// Passing all tools with the snapshot's ActiveTools gives the same client
// subset (server tools are always kept by the filter).
eq(t, "from all tools", toolIDs(filterToolsByActiveNames(ts.Tools(), snap.CallModel.ActiveTools)), []string{"a", "server:web_search_2025_08_26", "c"})
}
6 changes: 6 additions & 0 deletions anthropic_compat.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import (
"github.com/OpenRouterTeam/go-sdk/optionalnullable"
)

// ClaudeMessageInputItem is an input item emitted by FromClaudeMessages
// (upstream ClaudeMessageInputItem): a user/assistant message, a
// function_call, or a function_call_output, expressed as the SDK input-item
// union.
type ClaudeMessageInputItem = components.InputsUnion1

// ClaudeUsage mirrors the Anthropic Claude message usage shape (distinct from
// the OpenRouter SDK usage type). Field names match upstream
// stream-transformers.ts convertToClaudeMessage.
Expand Down
49 changes: 43 additions & 6 deletions chat_compat.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import (
"github.com/OpenRouterTeam/go-sdk/models/components"
)

// ChatMessageInputItem is an input item emitted by FromChatMessages (upstream
// ChatMessageInputItem): a user/system/assistant/developer message, a
// function_call, or a function_call_output. Go expresses the upstream union as
// the SDK input-item union, so it is directly usable as CallModelInput input.
type ChatMessageInputItem = components.InputsUnion1

type ChatMessage struct {
Role string `json:"role"`
Content any `json:"content"`
Expand All @@ -18,8 +24,10 @@ type ChatMessage struct {
// ToChatMessage converts an OpenRouter Responses result into an OpenAI
// Chat-style assistant message, carrying id/model/status metadata and any
// unsupported content so a round trip through FromChatMessages is lossless.
// Tool calls are carried whatever the response status: this is a format
// conversion, not an execution decision (see ExtractToolCallsFromResponse).
func ToChatMessage(resp components.OpenResponsesResult) ChatMessage {
return ChatMessage{Role: "assistant", Content: ExtractTextFromResponse(resp), ToolCalls: ExtractToolCallsFromResponse(resp), Metadata: map[string]any{"id": resp.ID, "model": resp.Model, "status": string(resp.Status), "unsupported_content": ScanUnsupportedContent(resp)}}
return ChatMessage{Role: "assistant", Content: ExtractTextFromResponse(resp), ToolCalls: extractFunctionCalls(resp), Metadata: map[string]any{"id": resp.ID, "model": resp.Model, "status": string(resp.Status), "unsupported_content": ScanUnsupportedContent(resp)}}
}

// FromChatMessages converts OpenAI Chat-style messages into OpenRouter input
Expand All @@ -36,11 +44,21 @@ func FromChatMessages(messages []ChatMessage) ([]components.InputsUnion1, error)
out = append(out, components.CreateInputsUnion1FunctionCallOutputItem(components.FunctionCallOutputItem{CallID: m.ToolCallID, Output: components.CreateFunctionCallOutputItemOutputUnion2Str(result), Type: components.FunctionCallOutputItemTypeFunctionCallOutputFunctionCallOutput}))
continue
}
if text, ok := m.Content.(string); ok {
out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Str(text)))
} else {
out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Any(m.Content)))
// An assistant message with no content is omitted only when tool calls
// are emitted in its place; a content-less message without tool calls
// still round-trips as an empty message (upstream #11).
if m.Role != "assistant" || !chatContentEmpty(m.Content) || len(m.ToolCalls) == 0 {
if text, ok := m.Content.(string); ok {
out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Str(text)))
} else if m.Content == nil {
out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Str("")))
} else {
out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Any(m.Content)))
}
}
// One function_call item per tool call, after the message. Already
// serialized arguments (RawArgs) are forwarded as-is, never
// re-stringified; only structured Arguments are marshaled.
for _, call := range m.ToolCalls {
args := call.RawArgs
if args == "" && call.Arguments != nil {
Expand All @@ -50,7 +68,16 @@ func FromChatMessages(messages []ChatMessage) ([]components.InputsUnion1, error)
}
args = string(b)
}
out = append(out, components.CreateInputsUnion1FunctionCallItem(components.FunctionCallItem{ID: callKey(call), CallID: call.CallID, Name: call.Name, Arguments: args, Type: components.FunctionCallItemTypeFunctionCall}))
// A chat tool call carries a single id that serves as both the
// item id and the call_id (upstream sets id = callId = tc.id).
callID, itemID := call.CallID, call.ID
if callID == "" {
callID = itemID
}
if itemID == "" {
itemID = callID
}
out = append(out, components.CreateInputsUnion1FunctionCallItem(components.FunctionCallItem{ID: itemID, CallID: callID, Name: call.Name, Arguments: args, Status: components.ToolCallStatusCompleted.ToPointer(), Type: components.FunctionCallItemTypeFunctionCall}))
}
}
return out, nil
Expand All @@ -71,3 +98,13 @@ func contentToStringWithError(content any) (string, error) {
}
return string(b), nil
}

// chatContentEmpty mirrors upstream's `contentToString(content).length === 0`
// check for assistant messages: nil and "" are empty.
func chatContentEmpty(content any) bool {
if content == nil {
return true
}
s, ok := content.(string)
return ok && s == ""
}
160 changes: 160 additions & 0 deletions chat_compat_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package agent

import (
"encoding/json"
"reflect"
"testing"

openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/models/components"
"github.com/OpenRouterTeam/go-sdk/models/operations"
)

// assertWireJSON compares the wire (JSON) form of got against the JSON literal
// want, independent of key order. Upstream's chat-compat tests assert on the
// emitted object shape, which in Go is the marshaled SDK union.
func assertWireJSON(t *testing.T, got any, want string) {
t.Helper()
b, err := json.Marshal(got)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var g, w any
if err := json.Unmarshal(b, &g); err != nil {
t.Fatalf("unmarshal got: %v", err)
}
if err := json.Unmarshal([]byte(want), &w); err != nil {
t.Fatalf("unmarshal want: %v", err)
}
if !reflect.DeepEqual(g, w) {
t.Fatalf("wire mismatch\n got: %s\nwant: %s", b, want)
}
}

// Regression tests for upstream issue #11 (assistant tool call conversion).

func TestFromChatMessagesNullContentToolCallEmitsFunctionCall(t *testing.T) {
items, err := FromChatMessages([]ChatMessage{
{Role: "user", Content: "What is the weather in Paris?"},
{Role: "assistant", Content: nil, ToolCalls: []ParsedToolCall{{CallID: "call_123", Name: "get_weather", RawArgs: `{"location":"Paris"}`}}},
{Role: "tool", Content: "Sunny, 22C", ToolCallID: "call_123"},
})
if err != nil {
t.Fatalf("FromChatMessages: %v", err)
}
assertWireJSON(t, items, `[
{"role":"user","content":"What is the weather in Paris?"},
{"type":"function_call","call_id":"call_123","id":"call_123","name":"get_weather","arguments":"{\"location\":\"Paris\"}","status":"completed"},
{"type":"function_call_output","call_id":"call_123","output":"Sunny, 22C"}
]`)
}

func TestFromChatMessagesTextAndToolCallsEmitsBothInOrder(t *testing.T) {
items, err := FromChatMessages([]ChatMessage{
{Role: "assistant", Content: "Let me check the weather for you.", ToolCalls: []ParsedToolCall{{CallID: "call_456", Name: "get_weather", RawArgs: `{"location":"London"}`}}},
})
if err != nil {
t.Fatalf("FromChatMessages: %v", err)
}
assertWireJSON(t, items, `[
{"role":"assistant","content":"Let me check the weather for you."},
{"type":"function_call","call_id":"call_456","id":"call_456","name":"get_weather","arguments":"{\"location\":\"London\"}","status":"completed"}
]`)
}

func TestFromChatMessagesParallelToolCallsEmitOneItemEach(t *testing.T) {
items, err := FromChatMessages([]ChatMessage{
{Role: "assistant", ToolCalls: []ParsedToolCall{
{CallID: "call_a", Name: "get_weather", RawArgs: `{"location":"Paris"}`},
{CallID: "call_b", Name: "get_time", RawArgs: `{"tz":"UTC"}`},
}},
})
if err != nil {
t.Fatalf("FromChatMessages: %v", err)
}
assertWireJSON(t, items, `[
{"type":"function_call","call_id":"call_a","id":"call_a","name":"get_weather","arguments":"{\"location\":\"Paris\"}","status":"completed"},
{"type":"function_call","call_id":"call_b","id":"call_b","name":"get_time","arguments":"{\"tz\":\"UTC\"}","status":"completed"}
]`)
}

func TestFromChatMessagesDoesNotReStringifyArguments(t *testing.T) {
items, err := FromChatMessages([]ChatMessage{
{Role: "assistant", ToolCalls: []ParsedToolCall{{CallID: "call_raw", Name: "noop", RawArgs: `{"a":1}`, Arguments: map[string]any{"a": 1}}}},
})
if err != nil {
t.Fatalf("FromChatMessages: %v", err)
}
if len(items) != 1 || items[0].FunctionCallItem == nil {
t.Fatalf("expected a single function_call item, got %#v", items)
}
// Would be "\"{\\\"a\\\":1}\"" if the serialized arguments were encoded again.
if got := items[0].FunctionCallItem.Arguments; got != `{"a":1}` {
t.Fatalf("arguments = %q, want %q", got, `{"a":1}`)
}
}

func TestFromChatMessagesEmptyToolCallsEmitsOnlyMessage(t *testing.T) {
items, err := FromChatMessages([]ChatMessage{
{Role: "assistant", Content: "No tools needed.", ToolCalls: []ParsedToolCall{}},
})
if err != nil {
t.Fatalf("FromChatMessages: %v", err)
}
assertWireJSON(t, items, `[{"role":"assistant","content":"No tools needed."}]`)
}

// A content-less assistant message without tool calls still round-trips as an
// empty message (upstream keeps it; only tool calls may replace it).
func TestFromChatMessagesEmptyAssistantWithoutToolCallsIsKept(t *testing.T) {
items, err := FromChatMessages([]ChatMessage{{Role: "assistant", Content: nil}, {Role: "assistant", Content: ""}})
if err != nil {
t.Fatalf("FromChatMessages: %v", err)
}
assertWireJSON(t, items, `[{"role":"assistant","content":""},{"role":"assistant","content":""}]`)
}

// Regression test for upstream issue #41: the result is directly usable as
// CallModel input (Go: []InputsUnion1 feeds CallModelInput.Input).
func TestFromChatMessagesResultIsCallModelInput(t *testing.T) {
items, err := FromChatMessages([]ChatMessage{
{Role: "system", Content: "You are helpful."},
{Role: "user", Content: "Hi"},
{Role: "assistant", ToolCalls: []ParsedToolCall{{CallID: "call_typed", Name: "get_weather", RawArgs: `{}`}}},
{Role: "tool", Content: "ok", ToolCallID: "call_typed"},
})
if err != nil {
t.Fatalf("FromChatMessages: %v", err)
}
var typed []ChatMessageInputItem = items
resp := components.OpenResponsesResult{ID: "resp_1", Model: "openai/test", Status: components.OpenAIResponsesResponseStatusCompleted, OutputText: openrouter.String("done")}
created := operations.CreateCreateResponsesResponseOpenResponsesResult(resp)
sender := &fakeSender{responses: []*operations.CreateResponsesResponse{&created}}
result, err := CallModel(t.Context(), sender, CallModelInput{Model: "openai/test", Input: typed})
if err != nil {
t.Fatalf("CallModel: %v", err)
}
if _, err := result.Text(t.Context()); err != nil {
t.Fatalf("Text: %v", err)
}
if len(sender.requests) != 1 || sender.requests[0].Input == nil {
t.Fatalf("expected one request carrying input, got %d", len(sender.requests))
}
assertWireJSON(t, sender.requests[0].Input.ArrayOfInputsUnion1, `[
{"role":"system","content":"You are helpful."},
{"role":"user","content":"Hi"},
{"type":"function_call","call_id":"call_typed","id":"call_typed","name":"get_weather","arguments":"{}","status":"completed"},
{"type":"function_call_output","call_id":"call_typed","output":"ok"}
]`)
}

// ToChatMessage is a format conversion: it keeps the emitted tool calls even
// for a non-completed response, unlike ExtractToolCallsFromResponse, which
// gates execution on the completed status.
func TestToChatMessageKeepsToolCallsOfIncompleteResponse(t *testing.T) {
call := components.OutputFunctionCallItem{CallID: "c1", Name: "search", Arguments: `{"q":"go"}`}
resp := components.OpenResponsesResult{ID: "r", Status: components.OpenAIResponsesResponseStatusIncomplete, Output: []components.OutputItems{components.CreateOutputItemsFunctionCall(call)}}
if got := ToChatMessage(resp).ToolCalls; len(got) != 1 || got[0].CallID != "c1" {
t.Fatalf("ToChatMessage dropped tool calls: %+v", got)
}
}
Loading
Loading