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
91 changes: 91 additions & 0 deletions cmd/ocgo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1015,9 +1015,100 @@ func proxyChatCompletions(w http.ResponseWriter, r *http.Request, cfg Config) {
defer resp.Body.Close()
copyHeaders(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
if or.Stream {
streamChatCompletionsPassthrough(w, resp.Body)
return
}
_, _ = io.Copy(w, resp.Body)
}

// streamChatCompletionsPassthrough forwards an upstream OpenAI chat
// completions SSE stream verbatim, except that it drops null id/name fields
// from tool_calls argument deltas. Some upstreams emit those nulls, which
// strict streaming clients (e.g. dsh) use to overwrite the tool identity set
// on the first tool_calls chunk, producing empty tool names.
func streamChatCompletionsPassthrough(w http.ResponseWriter, body io.Reader) {
flusher, _ := w.(http.Flusher)
s := bufio.NewScanner(body)
collected := make([]string, 0, 2)
flush := func() {
if len(collected) == 0 {
return
}
payload := strings.Join(collected, "\n")
collected = collected[:0]
out := []byte(payload)
if payload != "[DONE]" && bytes.Contains(out, []byte("tool_calls")) {
var chunk map[string]any
if json.Unmarshal(out, &chunk) == nil && sanitizeToolCallDeltaNulls(chunk) {
out, _ = json.Marshal(chunk)
}
}
_, _ = fmt.Fprintf(w, "data: %s\n\n", out)
if flusher != nil {
flusher.Flush()
}
}
for s.Scan() {
line := strings.TrimRight(s.Text(), "\r")
if line == "" {
flush()
continue
}
if strings.HasPrefix(line, "data:") {
collected = append(collected, strings.TrimSpace(strings.TrimPrefix(line, "data:")))
}
}
flush()
}

// sanitizeToolCallDeltaNulls removes id and function.name keys whose values
// are nil/empty from tool_calls deltas. Returns true if anything changed.
func sanitizeToolCallDeltaNulls(chunk map[string]any) bool {
choices, _ := chunk["choices"].([]any)
changed := false
for _, c := range choices {
choice, _ := c.(map[string]any)
if choice == nil {
continue
}
delta, _ := choice["delta"].(map[string]any)
if delta == nil {
continue
}
calls, _ := delta["tool_calls"].([]any)
for _, ct := range calls {
call, _ := ct.(map[string]any)
if call == nil {
continue
}
if id, ok := call["id"]; ok {
if s, isStr := id.(string); isStr && s == "" {
delete(call, "id")
changed = true
} else if id == nil {
delete(call, "id")
changed = true
}
}
fn, _ := call["function"].(map[string]any)
if fn == nil {
continue
}
if name, ok := fn["name"]; ok {
if s, isStr := name.(string); isStr && s == "" {
delete(fn, "name")
changed = true
} else if name == nil {
delete(fn, "name")
changed = true
}
}
}
}
return changed
}

func proxyResponses(w http.ResponseWriter, r *http.Request, cfg Config) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
Expand Down
62 changes: 62 additions & 0 deletions cmd/ocgo/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1140,3 +1140,65 @@ func TestSanitizeRawChatToolMessagesDropsLateToolMessage(t *testing.T) {
t.Fatalf("expected assistant after placeholder, got %+v", roles[2])
}
}

func TestSanitizeToolCallDeltaNullsDropsNullIDAndName(t *testing.T) {
var chunk map[string]any
data := []byte(`{"choices":[{"delta":{"tool_calls":[{"index":0,"id":null,"type":"function","function":{"name":null,"arguments":"{\""}}]}}]}`)
if err := json.Unmarshal(data, &chunk); err != nil {
t.Fatal(err)
}
if !sanitizeToolCallDeltaNulls(chunk) {
t.Fatal("expected nulls to be removed")
}
choices := chunk["choices"].([]any)
choice := choices[0].(map[string]any)
delta := choice["delta"].(map[string]any)
calls := delta["tool_calls"].([]any)
call := calls[0].(map[string]any)
if _, ok := call["id"]; ok {
t.Fatalf("id should be removed, got %+v", call)
}
fn := call["function"].(map[string]any)
if _, ok := fn["name"]; ok {
t.Fatalf("name should be removed, got %+v", fn)
}
if args, _ := fn["arguments"].(string); args != `{"` {
t.Fatalf("arguments must be preserved, got %q", args)
}
}

func TestSanitizeToolCallDeltaNullsKeepsRealValues(t *testing.T) {
var chunk map[string]any
data := []byte(`{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"bash","arguments":""}}]}}]}`)
if err := json.Unmarshal(data, &chunk); err != nil {
t.Fatal(err)
}
if sanitizeToolCallDeltaNulls(chunk) {
t.Fatal("expected no changes for populated values")
}
}

func TestStreamChatCompletionsPassthroughPreservesToolIdentityAndDONE(t *testing.T) {
body := strings.NewReader(strings.Join([]string{
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"bash","arguments":""}}]}}]}`,
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":null,"type":"function","function":{"name":null,"arguments":"{\""}}]}}]}`,
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":null,"type":"function","function":{"name":null,"arguments":"ls\"}"}}]}}]}`,
`data: [DONE]`,
``,
}, "\n\n"))
w := httptest.NewRecorder()
streamChatCompletionsPassthrough(w, body)
out := w.Body.String()
if !strings.Contains(out, `data: [DONE]`) {
t.Fatalf("DONE must be forwarded, got:\n%s", out)
}
if strings.Count(out, `"name":"bash"`) != 1 {
t.Fatalf("tool name must appear exactly once, got:\n%s", out)
}
if strings.Contains(out, `"name":null`) || strings.Contains(out, `"id":null`) {
t.Fatalf("null id/name must be dropped, got:\n%s", out)
}
if !strings.Contains(out, `"arguments":"ls\"}"`) {
t.Fatalf("arguments must be preserved, got:\n%s", out)
}
}