mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
fix: preserve reasoning and add session affinity
This commit is contained in:
1 parent
4d10eac974
commit
52f19b7bd3
5 files changed
+354
-53
No files matched your search
@@ -7,15 +7,15 @@
|
||||
- 支持 OpenAI Chat Completions、Responses 和 Models API
|
||||
- 支持 Anthropic Messages API
|
||||
- 支持普通响应和 SSE 流式响应
|
||||
- 支持文本、图片、工具定义、工具调用和工具结果转换
|
||||
- 支持文本、图片、thinking/reasoning、工具定义、工具调用和工具结果转换
|
||||
- 分离配置 Zen key 池与 Zen Go key 池
|
||||
- 模型同时存在于两个上游时按 `prefer` 配置优先使用 Go 或 Zen(默认 Go)
|
||||
- 支持直连、HTTP、HTTPS、SOCKS5 和 SOCKS5H 代理
|
||||
- 将 key 自动均衡绑定到代理,保持连接亲和性
|
||||
- 使用无锁轮询分配并发请求
|
||||
- 使用稳定会话哈希保持同一会话的 key/proxy 亲和性,并在节点故障时自动回退
|
||||
- 代理失败后自动迁移绑定,key 失败后进行短时冷却
|
||||
- 根据真实上游流量识别代理故障,并每 15 分钟通过 Cloudflare trace 并行复查异常代理
|
||||
- 为不同会话生成不同的 OpenCode 会话 ID
|
||||
- 为不同会话生成不同的 OpenCode 会话 ID,并支持 `x-opencode-session`、`x-session-id` 和 `conversation-id` 显式指定会话
|
||||
|
||||
## API 路径
|
||||
|
||||
|
||||
+139
-12
@@ -11,6 +11,8 @@ import (
|
||||
type bridgeBlock struct {
|
||||
Kind string
|
||||
Text string
|
||||
Signature string
|
||||
Encrypted string
|
||||
URL string
|
||||
MediaType string
|
||||
Data string
|
||||
@@ -64,13 +66,14 @@ type bridgeUsage struct {
|
||||
}
|
||||
|
||||
type bridgeResponse struct {
|
||||
ID string
|
||||
Model string
|
||||
Text string
|
||||
Tools []bridgeBlock
|
||||
Stop string
|
||||
Usage bridgeUsage
|
||||
Created int64
|
||||
ID string
|
||||
Model string
|
||||
Text string
|
||||
Reasoning []bridgeBlock
|
||||
Tools []bridgeBlock
|
||||
Stop string
|
||||
Usage bridgeUsage
|
||||
Created int64
|
||||
}
|
||||
|
||||
func convertRequest(from, to Protocol, input map[string]any) (map[string]any, error) {
|
||||
@@ -104,6 +107,9 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
|
||||
}
|
||||
role := stringAt(message, "role")
|
||||
blocks := decodeOpenAIBlocks(message["content"])
|
||||
if role == "assistant" {
|
||||
blocks = append(decodeChatReasoning(message), blocks...)
|
||||
}
|
||||
for j, rawCall := range sliceAt(message, "tool_calls") {
|
||||
call, ok := rawCall.(map[string]any)
|
||||
if !ok {
|
||||
@@ -162,6 +168,10 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
|
||||
return request, fmt.Errorf("input[%d] must be an object", i)
|
||||
}
|
||||
switch stringAt(item, "type") {
|
||||
case "reasoning":
|
||||
for _, block := range decodeResponsesReasoning(item) {
|
||||
appendBridgeBlock(&request.Messages, "assistant", block)
|
||||
}
|
||||
case "function_call":
|
||||
appendBridgeBlock(&request.Messages, "assistant", bridgeBlock{
|
||||
Kind: "tool_call",
|
||||
@@ -304,9 +314,11 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
|
||||
}
|
||||
|
||||
for i, message := range request.Messages {
|
||||
var content, calls, results []bridgeBlock
|
||||
var content, reasoning, calls, results []bridgeBlock
|
||||
for _, block := range message.Blocks {
|
||||
switch block.Kind {
|
||||
case "reasoning":
|
||||
reasoning = append(reasoning, block)
|
||||
case "tool_call":
|
||||
calls = append(calls, block)
|
||||
case "tool_result":
|
||||
@@ -323,6 +335,9 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
|
||||
return nil, fmt.Errorf("messages[%d]: assistant message contains tool results", i)
|
||||
}
|
||||
encoded := map[string]any{"role": "assistant", "content": nil}
|
||||
if value, ok := bridgeReasoningText(reasoning); ok {
|
||||
encoded["reasoning_content"] = value
|
||||
}
|
||||
if len(content) > 0 {
|
||||
encoded["content"] = encodeChatBlocks(content)
|
||||
}
|
||||
@@ -348,7 +363,7 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
|
||||
}
|
||||
encoded["tool_calls"] = toolCalls
|
||||
}
|
||||
if len(content) > 0 || len(calls) > 0 {
|
||||
if len(content) > 0 || len(reasoning) > 0 || len(calls) > 0 {
|
||||
messages = append(messages, encoded)
|
||||
}
|
||||
continue
|
||||
@@ -476,6 +491,9 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any {
|
||||
}
|
||||
for _, block := range message.Blocks {
|
||||
switch block.Kind {
|
||||
case "reasoning":
|
||||
flushContent()
|
||||
items = append(items, encodeResponsesReasoning(block, false))
|
||||
case "text":
|
||||
kind := "input_text"
|
||||
if message.Role == "assistant" {
|
||||
@@ -620,6 +638,14 @@ func decodeAnthropicBlocks(value any) []bridgeBlock {
|
||||
for _, raw := range asSlice(value) {
|
||||
part, _ := raw.(map[string]any)
|
||||
switch stringAt(part, "type") {
|
||||
case "thinking":
|
||||
blocks = append(blocks, bridgeBlock{
|
||||
Kind: "reasoning",
|
||||
Text: stringAt(part, "thinking"),
|
||||
Signature: stringAt(part, "signature"),
|
||||
})
|
||||
case "redacted_thinking":
|
||||
blocks = append(blocks, bridgeBlock{Kind: "reasoning", Encrypted: stringAt(part, "data")})
|
||||
case "text":
|
||||
blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")})
|
||||
case "image":
|
||||
@@ -648,6 +674,85 @@ func decodeAnthropicBlocks(value any) []bridgeBlock {
|
||||
return blocks
|
||||
}
|
||||
|
||||
func decodeChatReasoning(message map[string]any) []bridgeBlock {
|
||||
value, exists := message["reasoning_content"]
|
||||
if !exists {
|
||||
value, exists = message["reasoning"]
|
||||
}
|
||||
text, ok := value.(string)
|
||||
if !exists || !ok {
|
||||
return nil
|
||||
}
|
||||
return []bridgeBlock{{
|
||||
Kind: "reasoning",
|
||||
Text: text,
|
||||
Signature: stringAt(message, "reasoning_signature"),
|
||||
}}
|
||||
}
|
||||
|
||||
func decodeResponsesReasoning(item map[string]any) []bridgeBlock {
|
||||
var text strings.Builder
|
||||
for _, raw := range asSlice(item["summary"]) {
|
||||
part, _ := raw.(map[string]any)
|
||||
text.WriteString(stringAt(part, "text"))
|
||||
}
|
||||
if content := item["content"]; content != nil {
|
||||
for _, raw := range asSlice(content) {
|
||||
part, _ := raw.(map[string]any)
|
||||
text.WriteString(stringAt(part, "text"))
|
||||
}
|
||||
}
|
||||
encrypted := stringAt(item, "encrypted_content")
|
||||
if text.Len() == 0 && encrypted == "" {
|
||||
return nil
|
||||
}
|
||||
return []bridgeBlock{{
|
||||
Kind: "reasoning",
|
||||
ID: stringAt(item, "id"),
|
||||
Text: text.String(),
|
||||
Encrypted: encrypted,
|
||||
}}
|
||||
}
|
||||
|
||||
func encodeResponsesReasoning(block bridgeBlock, completed bool) map[string]any {
|
||||
id := block.ID
|
||||
if id == "" {
|
||||
id = randomID("rs", 12)
|
||||
}
|
||||
summary := []any{}
|
||||
if block.Text != "" {
|
||||
summary = append(summary, map[string]any{"type": "summary_text", "text": block.Text})
|
||||
}
|
||||
item := map[string]any{"id": id, "type": "reasoning", "summary": summary}
|
||||
if block.Encrypted != "" {
|
||||
item["encrypted_content"] = block.Encrypted
|
||||
}
|
||||
if completed {
|
||||
item["status"] = "completed"
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func bridgeReasoningText(blocks []bridgeBlock) (string, bool) {
|
||||
if len(blocks) == 0 {
|
||||
return "", false
|
||||
}
|
||||
var text strings.Builder
|
||||
for _, block := range blocks {
|
||||
text.WriteString(block.Text)
|
||||
}
|
||||
return text.String(), true
|
||||
}
|
||||
|
||||
func bridgeReasoningSignature(blocks []bridgeBlock) string {
|
||||
for i := len(blocks) - 1; i >= 0; i-- {
|
||||
if blocks[i].Signature != "" {
|
||||
return blocks[i].Signature
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func encodeChatBlocks(blocks []bridgeBlock) any {
|
||||
if len(blocks) == 1 && blocks[0].Kind == "text" {
|
||||
return blocks[0].Text
|
||||
@@ -688,6 +793,13 @@ func encodeAnthropicBlocks(blocks []bridgeBlock) []any {
|
||||
parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": input})
|
||||
case "tool_result":
|
||||
parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.CallID, "content": block.Result, "is_error": block.IsError})
|
||||
case "reasoning":
|
||||
if block.Encrypted != "" {
|
||||
parts = append(parts, map[string]any{"type": "redacted_thinking", "data": block.Encrypted})
|
||||
continue
|
||||
}
|
||||
part := map[string]any{"type": "thinking", "thinking": block.Text, "signature": block.Signature}
|
||||
parts = append(parts, part)
|
||||
}
|
||||
}
|
||||
return parts
|
||||
@@ -841,6 +953,7 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon
|
||||
}
|
||||
choice, _ := choices[0].(map[string]any)
|
||||
message := mapAt(choice, "message")
|
||||
response.Reasoning = decodeChatReasoning(message)
|
||||
response.Text = bridgeBlocksText(decodeOpenAIBlocks(message["content"]))
|
||||
for _, raw := range sliceAt(message, "tool_calls") {
|
||||
call, _ := raw.(map[string]any)
|
||||
@@ -858,6 +971,8 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon
|
||||
for _, raw := range sliceAt(input, "output") {
|
||||
item, _ := raw.(map[string]any)
|
||||
switch stringAt(item, "type") {
|
||||
case "reasoning":
|
||||
response.Reasoning = append(response.Reasoning, decodeResponsesReasoning(item)...)
|
||||
case "message":
|
||||
response.Text += bridgeBlocksText(decodeOpenAIBlocks(item["content"]))
|
||||
case "function_call":
|
||||
@@ -879,7 +994,9 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon
|
||||
response.Usage = decodeOpenAIUsage(mapAt(input, "usage"))
|
||||
case ProtocolAnthropic:
|
||||
for _, block := range decodeAnthropicBlocks(input["content"]) {
|
||||
if block.Kind == "text" {
|
||||
if block.Kind == "reasoning" {
|
||||
response.Reasoning = append(response.Reasoning, block)
|
||||
} else if block.Kind == "text" {
|
||||
response.Text += block.Text
|
||||
} else if block.Kind == "tool_call" {
|
||||
response.Tools = append(response.Tools, block)
|
||||
@@ -900,6 +1017,12 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string
|
||||
switch protocol {
|
||||
case ProtocolChat:
|
||||
message := map[string]any{"role": "assistant", "content": response.Text}
|
||||
if value, ok := bridgeReasoningText(response.Reasoning); ok {
|
||||
message["reasoning_content"] = value
|
||||
}
|
||||
if signature := bridgeReasoningSignature(response.Reasoning); signature != "" {
|
||||
message["reasoning_signature"] = signature
|
||||
}
|
||||
if len(response.Tools) > 0 {
|
||||
calls := make([]any, 0, len(response.Tools))
|
||||
for _, tool := range response.Tools {
|
||||
@@ -927,7 +1050,10 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string
|
||||
"usage": openAIUsage(response.Usage),
|
||||
}
|
||||
case ProtocolResponses:
|
||||
output := make([]any, 0, len(response.Tools)+1)
|
||||
output := make([]any, 0, len(response.Reasoning)+len(response.Tools)+1)
|
||||
for _, reasoning := range response.Reasoning {
|
||||
output = append(output, encodeResponsesReasoning(reasoning, true))
|
||||
}
|
||||
if response.Text != "" {
|
||||
output = append(output, map[string]any{
|
||||
"id": randomID("msg", 12),
|
||||
@@ -973,7 +1099,8 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string
|
||||
},
|
||||
}
|
||||
case ProtocolAnthropic:
|
||||
content := make([]any, 0, len(response.Tools)+1)
|
||||
content := make([]any, 0, len(response.Reasoning)+len(response.Tools)+1)
|
||||
content = append(content, encodeAnthropicBlocks(response.Reasoning)...)
|
||||
if response.Text != "" {
|
||||
content = append(content, map[string]any{"type": "text", "text": response.Text})
|
||||
}
|
||||
|
||||
+1
-1
@@ -297,7 +297,7 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
nodes = g.goNodes
|
||||
baseURL = g.cfg.Upstream.Go
|
||||
}
|
||||
cursor := nodes.Cursor()
|
||||
cursor := nodes.CursorFor(ids.Session)
|
||||
if nodes.Len() == 0 {
|
||||
return nil, fmt.Errorf("no %s nodes configured", route.Tier)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net"
|
||||
@@ -315,6 +316,19 @@ func (p *nodePool) Cursor() nodeCursor {
|
||||
return nodeCursor{pool: p, next: int((p.next.Add(1) - 1) % uint64(len(p.nodes)))}
|
||||
}
|
||||
|
||||
// CursorFor returns a cursor whose first choice is stable for the supplied
|
||||
// affinity key. This keeps every turn in a conversation on the same upstream
|
||||
// key while retaining Next's cooldown-aware failover behavior. Empty affinity
|
||||
// keys keep the round-robin behavior used by background tasks.
|
||||
func (p *nodePool) CursorFor(affinity string) nodeCursor {
|
||||
if affinity == "" || len(p.nodes) == 0 {
|
||||
return p.Cursor()
|
||||
}
|
||||
hash := fnv.New64a()
|
||||
_, _ = hash.Write([]byte(affinity))
|
||||
return nodeCursor{pool: p, next: int(hash.Sum64() % uint64(len(p.nodes)))}
|
||||
}
|
||||
|
||||
func (c *nodeCursor) Next() *upstreamNode {
|
||||
if c.pool == nil || len(c.pool.nodes) == 0 {
|
||||
return nil
|
||||
|
||||
@@ -15,6 +15,7 @@ type bridgeStreamEvent struct {
|
||||
ResponseID string
|
||||
Model string
|
||||
Text string
|
||||
Signature string
|
||||
ToolKey string
|
||||
ToolID string
|
||||
ToolName string
|
||||
@@ -23,10 +24,11 @@ type bridgeStreamEvent struct {
|
||||
}
|
||||
|
||||
type bridgeStreamParser struct {
|
||||
protocol Protocol
|
||||
started bool
|
||||
tools map[string]bool
|
||||
responseArgs map[string]bool
|
||||
protocol Protocol
|
||||
started bool
|
||||
tools map[string]bool
|
||||
responseArgs map[string]bool
|
||||
responseReasoning map[string]bool
|
||||
}
|
||||
|
||||
func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) error {
|
||||
@@ -35,9 +37,10 @@ func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol,
|
||||
return fmt.Errorf("response writer does not support streaming")
|
||||
}
|
||||
parser := &bridgeStreamParser{
|
||||
protocol: from,
|
||||
tools: map[string]bool{},
|
||||
responseArgs: map[string]bool{},
|
||||
protocol: from,
|
||||
tools: map[string]bool{},
|
||||
responseArgs: map[string]bool{},
|
||||
responseReasoning: map[string]bool{},
|
||||
}
|
||||
emitter := newBridgeStreamEmitter(w, flusher, to, model)
|
||||
if err := readSSE(reader, func(eventName, data string) error {
|
||||
@@ -132,6 +135,9 @@ func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStream
|
||||
for _, raw := range sliceAt(value, "choices") {
|
||||
choice, _ := raw.(map[string]any)
|
||||
delta := mapAt(choice, "delta")
|
||||
if reasoning := stringAt(delta, "reasoning_content"); reasoning != "" {
|
||||
events = append(events, bridgeStreamEvent{Kind: "reasoning", Text: reasoning})
|
||||
}
|
||||
if text := stringAt(delta, "content"); text != "" {
|
||||
events = append(events, bridgeStreamEvent{Kind: "text", Text: text})
|
||||
}
|
||||
@@ -170,6 +176,15 @@ func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridge
|
||||
block := mapAt(value, "content_block")
|
||||
key := fmt.Sprint(value["index"])
|
||||
switch stringAt(block, "type") {
|
||||
case "thinking":
|
||||
events := make([]bridgeStreamEvent, 0, 2)
|
||||
if thinking := stringAt(block, "thinking"); thinking != "" {
|
||||
events = append(events, bridgeStreamEvent{Kind: "reasoning", Text: thinking})
|
||||
}
|
||||
if signature := stringAt(block, "signature"); signature != "" {
|
||||
events = append(events, bridgeStreamEvent{Kind: "reasoning_signature", Signature: signature})
|
||||
}
|
||||
return events, nil
|
||||
case "tool_use":
|
||||
parser.tools[key] = true
|
||||
return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(block, "id"), ToolName: stringAt(block, "name")}}, nil
|
||||
@@ -182,6 +197,10 @@ func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridge
|
||||
delta := mapAt(value, "delta")
|
||||
key := fmt.Sprint(value["index"])
|
||||
switch stringAt(delta, "type") {
|
||||
case "thinking_delta":
|
||||
return []bridgeStreamEvent{{Kind: "reasoning", Text: stringAt(delta, "thinking")}}, nil
|
||||
case "signature_delta":
|
||||
return []bridgeStreamEvent{{Kind: "reasoning_signature", Signature: stringAt(delta, "signature")}}, nil
|
||||
case "text_delta":
|
||||
return []bridgeStreamEvent{{Kind: "text", Text: stringAt(delta, "text")}}, nil
|
||||
case "input_json_delta":
|
||||
@@ -217,6 +236,10 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str
|
||||
return []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(response, "id"), Model: stringAt(response, "model")}}
|
||||
case "response.output_text.delta":
|
||||
return []bridgeStreamEvent{{Kind: "text", Text: stringAt(value, "delta")}}
|
||||
case "response.reasoning_summary_text.delta":
|
||||
key := responseToolKey(value, nil)
|
||||
parser.responseReasoning[key] = true
|
||||
return []bridgeStreamEvent{{Kind: "reasoning", Text: stringAt(value, "delta")}}
|
||||
case "response.output_item.added":
|
||||
item := mapAt(value, "item")
|
||||
if stringAt(item, "type") == "function_call" {
|
||||
@@ -230,6 +253,17 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str
|
||||
return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(value, "delta")}}
|
||||
case "response.output_item.done":
|
||||
item := mapAt(value, "item")
|
||||
if stringAt(item, "type") == "reasoning" {
|
||||
key := responseToolKey(value, item)
|
||||
if parser.responseReasoning[key] {
|
||||
return nil
|
||||
}
|
||||
blocks := decodeResponsesReasoning(item)
|
||||
if len(blocks) > 0 {
|
||||
return []bridgeStreamEvent{{Kind: "reasoning", Text: blocks[0].Text}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if stringAt(item, "type") == "function_call" {
|
||||
key := responseToolKey(value, item)
|
||||
events := make([]bridgeStreamEvent, 0, 2)
|
||||
@@ -281,27 +315,36 @@ type bridgeStreamTool struct {
|
||||
}
|
||||
|
||||
type bridgeStreamEmitter struct {
|
||||
w io.Writer
|
||||
flush http.Flusher
|
||||
target Protocol
|
||||
model string
|
||||
id string
|
||||
created int64
|
||||
started bool
|
||||
done bool
|
||||
stop string
|
||||
usage bridgeUsage
|
||||
text strings.Builder
|
||||
w io.Writer
|
||||
flush http.Flusher
|
||||
target Protocol
|
||||
model string
|
||||
id string
|
||||
created int64
|
||||
started bool
|
||||
done bool
|
||||
stop string
|
||||
usage bridgeUsage
|
||||
text strings.Builder
|
||||
reasoning strings.Builder
|
||||
reasoningSignature strings.Builder
|
||||
|
||||
tools map[string]*bridgeStreamTool
|
||||
order []string
|
||||
|
||||
sequence int
|
||||
nextOutput int
|
||||
textOpen bool
|
||||
textItemID string
|
||||
textOutput int
|
||||
responseOutput []any
|
||||
sequence int
|
||||
nextOutput int
|
||||
textOpen bool
|
||||
reasoningOpen bool
|
||||
reasoningClosed bool
|
||||
reasoningItemID string
|
||||
reasoningOutput int
|
||||
reasoningIndex int
|
||||
textIndex int
|
||||
nextAnthropic int
|
||||
textItemID string
|
||||
textOutput int
|
||||
responseOutput []any
|
||||
}
|
||||
|
||||
func newBridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string) *bridgeStreamEmitter {
|
||||
@@ -322,12 +365,24 @@ func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error {
|
||||
if event.Model != "" {
|
||||
emitter.model = event.Model
|
||||
}
|
||||
if !emitter.started && (event.Kind == "start" || event.Kind == "text" || event.Kind == "tool_start" || event.Kind == "tool_delta") {
|
||||
if !emitter.started && (event.Kind == "start" || event.Kind == "reasoning" || event.Kind == "reasoning_signature" || event.Kind == "text" || event.Kind == "tool_start" || event.Kind == "tool_delta") {
|
||||
if err := emitter.start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
switch event.Kind {
|
||||
case "reasoning":
|
||||
if event.Text == "" {
|
||||
return nil
|
||||
}
|
||||
emitter.reasoning.WriteString(event.Text)
|
||||
return emitter.emitReasoning(event.Text)
|
||||
case "reasoning_signature":
|
||||
if event.Signature == "" {
|
||||
return nil
|
||||
}
|
||||
emitter.reasoningSignature.WriteString(event.Signature)
|
||||
return emitter.emitReasoningSignature(event.Signature)
|
||||
case "text":
|
||||
if event.Text == "" {
|
||||
return nil
|
||||
@@ -433,15 +488,22 @@ func (emitter *bridgeStreamEmitter) start() error {
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) emitText(delta string) error {
|
||||
if emitter.target == ProtocolAnthropic || emitter.target == ProtocolResponses {
|
||||
if err := emitter.finishReasoning(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
return emitter.chatChunk(map[string]any{"content": delta}, nil)
|
||||
case ProtocolAnthropic:
|
||||
if !emitter.textOpen {
|
||||
emitter.textOpen = true
|
||||
emitter.textIndex = emitter.nextAnthropic
|
||||
emitter.nextAnthropic++
|
||||
if err := emitter.sse("content_block_start", map[string]any{
|
||||
"type": "content_block_start",
|
||||
"index": 0,
|
||||
"index": emitter.textIndex,
|
||||
"content_block": map[string]any{"type": "text", "text": ""},
|
||||
}); err != nil {
|
||||
return err
|
||||
@@ -449,7 +511,7 @@ func (emitter *bridgeStreamEmitter) emitText(delta string) error {
|
||||
}
|
||||
return emitter.sse("content_block_delta", map[string]any{
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"index": emitter.textIndex,
|
||||
"delta": map[string]any{"type": "text_delta", "text": delta},
|
||||
})
|
||||
case ProtocolResponses:
|
||||
@@ -472,10 +534,102 @@ func (emitter *bridgeStreamEmitter) emitText(delta string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) emitReasoning(delta string) error {
|
||||
if err := emitter.startReasoning(); err != nil {
|
||||
return err
|
||||
}
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
return emitter.chatChunk(map[string]any{"reasoning_content": delta}, nil)
|
||||
case ProtocolAnthropic:
|
||||
return emitter.sse("content_block_delta", map[string]any{
|
||||
"type": "content_block_delta",
|
||||
"index": emitter.reasoningIndex,
|
||||
"delta": map[string]any{"type": "thinking_delta", "thinking": delta},
|
||||
})
|
||||
case ProtocolResponses:
|
||||
return emitter.sse("response.reasoning_summary_text.delta", map[string]any{"type": "response.reasoning_summary_text.delta", "delta": delta, "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "sequence_number": emitter.nextSequence()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) emitReasoningSignature(signature string) error {
|
||||
if err := emitter.startReasoning(); err != nil {
|
||||
return err
|
||||
}
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
return emitter.chatChunk(map[string]any{"reasoning_signature": signature}, nil)
|
||||
case ProtocolAnthropic:
|
||||
return emitter.sse("content_block_delta", map[string]any{
|
||||
"type": "content_block_delta",
|
||||
"index": emitter.reasoningIndex,
|
||||
"delta": map[string]any{"type": "signature_delta", "signature": signature},
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) startReasoning() error {
|
||||
if emitter.reasoningOpen || emitter.reasoningClosed {
|
||||
return nil
|
||||
}
|
||||
emitter.reasoningOpen = true
|
||||
switch emitter.target {
|
||||
case ProtocolAnthropic:
|
||||
emitter.reasoningIndex = emitter.nextAnthropic
|
||||
emitter.nextAnthropic++
|
||||
return emitter.sse("content_block_start", map[string]any{
|
||||
"type": "content_block_start",
|
||||
"index": emitter.reasoningIndex,
|
||||
"content_block": map[string]any{"type": "thinking", "thinking": "", "signature": ""},
|
||||
})
|
||||
case ProtocolResponses:
|
||||
emitter.reasoningItemID = randomID("rs", 12)
|
||||
emitter.reasoningOutput = emitter.nextOutput
|
||||
emitter.nextOutput++
|
||||
item := map[string]any{"id": emitter.reasoningItemID, "type": "reasoning", "status": "in_progress", "summary": []any{}}
|
||||
if err := emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": emitter.reasoningOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
part := map[string]any{"type": "summary_text", "text": ""}
|
||||
return emitter.sse("response.reasoning_summary_part.added", map[string]any{"type": "response.reasoning_summary_part.added", "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "part": part, "sequence_number": emitter.nextSequence()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) finishReasoning() error {
|
||||
if !emitter.reasoningOpen || emitter.reasoningClosed {
|
||||
return nil
|
||||
}
|
||||
emitter.reasoningClosed = true
|
||||
text := emitter.reasoning.String()
|
||||
switch emitter.target {
|
||||
case ProtocolAnthropic:
|
||||
return emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.reasoningIndex})
|
||||
case ProtocolResponses:
|
||||
if err := emitter.sse("response.reasoning_summary_text.done", map[string]any{"type": "response.reasoning_summary_text.done", "text": text, "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
part := map[string]any{"type": "summary_text", "text": text}
|
||||
if err := emitter.sse("response.reasoning_summary_part.done", map[string]any{"type": "response.reasoning_summary_part.done", "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
item := map[string]any{"id": emitter.reasoningItemID, "type": "reasoning", "status": "completed", "summary": []any{part}}
|
||||
return emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": emitter.reasoningOutput, "item": item, "sequence_number": emitter.nextSequence()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error {
|
||||
if tool.Started || emitter.target == ProtocolAnthropic {
|
||||
return nil
|
||||
}
|
||||
if emitter.target == ProtocolResponses {
|
||||
if err := emitter.finishReasoning(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
tool.Started = true
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
@@ -530,6 +684,9 @@ func (emitter *bridgeStreamEmitter) Finish() error {
|
||||
emitter.stop = "stop"
|
||||
}
|
||||
}
|
||||
if err := emitter.finishReasoning(); err != nil {
|
||||
return err
|
||||
}
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
if err := emitter.chatChunk(map[string]any{}, chatStop(emitter.stop)); err != nil {
|
||||
@@ -548,15 +705,15 @@ func (emitter *bridgeStreamEmitter) Finish() error {
|
||||
return emitter.rawSSE("", "[DONE]")
|
||||
|
||||
case ProtocolAnthropic:
|
||||
index := 0
|
||||
if emitter.textOpen {
|
||||
if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil {
|
||||
if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.textIndex}); err != nil {
|
||||
return err
|
||||
}
|
||||
index++
|
||||
}
|
||||
for _, key := range emitter.order {
|
||||
tool := emitter.tools[key]
|
||||
index := emitter.nextAnthropic
|
||||
emitter.nextAnthropic++
|
||||
if err := emitter.sse("content_block_start", map[string]any{
|
||||
"type": "content_block_start",
|
||||
"index": index,
|
||||
@@ -572,7 +729,6 @@ func (emitter *bridgeStreamEmitter) Finish() error {
|
||||
if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil {
|
||||
return err
|
||||
}
|
||||
index++
|
||||
}
|
||||
if err := emitter.sse("message_delta", map[string]any{
|
||||
"type": "message_delta",
|
||||
@@ -588,12 +744,16 @@ func (emitter *bridgeStreamEmitter) Finish() error {
|
||||
return err
|
||||
}
|
||||
response := bridgeResponse{
|
||||
ID: emitter.id,
|
||||
Model: emitter.model,
|
||||
Text: emitter.text.String(),
|
||||
Stop: emitter.stop,
|
||||
Usage: emitter.usage,
|
||||
Created: emitter.created,
|
||||
ID: emitter.id,
|
||||
Model: emitter.model,
|
||||
Text: emitter.text.String(),
|
||||
Reasoning: []bridgeBlock{{Kind: "reasoning", ID: emitter.reasoningItemID, Text: emitter.reasoning.String(), Signature: emitter.reasoningSignature.String()}},
|
||||
Stop: emitter.stop,
|
||||
Usage: emitter.usage,
|
||||
Created: emitter.created,
|
||||
}
|
||||
if emitter.reasoning.Len() == 0 && emitter.reasoningSignature.Len() == 0 {
|
||||
response.Reasoning = nil
|
||||
}
|
||||
for _, key := range emitter.order {
|
||||
tool := emitter.tools[key]
|
||||
|
||||
Reference in new issue
Block a user