Skip to content

feat: 改进Claude响应转OpenAI响应 - #1761

Merged
creamlike1024 merged 1 commit into
alphafrom
openaitoclaude-improve
Sep 7, 2025
Merged

creamlike1024 merged 1 commit into
alphafrom
openaitoclaude-improve

Conversation

@creamlike1024

@creamlike1024 creamlike1024 commented Sep 7, 2025 •

Copy link
Copy Markdown
Collaborator
  • 映射 claude stop reason "max_tokens" 为 openai 的 finish_reason "length"
  • 流模式起始块发送首段文本

Summary by CodeRabbit

  • Bug Fixes
    • Corrected finish reason mapping for token limits to report “length” (improves OpenAI-compatible client behavior).
    • Improved streaming to only emit initial content when a valid text block is available, reducing empty or misleading first tokens.
  • Refactor
    • Streamlined content handling for more predictable text vs. tool-call streaming without changing public APIs.

…start type

- convert claude stop reason "max_tokens" to openai "length"
- send content_block_start content text delta
@coderabbitai

coderabbitai Bot commented Sep 7, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Updates Claude-to-OpenAI mapping: converts Claude stop reason "max_tokens" to "length". Adjusts streaming logic to emit initial content only for explicit text blocks during content_block_start events; continues handling for tool_use. No exported APIs changed.

Changes

Cohort / File(s) Summary
Claude relay mapping and stream handling
relay/channel/claude/relay-claude.go
- Map Claude "max_tokens" → OpenAI "length" in stop-reason converter
- In StreamResponseClaude2OpenAI, on content_block_start emit text only when Type=="text" and Text present; keep tool_use handling; avoid emitting unspecified content
- Added inline comment (Chinese); no API signature changes

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client as Client (OpenAI-compatible)
  participant Relay as Relay (Claude channel)
  participant Claude as Claude API (stream)

  Client->>Relay: Start chat/completions (stream)
  Relay->>Claude: Send request
  Claude-->>Relay: stream: content_block_start
  alt Content block is text with content
    Relay->>Client: delta: content (text segment)
  else Content block is tool_use
    Relay->>Client: delta: tool_calls (init)
  else Other/empty
    Relay->>Client: (no content emitted)
  end
  Claude-->>Relay: stream: content / tool data …
  Relay->>Client: forward mapped deltas

  Claude-->>Relay: stream end (stop_reason)
  Note over Relay: Map stop reasons:<br/>max_tokens → length<br/>stop_sequence/end_turn → stop<br/>tool_use → tool_calls
  Relay->>Client: final message + mapped finish_reason
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

I twitch my ears at streaming light,
Text blocks hop in, crisp and bright;
Tools queue neatly, paws in line,
Max tokens now say “length” — so fine.
In relay burrows, signals flow,
A rabbit nods: on with the show! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch openaitoclaude-improve

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
relay/channel/claude/relay-claude.go (1)

599-603: Also append the initial text to ResponseText during content_block_start to keep usage accounting correct.

Without this, ResponseText2Usage undercounts when upstream usage is incomplete.

-		} else if claudeResponse.Type == "content_block_start" {
-		} else {
+		} else if claudeResponse.Type == "content_block_start" {
+			if claudeResponse.ContentBlock != nil &&
+				claudeResponse.ContentBlock.Type == "text" &&
+				claudeResponse.ContentBlock.Text != nil {
+				claudeInfo.ResponseText.WriteString(*claudeResponse.ContentBlock.Text)
+			}
+		} else {
🧹 Nitpick comments (3)
relay/channel/claude/relay-claude.go (3)

35-35: Mapping "max_tokens" → "length" is correct; consider future-proofing synonyms.

Anthropic may also emit "max_output_tokens". Map both to "length" to avoid regressions.

-	case "max_tokens":
-		return "length"
+	case "max_tokens", "max_output_tokens":
+		return "length"

469-472: Guard against nil StopReason in message_delta to avoid a rare panic.

Be defensive in case upstream omits stop_reason.

-		} else if claudeResponse.Type == "message_delta" {
-			finishReason := stopReasonClaude2OpenAI(*claudeResponse.Delta.StopReason)
-			if finishReason != "null" {
-				choice.FinishReason = &finishReason
-			}
+		} else if claudeResponse.Type == "message_delta" {
+			if claudeResponse.Delta != nil && claudeResponse.Delta.StopReason != nil {
+				finishReason := stopReasonClaude2OpenAI(*claudeResponse.Delta.StopReason)
+				if finishReason != "null" {
+					choice.FinishReason = &finishReason
+				}
+			}

452-458: Tool-call streaming emits new entries instead of updating the prior one.

OpenAI-style SSE typically updates the same tool_calls[index] arguments over time. Appending a fresh ToolCallResponse each delta can confuse clients that expect in-place growth. Consider tracking the current tool call per fcIdx and updating its Arguments string incrementally rather than pushing new slice elements each time.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7527eb and b29efbd.

📒 Files selected for processing (1)
  • relay/channel/claude/relay-claude.go (2 hunks)
🔇 Additional comments (1)
relay/channel/claude/relay-claude.go (1)

429-433: Streaming first text chunk on content_block_start — good improvement.

LGTM for emitting the initial text when present; aligns with OpenAI delta semantics. See my follow-up to also record this in ResponseText for accurate usage fallbacks.

@creamlike1024
creamlike1024 merged commit 1c12c73 into alpha Sep 7, 2025
@Calcium-Ion
Calcium-Ion deleted the openaitoclaude-improve branch October 11, 2025 03:06
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
…mprove

feat: 改进Claude响应转OpenAI响应
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
…mprove

feat: 改进Claude响应转OpenAI响应
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
…mprove

feat: 改进Claude响应转OpenAI响应
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant