1
0
Files
nex/backend/internal/protocol/openai/adapter.go
lanyuanxiaoyao 915b004924 feat: 初始化 AI Gateway 项目
实现支持 OpenAI 和 Anthropic 双协议的统一大模型 API 网关 MVP 版本,包含:
- OpenAI 和 Anthropic 协议代理
- 供应商和模型管理
- 用量统计
- 前端配置界面
2026-04-15 16:53:28 +08:00

87 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package openai
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// Adapter OpenAI 协议适配器(透传)
type Adapter struct{}
// NewAdapter 创建 OpenAI 适配器
func NewAdapter() *Adapter {
return &Adapter{}
}
// PrepareRequest 准备发送给供应商的请求(透传)
func (a *Adapter) PrepareRequest(req *ChatCompletionRequest, apiKey, baseURL string) (*http.Request, error) {
// 序列化请求体
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
// 调试日志:打印请求体
fmt.Printf("[DEBUG] 请求Body: %s\n", string(body))
// 创建 HTTP 请求
// baseURL 已包含版本路径(如 /v1 或 /v4只需添加端点路径
httpReq, err := http.NewRequest("POST", baseURL+"/chat/completions", bytes.NewReader(body))
if err != nil {
return nil, err
}
// 设置请求头
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+apiKey)
return httpReq, nil
}
// ParseResponse 解析供应商响应(透传)
func (a *Adapter) ParseResponse(resp *http.Response) (*ChatCompletionResponse, error) {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result ChatCompletionResponse
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// ParseErrorResponse 解析错误响应
func (a *Adapter) ParseErrorResponse(resp *http.Response) (*ErrorResponse, error) {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result ErrorResponse
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// ParseStreamChunk 解析流式响应块
func (a *Adapter) ParseStreamChunk(data []byte) (*StreamChunk, error) {
var chunk StreamChunk
err := json.Unmarshal(data, &chunk)
if err != nil {
return nil, err
}
return &chunk, nil
}