feat: 支持Anthropic API协议 | support Anthropic API protocol

- 添加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: zgdmemail@gmail.com
This commit is contained in:
Deadwalk
2025-09-28 11:13:55 +08:00
parent 8df4a2670b
commit 008ffe4662
12 changed files with 517 additions and 24 deletions

View File

@@ -11,6 +11,7 @@ import (
"github.com/songquanpeng/one-api/relay/adaptor"
"github.com/songquanpeng/one-api/relay/meta"
"github.com/songquanpeng/one-api/relay/model"
"github.com/songquanpeng/one-api/relay/relaymode"
)
type Adaptor struct {
@@ -21,7 +22,15 @@ func (a *Adaptor) Init(meta *meta.Meta) {
}
func (a *Adaptor) GetRequestURL(meta *meta.Meta) (string, error) {
return fmt.Sprintf("%s/v1/messages", meta.BaseURL), nil
// For native Anthropic API
if strings.Contains(meta.BaseURL, "api.anthropic.com") {
return fmt.Sprintf("%s/v1/messages", meta.BaseURL), nil
}
// For third-party providers supporting Anthropic protocol (like DeepSeek)
// They typically expose the endpoint at /anthropic/v1/messages
baseURL := strings.TrimSuffix(meta.BaseURL, "/")
return fmt.Sprintf("%s/anthropic/v1/messages", baseURL), nil
}
func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Request, meta *meta.Meta) error {
@@ -47,6 +56,15 @@ func (a *Adaptor) ConvertRequest(c *gin.Context, relayMode int, request *model.G
if request == nil {
return nil, errors.New("request is nil")
}
// For native Anthropic protocol requests, return the request as-is (no conversion needed)
if relayMode == relaymode.AnthropicMessages {
// The request should already be in Anthropic format, so we pass it through
// This will be handled by the caller which already has the anthropic request
return request, nil
}
// For OpenAI to Anthropic conversion (existing functionality)
return ConvertRequest(*request), nil
}
@@ -62,6 +80,17 @@ func (a *Adaptor) DoRequest(c *gin.Context, meta *meta.Meta, requestBody io.Read
}
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, meta *meta.Meta) (usage *model.Usage, err *model.ErrorWithStatusCode) {
// For native Anthropic protocol requests, handle response directly without conversion
if meta.Mode == relaymode.AnthropicMessages {
if meta.IsStream {
err, usage = DirectStreamHandler(c, resp)
} else {
err, usage = DirectHandler(c, resp, meta.PromptTokens, meta.ActualModelName)
}
return
}
// For OpenAI to Anthropic conversion (existing functionality)
if meta.IsStream {
err, usage = StreamHandler(c, resp)
} else {