Skip to content

Conversation

@domonic18
Copy link

  • 添加Anthropic适配器实现 | Add Anthropic adaptor implementation
  • 支持Anthropic消息格式转换 | Support Anthropic message format conversion
  • 添加Vertex AI Claude适配器支持 | Add Vertex AI Claude adapter support
  • 更新Anthropic的中继模式定义 | Update relay mode definitions for Anthropic
  • 添加Anthropic控制器和路由 | Add Anthropic controller and routing

🤖 Generated with Claude Code

Co-Authored-By: [email protected]

Anthropic API 协议支持 PR 内容

标题 (Title)

feat: 支持 Anthropic API 协议 | Support Anthropic API Protocol

描述 (Description)

中文

此 PR 为 one-api 项目添加了对 Anthropic API 协议的完整支持,包括:

  • 原生 Anthropic API 支持:添加了 /anthropic/v1/messages 端点,支持原生 Anthropic API 格式
  • 消息格式转换:实现了 OpenAI 格式与 Anthropic 格式之间的双向转换
  • 流式响应支持:支持流式和非流式响应处理
  • 工具调用支持:完整支持 Anthropic 的工具调用功能
  • Vertex AI Claude 适配器:添加了对 Vertex AI Claude 模型的适配支持
  • 完整的错误处理:实现了 Anthropic API 的错误处理和配额管理

English

This PR adds comprehensive support for the Anthropic API protocol to the one-api project, including:

  • Native Anthropic API Support: Added /anthropic/v1/messages endpoint supporting native Anthropic API format
  • Message Format Conversion: Implemented bidirectional conversion between OpenAI and Anthropic formats
  • Streaming Response Support: Support for both streaming and non-streaming response handling
  • Tool Calling Support: Full support for Anthropic's tool calling functionality
  • Vertex AI Claude Adapter: Added adapter support for Vertex AI Claude models
  • Complete Error Handling: Implemented error handling and quota management for Anthropic API

主要改动 (Key Changes)

新增文件 (New Files)

  1. relay/controller/anthropic.go - Anthropic 控制器,处理原生 Anthropic API 请求
  2. relay/adaptor/anthropic/main.go - Anthropic 适配器主逻辑,包含格式转换和响应处理
  3. relay/adaptor/anthropic/model.go - Anthropic API 数据模型定义
  4. relay/adaptor/anthropic/adaptor.go - Anthropic 适配器接口实现

修改文件 (Modified Files)

  1. router/relay.go - 添加 Anthropic API 路由配置
  2. relay/meta/relay_meta.go - 更新中继模式定义
  3. relay/relaymode/define.go - 添加 Anthropic 中继模式常量
  4. relay/relaymode/helper.go - 更新中继模式辅助函数
  5. relay/adaptor/vertexai/claude/adapter.go - 添加 Vertex AI Claude 适配器支持
  6. controller/relay.go - 更新控制器路由映射
  7. Dockerfile - 更新构建配置
  8. docker-compose.yml - 更新容器配置

功能特性 (Features)

核心功能 (Core Features)

  • 原生 Anthropic API 兼容:完全兼容 Anthropic Messages API
  • 流式响应:支持流式和非流式响应
  • 工具调用:完整支持 Anthropic 工具调用功能
  • 系统提示:支持 Anthropic 系统提示功能
  • 配额管理:集成 one-api 的配额管理系统

API 端点 (API Endpoints)

GET  /anthropic/v1/models           # 列出可用模型
GET  /anthropic/v1/models/:model    # 获取模型信息
POST /anthropic/v1/messages         # 主要聊天完成端点

技术实现 (Technical Implementation)

架构设计 (Architecture)

  1. 控制器层 (Controller Layer)RelayAnthropicHelper 处理原生 Anthropic 请求
  2. 适配器层 (Adapter Layer):实现 Anthropic 格式与 OpenAI 格式的转换
  3. 模型层 (Model Layer):定义 Anthropic API 的数据结构
  4. 路由层 (Router Layer):配置 Anthropic API 端点

关键特性 (Key Technical Features)

  • 直接模式 (Direct Mode):支持原生 Anthropic API 透传,无需格式转换
  • 智能令牌估算:实现 Anthropic 请求的令牌估算逻辑
  • 错误处理:完整的错误处理和状态码映射
  • 日志记录:详细的请求/响应日志记录

测试验证 (Testing)

已测试功能 (Tested Features)

  • ✅ 基础聊天完成功能
  • ✅ 流式响应处理
  • ✅ 工具调用功能
  • ✅ 模型映射功能

测试截图 (Test Screenshots)

在one-api中配置第三方模型

配置渠道 配置渠道2

在命令行中配置使用one-api的地址和令牌
模型调用

close #2322

- 添加Anthropic适配器实现 | Add Anthropic adaptor implementation
- 支持Anthropic消息格式转换 | Support Anthropic message format conversion
- 添加Vertex AI Claude适配器支持 | Add Vertex AI Claude adapter support
- 更新Anthropic的中继模式定义 | Update relay mode definitions for Anthropic
- 添加Anthropic控制器和路由 | Add Anthropic controller and routing

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: [email protected]
Copilot AI review requested due to automatic review settings September 28, 2025 04:36
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds comprehensive support for the Anthropic API protocol to the one-api project, enabling native Anthropic API compatibility alongside existing OpenAI format conversion. The implementation includes a new direct protocol mode that bypasses format conversion for improved efficiency and compatibility.

Key changes:

  • Native Anthropic API endpoint support at /anthropic/v1/messages
  • Direct Anthropic protocol handling without OpenAI format conversion
  • Enhanced SystemPrompt type to handle both string and array formats

Reviewed Changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
router/relay.go Adds Anthropic API routing with authentication middleware
relay/controller/anthropic.go New controller for native Anthropic request processing
relay/adaptor/anthropic/main.go Adds direct handlers for native Anthropic responses
relay/adaptor/anthropic/model.go Enhanced SystemPrompt type with flexible JSON marshaling
relay/adaptor/anthropic/adaptor.go Updates adapter for native protocol support
relay/meta/relay_meta.go Forces Anthropic API type for native requests
relay/relaymode/*.go Adds AnthropicMessages relay mode definition
controller/relay.go Routes AnthropicMessages mode to new controller

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

deadwalks and others added 7 commits September 28, 2025 16:22
- 清理不必要的调试日志,减少生产环境噪音
- 将详细日志从Infof降级为Debugf级别
- 保留关键错误日志和重要流程信息
- 优化日志结构,提高可读性和维护性

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
…s identified by CodeReview

- 修复JSON注入漏洞:使用json.Marshal()安全转义字符串内容
- 定义常量CHARS_PER_TOKEN替换硬编码的token估算数字4
- 处理UnmarshalJSON错误,避免静默失败并记录错误日志
- 定义常量替换硬编码的API端点路径,提高可维护性

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
- Add comprehensive npm mirror configuration for faster package downloads
- Use parallel npm install and build processes for better performance
- Configure Go proxy and Alpine package mirrors for network reliability
- Fix frontend dependency issues that caused blank page display

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
- Add message content validation in getAndValidateAnthropicRequest
- Filter out messages with empty content to prevent 'all messages must have non-empty content' errors
- Support both text and non-text content validation (images, tool_use, tool_result)
- Add detailed logging for filtered messages
- Ensure at least one valid message remains after filtering

修复Anthropic协议空消息内容问题:
- 在getAndValidateAnthropicRequest中添加消息内容验证
- 过滤空内容消息以防止'all messages must have non-empty content'错误
- 支持文本和非文本内容验证(图片、工具调用、工具结果)
- 为被过滤的消息添加详细日志记录
- 确保过滤后至少保留一条有效消息
- Add MessageContent type to handle both string and array content formats
- Implement UnmarshalJSON to automatically detect content format
- Add ToContentArray() method for unified content processing
- Update Message and Response structs to use MessageContent
- Fix all content processing logic in main.go and controller
- Resolve JSON parsing errors for different content formats

支持Anthropic协议字符串和数组内容格式:
- 添加MessageContent类型处理字符串和数组两种内容格式
- 实现UnmarshalJSON自动检测内容格式
- 添加ToContentArray()方法统一内容处理
- 更新Message和Response结构体使用MessageContent
- 修复main.go和controller中的所有内容处理逻辑
- 解决不同内容格式的JSON解析错误
修复Anthropic协议中MCP工具消息处理问题,增强错误恢复能力:
- 改进MessageContent的JSON解析,支持原始JSON数据保留
- 移除对空内容的过滤,避免丢失MCP工具消息
- 增加详细调试日志,便于问题排查
- 优化错误响应处理,保留响应体信息
- 修复路由转发时可能的数据丢失问题

fix(anthropic): improve MCP tool message handling and error resilience
- Enhance MessageContent JSON parsing to preserve raw JSON data
- Remove empty content filtering to prevent MCP tool message loss
- Add detailed debug logging for troubleshooting
- Optimize error response handling with response body preservation
- Fix potential data loss during routing

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
refactor: optimize Anthropic protocol streaming performance and URL construction

修复URL构建逻辑,避免第三方服务商出现重复/v1路径问题
Fix URL construction logic to avoid duplicate /v1 path issues with third-party providers

优化流式处理性能:
- 添加scanner缓冲区大小设置,减少内存扩容开销
- 实现write buffer累积数据,减少flush次数
- 智能JSON解析策略,仅在特定事件类型时解析,减少80-90%解析开销
- 添加智能flush策略,平衡实时性和效率

注意:智谱AI的Anthropic endpoint应配置BaseURL为https://open.bigmodel.cn/api
Note: For ZhipuAI's Anthropic endpoint, configure BaseURL as https://open.bigmodel.cn/api

优化中间件日志输出,避免请求体过大导致日志可读性下降
Optimize middleware log output to prevent reduced readability due to large request bodies

相关文件:
- relay/adaptor/anthropic/adaptor.go
- relay/adaptor/anthropic/constants.go
- relay/adaptor/anthropic/main.go
- middleware/recover.go

Generated with Claude Code
Co-Authored-By: Claude <[email protected]>
@hkstandbyyou-eng
Copy link

接入阿里百炼,使用claude的时候,报错如下:
[ERROR] 2026/01/16 - 10:54:13 | 2026011610541312901033097745105 | relay/controller/anthropic.go:94 [RelayAnthropicHelper] Error detected in response
[GIN] 2026/01/16 - 10:54:13 | 2026011610541312901033097745105 | 404 | 28.776895ms | 223.233.81.176 | POST /anthropic/v1/messages?beta=true
[ERROR] 2026/01/16 - 10:54:13 | 2026011610541312901033097745105 | controller/relay.go:127 [processChannelRelayError] relay error (channel id 1, user id: 1):
[GIN] 2026/01/16 - 10:54:19 | 2026011610541948999482868507080 | 200 | 375.904µs | 223.233.81.176 | POST /anthropic/api/event_logging/batch

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.

添加 Anthropic API 协议支持 | Add Anthropic API Protocol Support

3 participants