mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
refactor: rewrite protocol forwarding
This commit is contained in:
1 parent
efbdb6e7d1
commit
4d10eac974
5 files changed
+1318
-790
No files matched your search
@@ -158,7 +158,7 @@ SOCKS5 代理示例:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `retry.max_attempts` | 单个请求的最大尝试次数,包含第一次请求。非 2xx 响应或网络错误会切换节点。 |
|
||||
| `retry.max_attempts` | 单个请求的最大尝试次数,包含第一次请求。网络错误、认证失败、限流和 5xx 会切换节点;其他 4xx 属于确定性的请求错误,会直接返回而不轮换 key。 |
|
||||
| `retry.timeout_seconds` | 单个客户端请求的总超时时间,同时用于限制上游响应头等待时间。 |
|
||||
|
||||
流式响应一旦已经向客户端输出数据,就不会切换节点重新生成,避免拼接两个不同的响应。
|
||||
@@ -170,6 +170,7 @@ SOCKS5 代理示例:
|
||||
| `models.refresh_seconds` | 重新读取 Zen 和 Go 模型列表的间隔秒数。两个列表会并发刷新。 |
|
||||
| `models.protocols` | 手动指定模型的原生协议。值只能是 `chat`、`responses` 或 `anthropic`。通常保持为空。 |
|
||||
|
||||
|
||||
模型协议覆盖示例:
|
||||
|
||||
```json
|
||||
|
||||
+846
-528
File diff suppressed because it is too large.
Load diff
@@ -344,6 +344,14 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
g.logger.Debug("upstream accepted request", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "proxy", redactURL(proxy.name))
|
||||
return resp, nil
|
||||
}
|
||||
// Request-shape errors are deterministic and must be returned to the
|
||||
// caller without rotating through unrelated keys. Authentication,
|
||||
// throttling, server, and transport failures remain retryable.
|
||||
if err == nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests {
|
||||
nodes.MarkSuccess(node)
|
||||
g.logger.Debug("upstream rejected request without retry", "request_id", ids.Request, "attempt", attempt, "status", resp.StatusCode, "proxy", redactURL(proxy.name))
|
||||
return resp, nil
|
||||
}
|
||||
if proxyFailed {
|
||||
if nodes.Proxy(node) == proxy {
|
||||
nodes.MarkFailure(node, resp, err)
|
||||
|
||||
@@ -166,7 +166,7 @@ func inferProtocol(model string) Protocol {
|
||||
return ProtocolAnthropic
|
||||
}
|
||||
}
|
||||
for _, prefix := range []string{"gpt-", "o1", "o3", "o4", "grok-"} {
|
||||
for _, prefix := range []string{"gpt-", "o1", "o3", "o4", "grok-", "muse-"} {
|
||||
if strings.HasPrefix(m, prefix) {
|
||||
return ProtocolResponses
|
||||
}
|
||||
|
||||
@@ -10,31 +10,37 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type streamEvent struct {
|
||||
Kind string
|
||||
ID string
|
||||
Model string
|
||||
Text string
|
||||
Key string
|
||||
ToolID string
|
||||
Name string
|
||||
Stop string
|
||||
Usage *canonicalUsage
|
||||
type bridgeStreamEvent struct {
|
||||
Kind string
|
||||
ResponseID string
|
||||
Model string
|
||||
Text string
|
||||
ToolKey string
|
||||
ToolID string
|
||||
ToolName string
|
||||
Stop string
|
||||
Usage *bridgeUsage
|
||||
}
|
||||
|
||||
type streamParser struct {
|
||||
protocol Protocol
|
||||
toolSeen map[string]bool
|
||||
type bridgeStreamParser struct {
|
||||
protocol Protocol
|
||||
started bool
|
||||
tools map[string]bool
|
||||
responseArgs map[string]bool
|
||||
}
|
||||
|
||||
func transcodeStream(w http.ResponseWriter, r io.Reader, from, to Protocol, model string) error {
|
||||
func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) error {
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
return fmt.Errorf("response writer does not support streaming")
|
||||
}
|
||||
parser := &streamParser{protocol: from, toolSeen: map[string]bool{}}
|
||||
emitter := newStreamEmitter(w, flusher, to, model)
|
||||
err := readSSE(r, func(eventName, data string) error {
|
||||
parser := &bridgeStreamParser{
|
||||
protocol: from,
|
||||
tools: map[string]bool{},
|
||||
responseArgs: map[string]bool{},
|
||||
}
|
||||
emitter := newBridgeStreamEmitter(w, flusher, to, model)
|
||||
if err := readSSE(reader, func(eventName, data string) error {
|
||||
events, err := parser.Parse(eventName, data)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -45,26 +51,25 @@ func transcodeStream(w http.ResponseWriter, r io.Reader, from, to Protocol, mode
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return emitter.Finish()
|
||||
}
|
||||
|
||||
func readSSE(r io.Reader, fn func(eventName, data string) error) error {
|
||||
scanner := bufio.NewScanner(r)
|
||||
func readSSE(reader io.Reader, handler func(eventName, data string) error) error {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
scanner.Buffer(make([]byte, 64<<10), 16<<20)
|
||||
var eventName string
|
||||
var data []string
|
||||
var dataLines []string
|
||||
flush := func() error {
|
||||
if len(data) == 0 {
|
||||
if len(dataLines) == 0 {
|
||||
eventName = ""
|
||||
return nil
|
||||
}
|
||||
err := fn(eventName, strings.Join(data, "\n"))
|
||||
err := handler(eventName, strings.Join(dataLines, "\n"))
|
||||
eventName = ""
|
||||
data = data[:0]
|
||||
dataLines = dataLines[:0]
|
||||
return err
|
||||
}
|
||||
for scanner.Scan() {
|
||||
@@ -75,11 +80,15 @@ func readSSE(r io.Reader, fn func(eventName, data string) error) error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, ":") {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "event:") {
|
||||
eventName = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
data = append(data, strings.TrimSpace(strings.TrimPrefix(line, "data:")))
|
||||
dataLines = append(dataLines, strings.TrimSpace(strings.TrimPrefix(line, "data:")))
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
@@ -88,172 +97,233 @@ func readSSE(r io.Reader, fn func(eventName, data string) error) error {
|
||||
return flush()
|
||||
}
|
||||
|
||||
func (p *streamParser) Parse(eventName, data string) ([]streamEvent, error) {
|
||||
func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamEvent, error) {
|
||||
if data == "[DONE]" {
|
||||
return []streamEvent{{Kind: "done"}}, nil
|
||||
return []bridgeStreamEvent{{Kind: "done"}}, nil
|
||||
}
|
||||
var value map[string]any
|
||||
if err := json.Unmarshal([]byte(data), &value); err != nil {
|
||||
return nil, fmt.Errorf("invalid upstream SSE JSON: %w", err)
|
||||
}
|
||||
switch p.protocol {
|
||||
switch parser.protocol {
|
||||
case ProtocolChat:
|
||||
return p.parseChat(value), nil
|
||||
return parser.parseChat(value), nil
|
||||
case ProtocolAnthropic:
|
||||
return p.parseAnthropic(value), nil
|
||||
return parser.parseAnthropic(value)
|
||||
case ProtocolResponses:
|
||||
return p.parseResponses(eventName, value), nil
|
||||
return parser.parseResponses(eventName, value), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported stream protocol %q", p.protocol)
|
||||
return nil, fmt.Errorf("unsupported stream protocol %q", parser.protocol)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *streamParser) parseChat(v map[string]any) []streamEvent {
|
||||
var events []streamEvent
|
||||
if id := stringAt(v, "id"); id != "" {
|
||||
events = append(events, streamEvent{Kind: "start", ID: id, Model: stringAt(v, "model")})
|
||||
func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStreamEvent {
|
||||
events := make([]bridgeStreamEvent, 0, 4)
|
||||
if !parser.started {
|
||||
if id := stringAt(value, "id"); id != "" {
|
||||
parser.started = true
|
||||
events = append(events, bridgeStreamEvent{Kind: "start", ResponseID: id, Model: stringAt(value, "model")})
|
||||
}
|
||||
}
|
||||
if usageMap := mapAt(v, "usage"); len(usageMap) > 0 {
|
||||
if usageMap := mapAt(value, "usage"); len(usageMap) > 0 {
|
||||
usage := decodeOpenAIUsage(usageMap)
|
||||
events = append(events, streamEvent{Kind: "usage", Usage: &usage})
|
||||
events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage})
|
||||
}
|
||||
for _, raw := range sliceAt(v, "choices") {
|
||||
for _, raw := range sliceAt(value, "choices") {
|
||||
choice, _ := raw.(map[string]any)
|
||||
delta := mapAt(choice, "delta")
|
||||
if text := stringAt(delta, "content"); text != "" {
|
||||
events = append(events, streamEvent{Kind: "text", Text: text})
|
||||
events = append(events, bridgeStreamEvent{Kind: "text", Text: text})
|
||||
}
|
||||
for _, rawCall := range sliceAt(delta, "tool_calls") {
|
||||
call, _ := rawCall.(map[string]any)
|
||||
key := fmt.Sprint(firstAny(call["index"], stringAt(call, "id")))
|
||||
fn := mapAt(call, "function")
|
||||
if !p.toolSeen[key] {
|
||||
p.toolSeen[key] = true
|
||||
events = append(events, streamEvent{Kind: "tool_start", Key: key, ToolID: stringAt(call, "id"), Name: stringAt(fn, "name")})
|
||||
function := mapAt(call, "function")
|
||||
id := stringAt(call, "id")
|
||||
name := stringAt(function, "name")
|
||||
if !parser.tools[key] {
|
||||
parser.tools[key] = true
|
||||
events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: id, ToolName: name})
|
||||
}
|
||||
if args := stringAt(fn, "arguments"); args != "" {
|
||||
events = append(events, streamEvent{Kind: "tool_delta", Key: key, Text: args})
|
||||
if arguments := stringAt(function, "arguments"); arguments != "" {
|
||||
events = append(events, bridgeStreamEvent{Kind: "tool_delta", ToolKey: key, ToolID: id, ToolName: name, Text: arguments})
|
||||
}
|
||||
}
|
||||
if stop := stringAt(choice, "finish_reason"); stop != "" {
|
||||
events = append(events, streamEvent{Kind: "finish", Stop: stop})
|
||||
events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop})
|
||||
}
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
func (p *streamParser) parseAnthropic(v map[string]any) []streamEvent {
|
||||
typeName := stringAt(v, "type")
|
||||
switch typeName {
|
||||
func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridgeStreamEvent, error) {
|
||||
switch stringAt(value, "type") {
|
||||
case "message_start":
|
||||
message := mapAt(v, "message")
|
||||
events := []streamEvent{{Kind: "start", ID: stringAt(message, "id"), Model: stringAt(message, "model")}}
|
||||
message := mapAt(value, "message")
|
||||
events := []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(message, "id"), Model: stringAt(message, "model")}}
|
||||
if usageMap := mapAt(message, "usage"); len(usageMap) > 0 {
|
||||
usage := decodeAnthropicUsage(usageMap)
|
||||
events = append(events, streamEvent{Kind: "usage", Usage: &usage})
|
||||
events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage})
|
||||
}
|
||||
return events
|
||||
return events, nil
|
||||
case "content_block_start":
|
||||
block := mapAt(v, "content_block")
|
||||
key := fmt.Sprint(v["index"])
|
||||
if stringAt(block, "type") == "tool_use" {
|
||||
return []streamEvent{{Kind: "tool_start", Key: key, ToolID: stringAt(block, "id"), Name: stringAt(block, "name")}}
|
||||
block := mapAt(value, "content_block")
|
||||
key := fmt.Sprint(value["index"])
|
||||
switch stringAt(block, "type") {
|
||||
case "tool_use":
|
||||
parser.tools[key] = true
|
||||
return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(block, "id"), ToolName: stringAt(block, "name")}}, nil
|
||||
case "text":
|
||||
if text := stringAt(block, "text"); text != "" {
|
||||
return []bridgeStreamEvent{{Kind: "text", Text: text}}, nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
case "content_block_delta":
|
||||
delta := mapAt(v, "delta")
|
||||
key := fmt.Sprint(v["index"])
|
||||
if stringAt(delta, "type") == "input_json_delta" {
|
||||
return []streamEvent{{Kind: "tool_delta", Key: key, Text: stringAt(delta, "partial_json")}}
|
||||
}
|
||||
if stringAt(delta, "type") == "text_delta" {
|
||||
return []streamEvent{{Kind: "text", Text: stringAt(delta, "text")}}
|
||||
delta := mapAt(value, "delta")
|
||||
key := fmt.Sprint(value["index"])
|
||||
switch stringAt(delta, "type") {
|
||||
case "text_delta":
|
||||
return []bridgeStreamEvent{{Kind: "text", Text: stringAt(delta, "text")}}, nil
|
||||
case "input_json_delta":
|
||||
return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(delta, "partial_json")}}, nil
|
||||
}
|
||||
case "message_delta":
|
||||
var events []streamEvent
|
||||
if usageMap := mapAt(v, "usage"); len(usageMap) > 0 {
|
||||
events := make([]bridgeStreamEvent, 0, 2)
|
||||
if usageMap := mapAt(value, "usage"); len(usageMap) > 0 {
|
||||
usage := decodeAnthropicUsage(usageMap)
|
||||
events = append(events, streamEvent{Kind: "usage", Usage: &usage})
|
||||
events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage})
|
||||
}
|
||||
if stop := stringAt(v, "delta", "stop_reason"); stop != "" {
|
||||
events = append(events, streamEvent{Kind: "finish", Stop: stop})
|
||||
if stop := stringAt(value, "delta", "stop_reason"); stop != "" {
|
||||
events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop})
|
||||
}
|
||||
return events
|
||||
return events, nil
|
||||
case "message_stop":
|
||||
return []streamEvent{{Kind: "done"}}
|
||||
return []bridgeStreamEvent{{Kind: "done"}}, nil
|
||||
case "error":
|
||||
return []streamEvent{{Kind: "finish", Stop: "error"}, {Kind: "done"}}
|
||||
message := firstString(stringAt(value, "error", "message"), "upstream Anthropic stream error")
|
||||
return nil, fmt.Errorf("%s", message)
|
||||
}
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (p *streamParser) parseResponses(eventName string, v map[string]any) []streamEvent {
|
||||
typeName := stringAt(v, "type")
|
||||
func (parser *bridgeStreamParser) parseResponses(eventName string, value map[string]any) []bridgeStreamEvent {
|
||||
typeName := stringAt(value, "type")
|
||||
if typeName == "" {
|
||||
typeName = eventName
|
||||
}
|
||||
switch typeName {
|
||||
case "response.created":
|
||||
response := mapAt(v, "response")
|
||||
return []streamEvent{{Kind: "start", ID: stringAt(response, "id"), Model: stringAt(response, "model")}}
|
||||
response := mapAt(value, "response")
|
||||
return []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(response, "id"), Model: stringAt(response, "model")}}
|
||||
case "response.output_text.delta":
|
||||
return []streamEvent{{Kind: "text", Text: stringAt(v, "delta")}}
|
||||
return []bridgeStreamEvent{{Kind: "text", Text: stringAt(value, "delta")}}
|
||||
case "response.output_item.added":
|
||||
item := mapAt(v, "item")
|
||||
item := mapAt(value, "item")
|
||||
if stringAt(item, "type") == "function_call" {
|
||||
return []streamEvent{{Kind: "tool_start", Key: fmt.Sprint(v["output_index"]), ToolID: stringAt(item, "call_id"), Name: stringAt(item, "name")}}
|
||||
key := responseToolKey(value, item)
|
||||
parser.tools[key] = true
|
||||
return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(item, "call_id"), ToolName: stringAt(item, "name")}}
|
||||
}
|
||||
case "response.function_call_arguments.delta":
|
||||
return []streamEvent{{Kind: "tool_delta", Key: fmt.Sprint(v["output_index"]), Text: stringAt(v, "delta")}}
|
||||
key := responseToolKey(value, nil)
|
||||
parser.responseArgs[key] = true
|
||||
return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(value, "delta")}}
|
||||
case "response.output_item.done":
|
||||
item := mapAt(value, "item")
|
||||
if stringAt(item, "type") == "function_call" {
|
||||
key := responseToolKey(value, item)
|
||||
events := make([]bridgeStreamEvent, 0, 2)
|
||||
if !parser.tools[key] {
|
||||
parser.tools[key] = true
|
||||
events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: stringAt(item, "call_id"), ToolName: stringAt(item, "name")})
|
||||
}
|
||||
if !parser.responseArgs[key] {
|
||||
if arguments := stringAt(item, "arguments"); arguments != "" {
|
||||
events = append(events, bridgeStreamEvent{Kind: "tool_delta", ToolKey: key, Text: arguments})
|
||||
}
|
||||
}
|
||||
return events
|
||||
}
|
||||
case "response.completed", "response.incomplete", "response.failed":
|
||||
response := mapAt(v, "response")
|
||||
response := mapAt(value, "response")
|
||||
usage := decodeOpenAIUsage(mapAt(response, "usage"))
|
||||
stop := "stop"
|
||||
if typeName == "response.incomplete" {
|
||||
stop = "length"
|
||||
}
|
||||
if typeName == "response.failed" {
|
||||
} else if typeName == "response.failed" {
|
||||
stop = "error"
|
||||
}
|
||||
return []streamEvent{{Kind: "usage", Usage: &usage}, {Kind: "finish", Stop: stop}, {Kind: "done"}}
|
||||
return []bridgeStreamEvent{{Kind: "usage", Usage: &usage}, {Kind: "finish", Stop: stop}, {Kind: "done"}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type bufferedTool struct {
|
||||
func responseToolKey(event map[string]any, item map[string]any) string {
|
||||
if item != nil {
|
||||
if id := stringAt(item, "id"); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
if id := stringAt(event, "item_id"); id != "" {
|
||||
return id
|
||||
}
|
||||
return fmt.Sprint(event["output_index"])
|
||||
}
|
||||
|
||||
type bridgeStreamTool struct {
|
||||
Key string
|
||||
ID string
|
||||
ItemID string
|
||||
Name string
|
||||
Arguments strings.Builder
|
||||
Index int
|
||||
Started bool
|
||||
}
|
||||
|
||||
type streamEmitter struct {
|
||||
w io.Writer
|
||||
flush http.Flusher
|
||||
target Protocol
|
||||
response canonicalResponse
|
||||
started bool
|
||||
finished bool
|
||||
textOpen bool
|
||||
textItem string
|
||||
sequence int
|
||||
tools map[string]*bufferedTool
|
||||
order []string
|
||||
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
|
||||
|
||||
tools map[string]*bridgeStreamTool
|
||||
order []string
|
||||
|
||||
sequence int
|
||||
nextOutput int
|
||||
textOpen bool
|
||||
textItemID string
|
||||
textOutput int
|
||||
responseOutput []any
|
||||
}
|
||||
|
||||
func newStreamEmitter(w io.Writer, flush http.Flusher, target Protocol, model string) *streamEmitter {
|
||||
return &streamEmitter{w: w, flush: flush, target: target, response: canonicalResponse{Model: model, Created: time.Now().Unix()}, tools: map[string]*bufferedTool{}}
|
||||
func newBridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string) *bridgeStreamEmitter {
|
||||
return &bridgeStreamEmitter{
|
||||
w: writer,
|
||||
flush: flusher,
|
||||
target: target,
|
||||
model: model,
|
||||
created: time.Now().Unix(),
|
||||
tools: map[string]*bridgeStreamTool{},
|
||||
}
|
||||
}
|
||||
|
||||
func (e *streamEmitter) Emit(event streamEvent) error {
|
||||
if event.ID != "" && e.response.ID == "" {
|
||||
e.response.ID = event.ID
|
||||
func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error {
|
||||
if event.ResponseID != "" && emitter.id == "" {
|
||||
emitter.id = event.ResponseID
|
||||
}
|
||||
if event.Model != "" {
|
||||
e.response.Model = event.Model
|
||||
emitter.model = event.Model
|
||||
}
|
||||
if !e.started && (event.Kind == "start" || event.Kind == "text" || event.Kind == "tool_start") {
|
||||
if err := e.start(); err != nil {
|
||||
if !emitter.started && (event.Kind == "start" || event.Kind == "text" || event.Kind == "tool_start" || event.Kind == "tool_delta") {
|
||||
if err := emitter.start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -262,247 +332,378 @@ func (e *streamEmitter) Emit(event streamEvent) error {
|
||||
if event.Text == "" {
|
||||
return nil
|
||||
}
|
||||
e.response.Text += event.Text
|
||||
return e.emitText(event.Text)
|
||||
emitter.text.WriteString(event.Text)
|
||||
return emitter.emitText(event.Text)
|
||||
case "tool_start":
|
||||
if _, exists := e.tools[event.Key]; !exists {
|
||||
id := event.ToolID
|
||||
if id == "" {
|
||||
id = randomID("call", 12)
|
||||
}
|
||||
e.tools[event.Key] = &bufferedTool{ID: id, ItemID: randomID("fc", 12), Name: event.Name}
|
||||
e.order = append(e.order, event.Key)
|
||||
tool := emitter.tool(event.ToolKey)
|
||||
if event.ToolID != "" {
|
||||
tool.ID = event.ToolID
|
||||
}
|
||||
if event.ToolName != "" {
|
||||
tool.Name = event.ToolName
|
||||
}
|
||||
return emitter.startTool(tool)
|
||||
case "tool_delta":
|
||||
tool := e.tools[event.Key]
|
||||
if tool == nil {
|
||||
tool = &bufferedTool{ID: randomID("call", 12), ItemID: randomID("fc", 12)}
|
||||
e.tools[event.Key] = tool
|
||||
e.order = append(e.order, event.Key)
|
||||
tool := emitter.tool(event.ToolKey)
|
||||
if event.ToolID != "" {
|
||||
tool.ID = event.ToolID
|
||||
}
|
||||
if event.ToolName != "" {
|
||||
tool.Name = event.ToolName
|
||||
}
|
||||
if err := emitter.startTool(tool); err != nil {
|
||||
return err
|
||||
}
|
||||
tool.Arguments.WriteString(event.Text)
|
||||
return emitter.emitToolDelta(tool, event.Text)
|
||||
case "usage":
|
||||
if event.Usage != nil {
|
||||
mergeUsage(&e.response.Usage, *event.Usage)
|
||||
mergeBridgeUsage(&emitter.usage, *event.Usage)
|
||||
}
|
||||
case "finish":
|
||||
e.response.Stop = event.Stop
|
||||
emitter.stop = event.Stop
|
||||
case "done":
|
||||
return e.Finish()
|
||||
return emitter.Finish()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *streamEmitter) start() error {
|
||||
if e.started {
|
||||
func (emitter *bridgeStreamEmitter) tool(key string) *bridgeStreamTool {
|
||||
if key == "" {
|
||||
key = fmt.Sprintf("tool-%d", len(emitter.order))
|
||||
}
|
||||
if current := emitter.tools[key]; current != nil {
|
||||
return current
|
||||
}
|
||||
tool := &bridgeStreamTool{
|
||||
Key: key,
|
||||
ID: randomID("call", 12),
|
||||
ItemID: randomID("fc", 12),
|
||||
Index: len(emitter.order),
|
||||
}
|
||||
emitter.tools[key] = tool
|
||||
emitter.order = append(emitter.order, key)
|
||||
return tool
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) start() error {
|
||||
if emitter.started {
|
||||
return nil
|
||||
}
|
||||
e.started = true
|
||||
if e.response.ID == "" {
|
||||
e.response.ID = randomID("resp", 12)
|
||||
emitter.started = true
|
||||
if emitter.id == "" {
|
||||
emitter.id = randomID("resp", 12)
|
||||
}
|
||||
switch e.target {
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
return e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "content": ""}, "finish_reason": nil}}})
|
||||
return emitter.sse("", map[string]any{
|
||||
"id": asPrefix(emitter.id, "chatcmpl"),
|
||||
"object": "chat.completion.chunk",
|
||||
"created": emitter.created,
|
||||
"model": emitter.model,
|
||||
"choices": []any{map[string]any{
|
||||
"index": 0,
|
||||
"delta": map[string]any{"role": "assistant", "content": ""},
|
||||
"finish_reason": nil,
|
||||
}},
|
||||
})
|
||||
case ProtocolAnthropic:
|
||||
return e.sse("message_start", map[string]any{"type": "message_start", "message": map[string]any{"id": asPrefix(e.response.ID, "msg"), "type": "message", "role": "assistant", "model": e.response.Model, "content": []any{}, "stop_reason": nil, "stop_sequence": nil, "usage": map[string]any{"input_tokens": 0, "output_tokens": 0}}})
|
||||
return emitter.sse("message_start", map[string]any{
|
||||
"type": "message_start",
|
||||
"message": map[string]any{
|
||||
"id": asPrefix(emitter.id, "msg"),
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": emitter.model,
|
||||
"content": []any{},
|
||||
"stop_reason": nil,
|
||||
"stop_sequence": nil,
|
||||
"usage": map[string]any{"input_tokens": 0, "output_tokens": 0},
|
||||
},
|
||||
})
|
||||
case ProtocolResponses:
|
||||
base := map[string]any{"id": asPrefix(e.response.ID, "resp"), "object": "response", "created_at": e.response.Created, "status": "in_progress", "model": e.response.Model, "output": []any{}, "error": nil}
|
||||
if err := e.sse("response.created", map[string]any{"type": "response.created", "response": base, "sequence_number": e.nextSequence()}); err != nil {
|
||||
response := emitter.responsesBase("in_progress", []any{})
|
||||
if err := emitter.sse("response.created", map[string]any{"type": "response.created", "response": response, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
return e.sse("response.in_progress", map[string]any{"type": "response.in_progress", "response": base, "sequence_number": e.nextSequence()})
|
||||
return emitter.sse("response.in_progress", map[string]any{"type": "response.in_progress", "response": response, "sequence_number": emitter.nextSequence()})
|
||||
default:
|
||||
return fmt.Errorf("unsupported stream target %q", emitter.target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *streamEmitter) emitText(delta string) error {
|
||||
switch e.target {
|
||||
func (emitter *bridgeStreamEmitter) emitText(delta string) error {
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
return e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"content": delta}, "finish_reason": nil}}})
|
||||
return emitter.chatChunk(map[string]any{"content": delta}, nil)
|
||||
case ProtocolAnthropic:
|
||||
if !e.textOpen {
|
||||
e.textOpen = true
|
||||
if err := e.sse("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text", "text": ""}}); err != nil {
|
||||
if !emitter.textOpen {
|
||||
emitter.textOpen = true
|
||||
if err := emitter.sse("content_block_start", map[string]any{
|
||||
"type": "content_block_start",
|
||||
"index": 0,
|
||||
"content_block": map[string]any{"type": "text", "text": ""},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return e.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": delta}})
|
||||
return emitter.sse("content_block_delta", map[string]any{
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": map[string]any{"type": "text_delta", "text": delta},
|
||||
})
|
||||
case ProtocolResponses:
|
||||
if !e.textOpen {
|
||||
e.textOpen = true
|
||||
e.textItem = randomID("msg", 12)
|
||||
item := map[string]any{"id": e.textItem, "type": "message", "status": "in_progress", "role": "assistant", "content": []any{}}
|
||||
if err := e.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": 0, "item": item, "sequence_number": e.nextSequence()}); err != nil {
|
||||
if !emitter.textOpen {
|
||||
emitter.textOpen = true
|
||||
emitter.textItemID = randomID("msg", 12)
|
||||
emitter.textOutput = emitter.nextOutput
|
||||
emitter.nextOutput++
|
||||
item := map[string]any{"id": emitter.textItemID, "type": "message", "status": "in_progress", "role": "assistant", "content": []any{}}
|
||||
if err := emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": emitter.textOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := e.sse("response.content_part.added", map[string]any{"type": "response.content_part.added", "item_id": item["id"], "output_index": 0, "content_index": 0, "part": map[string]any{"type": "output_text", "text": "", "annotations": []any{}}, "sequence_number": e.nextSequence()}); err != nil {
|
||||
part := map[string]any{"type": "output_text", "text": "", "annotations": []any{}}
|
||||
if err := emitter.sse("response.content_part.added", map[string]any{"type": "response.content_part.added", "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return e.sse("response.output_text.delta", map[string]any{"type": "response.output_text.delta", "delta": delta, "item_id": e.textItem, "output_index": 0, "content_index": 0, "sequence_number": e.nextSequence()})
|
||||
return emitter.sse("response.output_text.delta", map[string]any{"type": "response.output_text.delta", "delta": delta, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *streamEmitter) Finish() error {
|
||||
if e.finished {
|
||||
func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error {
|
||||
if tool.Started || emitter.target == ProtocolAnthropic {
|
||||
return nil
|
||||
}
|
||||
e.finished = true
|
||||
if !e.started {
|
||||
if err := e.start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, key := range e.order {
|
||||
tool := e.tools[key]
|
||||
if tool == nil {
|
||||
continue
|
||||
}
|
||||
input := parseJSONOrString(tool.Arguments.String())
|
||||
e.response.Tools = append(e.response.Tools, canonicalBlock{Type: "tool_use", ID: tool.ID, Name: tool.Name, Input: input})
|
||||
}
|
||||
if e.response.Stop == "" {
|
||||
e.response.Stop = "stop"
|
||||
}
|
||||
switch e.target {
|
||||
tool.Started = true
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
if len(e.response.Tools) > 0 {
|
||||
calls := make([]any, 0, len(e.response.Tools))
|
||||
for i, tool := range e.response.Tools {
|
||||
args, _ := json.Marshal(tool.Input)
|
||||
calls = append(calls, map[string]any{"index": i, "id": tool.ID, "type": "function", "function": map[string]any{"name": tool.Name, "arguments": string(args)}})
|
||||
}
|
||||
if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"tool_calls": calls}, "finish_reason": nil}}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": chatStop(e.response.Stop)}}}); err != nil {
|
||||
return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{
|
||||
"index": tool.Index,
|
||||
"id": tool.ID,
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": tool.Name,
|
||||
"arguments": "",
|
||||
},
|
||||
}}}, nil)
|
||||
case ProtocolResponses:
|
||||
tool.Index = emitter.nextOutput
|
||||
emitter.nextOutput++
|
||||
item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "in_progress", "arguments": "", "call_id": tool.ID, "name": tool.Name}
|
||||
return emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, delta string) error {
|
||||
if delta == "" || emitter.target == ProtocolAnthropic {
|
||||
return nil
|
||||
}
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{
|
||||
"index": tool.Index,
|
||||
"function": map[string]any{"arguments": delta},
|
||||
}}}, nil)
|
||||
case ProtocolResponses:
|
||||
return emitter.sse("response.function_call_arguments.delta", map[string]any{"type": "response.function_call_arguments.delta", "delta": delta, "item_id": tool.ItemID, "output_index": tool.Index, "sequence_number": emitter.nextSequence()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) Finish() error {
|
||||
if emitter.done {
|
||||
return nil
|
||||
}
|
||||
emitter.done = true
|
||||
if !emitter.started {
|
||||
if err := emitter.start(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{}, "usage": openAIUsage(e.response.Usage)}); err != nil {
|
||||
}
|
||||
if emitter.stop == "" {
|
||||
if len(emitter.order) > 0 {
|
||||
emitter.stop = "tool_calls"
|
||||
} else {
|
||||
emitter.stop = "stop"
|
||||
}
|
||||
}
|
||||
switch emitter.target {
|
||||
case ProtocolChat:
|
||||
if err := emitter.chatChunk(map[string]any{}, chatStop(emitter.stop)); err != nil {
|
||||
return err
|
||||
}
|
||||
return e.rawSSE("", "[DONE]")
|
||||
if err := emitter.sse("", map[string]any{
|
||||
"id": asPrefix(emitter.id, "chatcmpl"),
|
||||
"object": "chat.completion.chunk",
|
||||
"created": emitter.created,
|
||||
"model": emitter.model,
|
||||
"choices": []any{},
|
||||
"usage": openAIUsage(emitter.usage),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return emitter.rawSSE("", "[DONE]")
|
||||
|
||||
case ProtocolAnthropic:
|
||||
index := 0
|
||||
if e.textOpen {
|
||||
if err := e.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil {
|
||||
if emitter.textOpen {
|
||||
if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil {
|
||||
return err
|
||||
}
|
||||
index++
|
||||
}
|
||||
for _, tool := range e.response.Tools {
|
||||
if err := e.sse("content_block_start", map[string]any{"type": "content_block_start", "index": index, "content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}}}); err != nil {
|
||||
for _, key := range emitter.order {
|
||||
tool := emitter.tools[key]
|
||||
if err := emitter.sse("content_block_start", map[string]any{
|
||||
"type": "content_block_start",
|
||||
"index": index,
|
||||
"content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
args, _ := json.Marshal(tool.Input)
|
||||
if err := e.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": index, "delta": map[string]any{"type": "input_json_delta", "partial_json": string(args)}}); err != nil {
|
||||
return err
|
||||
if arguments := tool.Arguments.String(); arguments != "" {
|
||||
if err := emitter.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": index, "delta": map[string]any{"type": "input_json_delta", "partial_json": arguments}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := e.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": index}); err != nil {
|
||||
return err
|
||||
}
|
||||
index++
|
||||
}
|
||||
if err := e.sse("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": anthropicStop(e.response.Stop), "stop_sequence": nil}, "usage": map[string]any{"input_tokens": e.response.Usage.Input, "output_tokens": e.response.Usage.Output}}); err != nil {
|
||||
if err := emitter.sse("message_delta", map[string]any{
|
||||
"type": "message_delta",
|
||||
"delta": map[string]any{"stop_reason": anthropicStop(emitter.stop), "stop_sequence": nil},
|
||||
"usage": map[string]any{"input_tokens": emitter.usage.Input, "output_tokens": emitter.usage.Output},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return e.sse("message_stop", map[string]any{"type": "message_stop"})
|
||||
return emitter.sse("message_stop", map[string]any{"type": "message_stop"})
|
||||
|
||||
case ProtocolResponses:
|
||||
if e.textOpen {
|
||||
if err := e.sse("response.output_text.done", map[string]any{"type": "response.output_text.done", "text": e.response.Text, "item_id": e.textItem, "output_index": 0, "content_index": 0, "sequence_number": e.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
part := map[string]any{"type": "output_text", "text": e.response.Text, "annotations": []any{}}
|
||||
if err := e.sse("response.content_part.done", map[string]any{"type": "response.content_part.done", "item_id": e.textItem, "output_index": 0, "content_index": 0, "part": part, "sequence_number": e.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
item := map[string]any{"id": e.textItem, "type": "message", "status": "completed", "role": "assistant", "content": []any{part}}
|
||||
if err := e.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": 0, "item": item, "sequence_number": e.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := emitter.finishResponsesItems(); err != nil {
|
||||
return err
|
||||
}
|
||||
baseIndex := 0
|
||||
if e.textOpen {
|
||||
baseIndex = 1
|
||||
response := bridgeResponse{
|
||||
ID: emitter.id,
|
||||
Model: emitter.model,
|
||||
Text: emitter.text.String(),
|
||||
Stop: emitter.stop,
|
||||
Usage: emitter.usage,
|
||||
Created: emitter.created,
|
||||
}
|
||||
for i, key := range e.order {
|
||||
tool := e.tools[key]
|
||||
if tool == nil {
|
||||
continue
|
||||
}
|
||||
index := baseIndex + i
|
||||
item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "in_progress", "arguments": "", "call_id": tool.ID, "name": tool.Name}
|
||||
if err := e.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": index, "item": item, "sequence_number": e.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
args := tool.Arguments.String()
|
||||
if err := e.sse("response.function_call_arguments.delta", map[string]any{"type": "response.function_call_arguments.delta", "delta": args, "item_id": tool.ItemID, "output_index": index, "sequence_number": e.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := e.sse("response.function_call_arguments.done", map[string]any{"type": "response.function_call_arguments.done", "arguments": args, "item_id": tool.ItemID, "output_index": index, "sequence_number": e.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
item["status"] = "completed"
|
||||
item["arguments"] = args
|
||||
if err := e.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": index, "item": item, "sequence_number": e.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, key := range emitter.order {
|
||||
tool := emitter.tools[key]
|
||||
response.Tools = append(response.Tools, bridgeBlock{Kind: "tool_call", ID: tool.ID, Name: tool.Name, ArgumentsJSON: tool.Arguments.String()})
|
||||
}
|
||||
output := encodeResponse(ProtocolResponses, e.response)["output"]
|
||||
response := encodeResponse(ProtocolResponses, e.response)
|
||||
response["output"] = output
|
||||
return e.sse("response.completed", map[string]any{"type": "response.completed", "response": response, "sequence_number": e.nextSequence()})
|
||||
completed := encodeBridgeResponse(ProtocolResponses, response)
|
||||
return emitter.sse("response.completed", map[string]any{"type": "response.completed", "response": completed, "sequence_number": emitter.nextSequence()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *streamEmitter) nextSequence() int {
|
||||
value := e.sequence
|
||||
e.sequence++
|
||||
return value
|
||||
func (emitter *bridgeStreamEmitter) finishResponsesItems() error {
|
||||
if emitter.textOpen {
|
||||
text := emitter.text.String()
|
||||
if err := emitter.sse("response.output_text.done", map[string]any{"type": "response.output_text.done", "text": text, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
part := map[string]any{"type": "output_text", "text": text, "annotations": []any{}}
|
||||
if err := emitter.sse("response.content_part.done", map[string]any{"type": "response.content_part.done", "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
item := map[string]any{"id": emitter.textItemID, "type": "message", "status": "completed", "role": "assistant", "content": []any{part}}
|
||||
if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": emitter.textOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, key := range emitter.order {
|
||||
tool := emitter.tools[key]
|
||||
arguments := tool.Arguments.String()
|
||||
if err := emitter.sse("response.function_call_arguments.done", map[string]any{"type": "response.function_call_arguments.done", "arguments": arguments, "item_id": tool.ItemID, "output_index": tool.Index, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "completed", "arguments": arguments, "call_id": tool.ID, "name": tool.Name}
|
||||
if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *streamEmitter) sse(event string, value any) error {
|
||||
func (emitter *bridgeStreamEmitter) chatChunk(delta map[string]any, finish any) error {
|
||||
return emitter.sse("", map[string]any{
|
||||
"id": asPrefix(emitter.id, "chatcmpl"),
|
||||
"object": "chat.completion.chunk",
|
||||
"created": emitter.created,
|
||||
"model": emitter.model,
|
||||
"choices": []any{map[string]any{
|
||||
"index": 0,
|
||||
"delta": delta,
|
||||
"finish_reason": finish,
|
||||
}},
|
||||
})
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) responsesBase(status string, output []any) map[string]any {
|
||||
return map[string]any{
|
||||
"id": asPrefix(emitter.id, "resp"),
|
||||
"object": "response",
|
||||
"created_at": emitter.created,
|
||||
"status": status,
|
||||
"model": emitter.model,
|
||||
"output": output,
|
||||
"error": nil,
|
||||
}
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) nextSequence() int {
|
||||
sequence := emitter.sequence
|
||||
emitter.sequence++
|
||||
return sequence
|
||||
}
|
||||
|
||||
func (emitter *bridgeStreamEmitter) sse(eventName string, value any) error {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return e.rawSSE(event, string(data))
|
||||
return emitter.rawSSE(eventName, string(data))
|
||||
}
|
||||
|
||||
func (e *streamEmitter) rawSSE(event, data string) error {
|
||||
if event != "" {
|
||||
if _, err := fmt.Fprintf(e.w, "event: %s\n", event); err != nil {
|
||||
func (emitter *bridgeStreamEmitter) rawSSE(eventName, data string) error {
|
||||
if eventName != "" {
|
||||
if _, err := fmt.Fprintf(emitter.w, "event: %s\n", eventName); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := fmt.Fprintf(e.w, "data: %s\n\n", data); err != nil {
|
||||
if _, err := fmt.Fprintf(emitter.w, "data: %s\n\n", data); err != nil {
|
||||
return err
|
||||
}
|
||||
e.flush.Flush()
|
||||
emitter.flush.Flush()
|
||||
return nil
|
||||
}
|
||||
|
||||
func mergeUsage(dst *canonicalUsage, src canonicalUsage) {
|
||||
if src.Input != 0 {
|
||||
dst.Input = src.Input
|
||||
func mergeBridgeUsage(destination *bridgeUsage, source bridgeUsage) {
|
||||
if source.Input != 0 {
|
||||
destination.Input = source.Input
|
||||
}
|
||||
if src.Output != 0 {
|
||||
dst.Output = src.Output
|
||||
if source.Output != 0 {
|
||||
destination.Output = source.Output
|
||||
}
|
||||
if src.Total != 0 {
|
||||
dst.Total = src.Total
|
||||
if source.Total != 0 {
|
||||
destination.Total = source.Total
|
||||
}
|
||||
if src.Cached != 0 {
|
||||
dst.Cached = src.Cached
|
||||
if source.Cached != 0 {
|
||||
destination.Cached = source.Cached
|
||||
}
|
||||
if src.Reasoning != 0 {
|
||||
dst.Reasoning = src.Reasoning
|
||||
if source.Reasoning != 0 {
|
||||
destination.Reasoning = source.Reasoning
|
||||
}
|
||||
if dst.Total == 0 {
|
||||
dst.Total = dst.Input + dst.Output
|
||||
if destination.Total == 0 {
|
||||
destination.Total = destination.Input + destination.Output
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user