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
9 changes: 9 additions & 0 deletions changelog/unreleased/provider-tool-profiles.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### English

- Give every adapter the canonical tool profile from `internal/toolcall`, so declared tools, tool choice and parallel calls reach the upstream payload unchanged.
- Replay a transient failure inside the adapter and report the internal retry count, keep an upstream `Retry-After` instead of a generic backoff, and stop a stream that ends without a terminal frame.

### 中文

- 各适配器统一使用 `internal/toolcall` 的规范工具档案,声明的工具、工具选择与并行调用原样进入上游请求体。
- 瞬时失败由适配器就地重放并回报内部重试次数,保留上游 `Retry-After` 而非通用退避,并对没有终态帧的流立即结束。
10 changes: 10 additions & 0 deletions changelog/unreleased/toolcall-contract-package.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### English

- Add `internal/toolcall`: one canonical model of tool declarations, tool choice, argument repair, native call identity and rendering, so protocols stop each re-implementing the contract.
- Validate `tools`, `tool_choice` and `parallel_tool_calls` through that parser in the shared chat-request validation every protocol entry runs, so an orphan `auto` degrades to unspecified while `required` or a named choice fails instead of silently dropping the tool request.

### 中文

- 新增 `internal/toolcall`:工具声明、工具选择、参数修复、原生调用身份与渲染只有一份规范模型,协议层不再各自实现这套契约。
- Responses 入口与各协议的共用请求校验都通过该解析器校验 `tools`、`tool_choice`、`parallel_tool_calls`:孤立的 `auto` 降级为未指定,`required` 或指定工具则校验失败,不再静默丢弃工具请求。

8 changes: 2 additions & 6 deletions internal/providers/client_ua.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,12 @@ func ClientUserAgentFromContext(ctx context.Context) string {

// WithConversation records the gateway session key so a provider can keep one
// upstream conversation id across the turns of a chat. Routing still owns the
// key; this only carries it.
// key; this only carries it. An empty key clears any inherited conversation.
func WithConversation(ctx context.Context, key string) context.Context {
if ctx == nil {
ctx = context.Background()
}
key = strings.TrimSpace(key)
if key == "" {
return ctx
}
return context.WithValue(ctx, conversationKey{}, key)
return context.WithValue(ctx, conversationKey{}, strings.TrimSpace(key))
}

// ConversationFromContext returns the session key set by WithConversation, or
Expand Down
45 changes: 44 additions & 1 deletion internal/providers/codex/sse.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,16 @@ func (c *streamConverter) handleEvent(event, payload string) {
c.finishReason = "stop"
if typ == "response.incomplete" {
c.finishReason = "length"
} else {
for _, item := range resp.Response.Output {
var probe struct {
Type string `json:"type"`
}
if json.Unmarshal(item, &probe) == nil && isResponsesToolItem(probe.Type) {
c.finishReason = "tool_calls"
break
}
}
}
c.sawTerminal = true
c.emitUsage()
Expand All @@ -270,15 +280,36 @@ func (c *streamConverter) handleEvent(event, payload string) {
var errObj struct {
Message string `json:"message"`
Code string `json:"code"`
Error struct {
Message string `json:"message"`
Code string `json:"code"`
} `json:"error"`
Response struct {
Error struct {
Message string `json:"message"`
Code string `json:"code"`
} `json:"error"`
} `json:"response"`
}
_ = json.Unmarshal([]byte(payload), &errObj)
c.emitDone()
message := firstNonEmpty(errObj.Message, errObj.Error.Message, errObj.Response.Error.Message, "upstream response failed")
code := firstNonEmpty(errObj.Code, errObj.Error.Code, errObj.Response.Error.Code, "upstream_error")
c.emitError(message, code)
c.sawTerminal = true
case "response.created":
// no-op; gateway synthesizes its own response.created
}
}

func isResponsesToolItem(kind string) bool {
switch kind {
case "function_call", "custom_tool_call", "local_shell_call", "mcp_call":
return true
default:
return false
}
}

func (c *streamConverter) emitContent(text string) {
if text == "" {
return
Expand Down Expand Up @@ -401,6 +432,18 @@ func (c *streamConverter) emitDone() {
_, _ = c.writer.Write([]byte("data: [DONE]\n\n"))
}

func (c *streamConverter) emitError(message, code string) {
payload, err := json.Marshal(map[string]any{"error": map[string]any{
"message": message,
"code": code,
"type": "upstream_error",
}})
if err != nil {
return
}
_, _ = c.writer.Write([]byte("data: " + string(payload) + "\n\n"))
}

func (c *streamConverter) writeChunk(obj map[string]any) {
obj["object"] = "chat.completion.chunk"
obj["model"] = c.model
Expand Down
46 changes: 46 additions & 0 deletions internal/providers/codex/sse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,52 @@ data: {"type":"response.completed","response":{"status":"completed","usage":{"in
}
}

func TestRewriteStreamMapsToolOutputToToolCallsFinish(t *testing.T) {
sse := `event: response.output_item.added
data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_weather","arguments":""}}

event: response.function_call_arguments.done
data: {"type":"response.function_call_arguments.done","output_index":0,"item_id":"fc_1","arguments":"{\"city\":\"Tokyo\"}"}

event: response.completed
data: {"type":"response.completed","response":{"status":"completed","usage":{"input_tokens":1,"output_tokens":1},"output":[{"type":"function_call","call_id":"call_1","name":"get_weather","arguments":"{\"city\":\"Tokyo\"}"}]}}

`
stream, err := rewriteStream(strings.NewReader(sse), "gpt-6.1-sol")
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(stream.Reader)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), `"finish_reason":"tool_calls"`) {
t.Fatalf("tool output finished without tool_calls: %s", body)
}
}

func TestRewriteStreamFailureIsAnErrorNotStop(t *testing.T) {
sse := `event: response.failed
data: {"type":"response.failed","response":{"status":"failed","error":{"message":"quota exhausted","code":"insufficient_quota"}}}

`
stream, err := rewriteStream(strings.NewReader(sse), "gpt-6.1-sol")
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(stream.Reader)
if err != nil {
t.Fatal(err)
}
out := string(body)
if !strings.Contains(out, `"error"`) || !strings.Contains(out, "quota exhausted") {
t.Fatalf("failure was not relayed as an error: %s", out)
}
if strings.Contains(out, `"finish_reason":"stop"`) || strings.Contains(out, "[DONE]") {
t.Fatalf("failure was turned into a successful terminal: %s", out)
}
}

// An item that is not a tool call must not consume a tool-call index or emit a
// chunk, otherwise a reasoning item would shift every later call.
func TestRewriteStreamIgnoresNonToolOutputItems(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions internal/providers/devin/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ func (c *Client) buildChatHTTPRequestFromPayload(ctx context.Context, credential
payload.System,
payload.Prompts,
payload.Tools,
payload.ToolChoice,
payload.Temperature,
payload.MaxTokens,
"",
Expand Down
44 changes: 44 additions & 0 deletions internal/providers/devin/payload.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"

"github.com/caigee-cmd/cli2api/internal/providers"
chatpb "github.com/caigee-cmd/cli2api/internal/providers/devin/devinpb/chat_pb"
"github.com/caigee-cmd/cli2api/internal/translate"
)

Expand All @@ -24,6 +25,7 @@ type ChatPayload struct {
System string
Prompts []Prompt
Tools []Tool
ToolChoice *chatpb.ChatToolChoice
Temperature *float64
MaxTokens int
ModelUID string
Expand Down Expand Up @@ -83,6 +85,7 @@ func BuildChatPayload(req translate.ChatRequest, catalogLevels map[string][]stri
System: system,
Prompts: prompts,
Tools: tools,
ToolChoice: parseToolChoice(req.ToolChoice, aliases),
Temperature: temp,
MaxTokens: maxTokens,
ModelUID: modelUID,
Expand Down Expand Up @@ -269,6 +272,47 @@ func parseTools(raw json.RawMessage, aliases *toolAliasMaps) []Tool {
return out
}

func parseToolChoice(raw json.RawMessage, aliases *toolAliasMaps) *chatpb.ChatToolChoice {
if len(raw) == 0 || string(raw) == "null" {
return nil
}
var text string
if json.Unmarshal(raw, &text) == nil {
switch strings.ToLower(strings.TrimSpace(text)) {
case "auto", "none", "required":
return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_OptionName{OptionName: strings.ToLower(strings.TrimSpace(text))}}
default:
name := strings.TrimSpace(text)
if name == "" {
return nil
}
return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_ToolName{ToolName: aliases.alias(name)}}
}
}
var object map[string]any
if json.Unmarshal(raw, &object) != nil {
return nil
}
kind, _ := object["type"].(string)
kind = strings.ToLower(strings.TrimSpace(kind))
switch kind {
case "none", "auto", "required":
return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_OptionName{OptionName: kind}}
case "function", "custom", "tool":
name, _ := object["name"].(string)
if fn, ok := object["function"].(map[string]any); ok {
name, _ = fn["name"].(string)
}
name = strings.TrimSpace(name)
if name == "" {
return nil
}
return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_ToolName{ToolName: aliases.alias(name)}}
default:
return nil
}
}

func expandNamespaceTools(raw json.RawMessage, namespace string) []Tool {
var wrapper struct {
Tools []json.RawMessage `json:"tools"`
Expand Down
4 changes: 4 additions & 0 deletions internal/providers/devin/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ func BuildGetChatMessageRequest(
systemPrompt string,
prompts []Prompt,
tools []Tool,
toolChoice *chatpb.ChatToolChoice,
temperature *float64,
maxTokens int,
sessionID string,
Expand Down Expand Up @@ -252,6 +253,9 @@ func BuildGetChatMessageRequest(
PlannerMode: commonpb.ConversationalPlannerMode_CONVERSATIONAL_PLANNER_MODE_DEFAULT,
ChatModelUid: chatModelUID,
}
if toolChoice != nil {
req.ToolChoice = toolChoice
}
if strings.TrimSpace(systemPrompt) != "" {
req.Prompt = systemPrompt
}
Expand Down
1 change: 1 addition & 0 deletions internal/providers/devin/wire_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func TestChatRequestWireContract(t *testing.T) {
Images: []Image{{Base64Data: "aGVsbG8=", MimeType: "image/png"}},
Thinking: "reason", Signature: []byte("signature"), SignatureType: "type"}},
[]Tool{{Name: "lookup", Description: "description", Parameters: []byte(`{"type":"object"}`)}},
nil,
&temperature, 1234, t.Name(), "cascade")
if err != nil {
t.Fatal(err)
Expand Down
9 changes: 9 additions & 0 deletions internal/providers/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ type ChatOutcome struct {
// ReasoningLevel is the clamped reasoning level actually sent upstream,
// empty when the provider did not include one in the payload.
ReasoningLevel string
// InternalRetries counts same-account replays the adapter performed.
InternalRetries int
}

// ResolvedChat carries provider-side metadata for a stream request that the
Expand All @@ -131,6 +133,9 @@ type ResolvedChat struct {
// ReasoningLevel is the clamped reasoning level actually sent upstream,
// empty when the provider did not include one in the payload.
ReasoningLevel string
// InternalRetries counts same-account replays the adapter performed
// before opening this stream.
InternalRetries int
}

// ProviderChat executes chat for one account. Stream implementations return
Expand Down Expand Up @@ -341,6 +346,10 @@ type Error struct {
Code string
Type string
RetryAfter time.Duration
// InternalRetries counts upstream requests the adapter already replayed
// before returning this failure. The executor adds it to the route attempt
// so one route attempt does not hide several wire requests.
InternalRetries int
}

func (e *Error) Error() string {
Expand Down
23 changes: 22 additions & 1 deletion internal/providers/kimi/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
Expand Down Expand Up @@ -201,16 +202,25 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err
if err != nil {
return providers.ChatOutcome{}, err
}
sawDone, sawFinish := false, false
for _, line := range strings.Split(string(raw), "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "data:") {
continue
}
data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if data == "" || data == "[DONE]" {
if data == "" {
continue
}
if data == "[DONE]" {
sawDone = true
continue
}
var chunk struct {
Error *struct {
Message string `json:"message"`
Code any `json:"code"`
} `json:"error"`
Choices []struct {
Delta struct {
Content string `json:"content"`
Expand Down Expand Up @@ -239,6 +249,13 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err
if json.Unmarshal([]byte(data), &chunk) != nil {
continue
}
if chunk.Error != nil {
message := strings.TrimSpace(chunk.Error.Message)
if message == "" {
message = fmt.Sprintf("kimi stream error (code %v)", chunk.Error.Code)
}
return providers.ChatOutcome{}, fmt.Errorf("kimi stream: %s", message)
}
if chunk.Usage != nil {
if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 {
agg.usage = chatUsage{
Expand All @@ -262,6 +279,7 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err
}
if choice.FinishReason != "" {
agg.finish = choice.FinishReason
sawFinish = true
}
for _, call := range choice.Delta.ToolCalls {
state := agg.tools[call.Index]
Expand All @@ -280,6 +298,9 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err
}
}
}
if !sawDone && !sawFinish {
return providers.ChatOutcome{}, fmt.Errorf("kimi stream ended without a terminal frame")
}
outcome := providers.ChatOutcome{
Model: model,
Content: agg.content.String(),
Expand Down
12 changes: 12 additions & 0 deletions internal/providers/kimi/flows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1032,3 +1032,15 @@ func TestDeviceLoginPendingDoesNotWidenInterval(t *testing.T) {
t.Fatalf("pending widened the interval to %v", got)
}
}

func TestCollectChatStreamRejectsErrorAndTruncatedStreams(t *testing.T) {
if _, err := collectChatStream(strings.NewReader(`data: {"error":{"message":"quota exhausted","code":"1113"}}`+"\n\n"), "kimi-k2"); err == nil || !strings.Contains(err.Error(), "quota exhausted") {
t.Fatalf("error frame error = %v", err)
}
if _, err := collectChatStream(strings.NewReader(`data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n\n"), "kimi-k2"); err == nil || !strings.Contains(err.Error(), "terminal") {
t.Fatalf("truncated stream error = %v", err)
}
if outcome, err := collectChatStream(strings.NewReader(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`+"\n\n"), "kimi-k2"); err != nil || outcome.FinishReason != "stop" {
t.Fatalf("finish-only stream outcome=%+v err=%v", outcome, err)
}
}
Loading
Loading