| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414 |
- package common
- import (
- "errors"
- "one-api/common"
- "one-api/constant"
- "one-api/dto"
- relayconstant "one-api/relay/constant"
- "one-api/types"
- "strings"
- "time"
- "github.com/gin-gonic/gin"
- "github.com/gorilla/websocket"
- )
- type ThinkingContentInfo struct {
- IsFirstThinkingContent bool
- SendLastThinkingContent bool
- HasSentThinkingContent bool
- }
- const (
- LastMessageTypeNone = "none"
- LastMessageTypeText = "text"
- LastMessageTypeTools = "tools"
- LastMessageTypeThinking = "thinking"
- )
- type ClaudeConvertInfo struct {
- LastMessagesType string
- Index int
- Usage *dto.Usage
- FinishReason string
- Done bool
- }
- type RerankerInfo struct {
- Documents []any
- ReturnDocuments bool
- }
- type BuildInToolInfo struct {
- ToolName string
- CallCount int
- SearchContextSize string
- }
- type ResponsesUsageInfo struct {
- BuiltInTools map[string]*BuildInToolInfo
- }
- type ChannelMeta struct {
- ChannelType int
- ChannelId int
- ChannelIsMultiKey bool
- ChannelMultiKeyIndex int
- ChannelBaseUrl string
- ApiType int
- ApiVersion string
- ApiKey string
- Organization string
- ChannelCreateTime int64
- ParamOverride map[string]interface{}
- ChannelSetting dto.ChannelSettings
- ChannelOtherSettings dto.ChannelOtherSettings
- UpstreamModelName string
- IsModelMapped bool
- SupportStreamOptions bool // 是否支持流式选项
- }
- type RelayInfo struct {
- TokenId int
- TokenKey string
- UserId int
- UsingGroup string // 使用的分组
- UserGroup string // 用户所在分组
- TokenUnlimited bool
- StartTime time.Time
- FirstResponseTime time.Time
- isFirstResponse bool
- //SendLastReasoningResponse bool
- IsStream bool
- IsGeminiBatchEmbedding bool
- IsPlayground bool
- UsePrice bool
- RelayMode int
- OriginModelName string
- //RecodeModelName string
- RequestURLPath string
- PromptTokens int
- //SupportStreamOptions bool
- ShouldIncludeUsage bool
- DisablePing bool // 是否禁止向下游发送自定义 Ping
- ClientWs *websocket.Conn
- TargetWs *websocket.Conn
- InputAudioFormat string
- OutputAudioFormat string
- RealtimeTools []dto.RealTimeTool
- IsFirstRequest bool
- AudioUsage bool
- ReasoningEffort string
- UserSetting dto.UserSetting
- UserEmail string
- UserQuota int
- RelayFormat types.RelayFormat
- SendResponseCount int
- FinalPreConsumedQuota int // 最终预消耗的配额
- PriceData types.PriceData
- Request dto.Request
- ThinkingContentInfo
- *ClaudeConvertInfo
- *RerankerInfo
- *ResponsesUsageInfo
- *ChannelMeta
- }
- func (info *RelayInfo) InitChannelMeta(c *gin.Context) {
- channelType := common.GetContextKeyInt(c, constant.ContextKeyChannelType)
- paramOverride := common.GetContextKeyStringMap(c, constant.ContextKeyChannelParamOverride)
- apiType, _ := common.ChannelType2APIType(channelType)
- channelMeta := &ChannelMeta{
- ChannelType: channelType,
- ChannelId: common.GetContextKeyInt(c, constant.ContextKeyChannelId),
- ChannelIsMultiKey: common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey),
- ChannelMultiKeyIndex: common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex),
- ChannelBaseUrl: common.GetContextKeyString(c, constant.ContextKeyChannelBaseUrl),
- ApiType: apiType,
- ApiVersion: c.GetString("api_version"),
- ApiKey: common.GetContextKeyString(c, constant.ContextKeyChannelKey),
- Organization: c.GetString("channel_organization"),
- ChannelCreateTime: c.GetInt64("channel_create_time"),
- ParamOverride: paramOverride,
- UpstreamModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
- IsModelMapped: false,
- SupportStreamOptions: false,
- }
- channelSetting, ok := common.GetContextKeyType[dto.ChannelSettings](c, constant.ContextKeyChannelSetting)
- if ok {
- channelMeta.ChannelSetting = channelSetting
- }
- channelOtherSettings, ok := common.GetContextKeyType[dto.ChannelOtherSettings](c, constant.ContextKeyChannelOtherSetting)
- if ok {
- channelMeta.ChannelOtherSettings = channelOtherSettings
- }
- if streamSupportedChannels[channelMeta.ChannelType] {
- channelMeta.SupportStreamOptions = true
- }
- info.ChannelMeta = channelMeta
- }
- // 定义支持流式选项的通道类型
- var streamSupportedChannels = map[int]bool{
- constant.ChannelTypeOpenAI: true,
- constant.ChannelTypeAnthropic: true,
- constant.ChannelTypeAws: true,
- constant.ChannelTypeGemini: true,
- constant.ChannelCloudflare: true,
- constant.ChannelTypeAzure: true,
- constant.ChannelTypeVolcEngine: true,
- constant.ChannelTypeOllama: true,
- constant.ChannelTypeXai: true,
- constant.ChannelTypeDeepSeek: true,
- constant.ChannelTypeBaiduV2: true,
- }
- func GenRelayInfoWs(c *gin.Context, ws *websocket.Conn) *RelayInfo {
- info := genBaseRelayInfo(c, nil)
- info.RelayFormat = types.RelayFormatOpenAIRealtime
- info.ClientWs = ws
- info.InputAudioFormat = "pcm16"
- info.OutputAudioFormat = "pcm16"
- info.IsFirstRequest = true
- return info
- }
- func GenRelayInfoClaude(c *gin.Context, request dto.Request) *RelayInfo {
- info := genBaseRelayInfo(c, request)
- info.RelayFormat = types.RelayFormatClaude
- info.ShouldIncludeUsage = false
- info.ClaudeConvertInfo = &ClaudeConvertInfo{
- LastMessagesType: LastMessageTypeNone,
- }
- return info
- }
- func GenRelayInfoRerank(c *gin.Context, request *dto.RerankRequest) *RelayInfo {
- info := genBaseRelayInfo(c, request)
- info.RelayMode = relayconstant.RelayModeRerank
- info.RelayFormat = types.RelayFormatRerank
- info.RerankerInfo = &RerankerInfo{
- Documents: request.Documents,
- ReturnDocuments: request.GetReturnDocuments(),
- }
- return info
- }
- func GenRelayInfoOpenAIAudio(c *gin.Context, request dto.Request) *RelayInfo {
- info := genBaseRelayInfo(c, request)
- info.RelayFormat = types.RelayFormatOpenAIAudio
- return info
- }
- func GenRelayInfoEmbedding(c *gin.Context, request dto.Request) *RelayInfo {
- info := genBaseRelayInfo(c, request)
- info.RelayFormat = types.RelayFormatEmbedding
- return info
- }
- func GenRelayInfoResponses(c *gin.Context, request *dto.OpenAIResponsesRequest) *RelayInfo {
- info := genBaseRelayInfo(c, request)
- info.RelayMode = relayconstant.RelayModeResponses
- info.RelayFormat = types.RelayFormatOpenAIResponses
- info.SupportStreamOptions = false
- info.ResponsesUsageInfo = &ResponsesUsageInfo{
- BuiltInTools: make(map[string]*BuildInToolInfo),
- }
- if len(request.Tools) > 0 {
- for _, tool := range request.Tools {
- toolType := common.Interface2String(tool["type"])
- info.ResponsesUsageInfo.BuiltInTools[toolType] = &BuildInToolInfo{
- ToolName: toolType,
- CallCount: 0,
- }
- switch toolType {
- case dto.BuildInToolWebSearchPreview:
- searchContextSize := common.Interface2String(tool["search_context_size"])
- if searchContextSize == "" {
- searchContextSize = "medium"
- }
- info.ResponsesUsageInfo.BuiltInTools[toolType].SearchContextSize = searchContextSize
- }
- }
- }
- return info
- }
- func GenRelayInfoGemini(c *gin.Context, request dto.Request) *RelayInfo {
- info := genBaseRelayInfo(c, request)
- info.RelayFormat = types.RelayFormatGemini
- info.ShouldIncludeUsage = false
- return info
- }
- func GenRelayInfoImage(c *gin.Context, request dto.Request) *RelayInfo {
- info := genBaseRelayInfo(c, request)
- info.RelayFormat = types.RelayFormatOpenAIImage
- return info
- }
- func GenRelayInfoOpenAI(c *gin.Context, request dto.Request) *RelayInfo {
- info := genBaseRelayInfo(c, request)
- info.RelayFormat = types.RelayFormatOpenAI
- return info
- }
- func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo {
- //channelType := common.GetContextKeyInt(c, constant.ContextKeyChannelType)
- //channelId := common.GetContextKeyInt(c, constant.ContextKeyChannelId)
- //paramOverride := common.GetContextKeyStringMap(c, constant.ContextKeyChannelParamOverride)
- startTime := common.GetContextKeyTime(c, constant.ContextKeyRequestStartTime)
- if startTime.IsZero() {
- startTime = time.Now()
- }
- isStream := false
- if request != nil {
- isStream = request.IsStream(c)
- }
- // firstResponseTime = time.Now() - 1 second
- info := &RelayInfo{
- Request: request,
- UserId: common.GetContextKeyInt(c, constant.ContextKeyUserId),
- UsingGroup: common.GetContextKeyString(c, constant.ContextKeyUsingGroup),
- UserGroup: common.GetContextKeyString(c, constant.ContextKeyUserGroup),
- UserQuota: common.GetContextKeyInt(c, constant.ContextKeyUserQuota),
- UserEmail: common.GetContextKeyString(c, constant.ContextKeyUserEmail),
- OriginModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
- PromptTokens: common.GetContextKeyInt(c, constant.ContextKeyPromptTokens),
- TokenId: common.GetContextKeyInt(c, constant.ContextKeyTokenId),
- TokenKey: common.GetContextKeyString(c, constant.ContextKeyTokenKey),
- TokenUnlimited: common.GetContextKeyBool(c, constant.ContextKeyTokenUnlimited),
- isFirstResponse: true,
- RelayMode: relayconstant.Path2RelayMode(c.Request.URL.Path),
- RequestURLPath: c.Request.URL.String(),
- IsStream: isStream,
- StartTime: startTime,
- FirstResponseTime: startTime.Add(-time.Second),
- ThinkingContentInfo: ThinkingContentInfo{
- IsFirstThinkingContent: true,
- SendLastThinkingContent: false,
- },
- }
- if strings.HasPrefix(c.Request.URL.Path, "/pg") {
- info.IsPlayground = true
- info.RequestURLPath = strings.TrimPrefix(info.RequestURLPath, "/pg")
- info.RequestURLPath = "/v1" + info.RequestURLPath
- }
- userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting)
- if ok {
- info.UserSetting = userSetting
- }
- return info
- }
- func GenRelayInfo(c *gin.Context, relayFormat types.RelayFormat, request dto.Request, ws *websocket.Conn) (*RelayInfo, error) {
- switch relayFormat {
- case types.RelayFormatOpenAI:
- return GenRelayInfoOpenAI(c, request), nil
- case types.RelayFormatOpenAIAudio:
- return GenRelayInfoOpenAIAudio(c, request), nil
- case types.RelayFormatOpenAIImage:
- return GenRelayInfoImage(c, request), nil
- case types.RelayFormatOpenAIRealtime:
- return GenRelayInfoWs(c, ws), nil
- case types.RelayFormatClaude:
- return GenRelayInfoClaude(c, request), nil
- case types.RelayFormatRerank:
- if request, ok := request.(*dto.RerankRequest); ok {
- return GenRelayInfoRerank(c, request), nil
- }
- return nil, errors.New("request is not a RerankRequest")
- case types.RelayFormatGemini:
- return GenRelayInfoGemini(c, request), nil
- case types.RelayFormatEmbedding:
- return GenRelayInfoEmbedding(c, request), nil
- case types.RelayFormatOpenAIResponses:
- if request, ok := request.(*dto.OpenAIResponsesRequest); ok {
- return GenRelayInfoResponses(c, request), nil
- }
- return nil, errors.New("request is not a OpenAIResponsesRequest")
- case types.RelayFormatTask:
- return genBaseRelayInfo(c, nil), nil
- case types.RelayFormatMjProxy:
- return genBaseRelayInfo(c, nil), nil
- default:
- return nil, errors.New("invalid relay format")
- }
- }
- func (info *RelayInfo) SetPromptTokens(promptTokens int) {
- info.PromptTokens = promptTokens
- }
- func (info *RelayInfo) SetFirstResponseTime() {
- if info.isFirstResponse {
- info.FirstResponseTime = time.Now()
- info.isFirstResponse = false
- }
- }
- func (info *RelayInfo) HasSendResponse() bool {
- return info.FirstResponseTime.After(info.StartTime)
- }
- type TaskRelayInfo struct {
- *RelayInfo
- Action string
- OriginTaskID string
- ConsumeQuota bool
- }
- func GenTaskRelayInfo(c *gin.Context) (*TaskRelayInfo, error) {
- relayInfo, err := GenRelayInfo(c, types.RelayFormatTask, nil, nil)
- if err != nil {
- return nil, err
- }
- info := &TaskRelayInfo{
- RelayInfo: relayInfo,
- }
- return info, nil
- }
- type TaskSubmitReq struct {
- Prompt string `json:"prompt"`
- Model string `json:"model,omitempty"`
- Mode string `json:"mode,omitempty"`
- Image string `json:"image,omitempty"`
- Size string `json:"size,omitempty"`
- Duration int `json:"duration,omitempty"`
- Metadata map[string]interface{} `json:"metadata,omitempty"`
- }
- type TaskInfo struct {
- Code int `json:"code"`
- TaskID string `json:"task_id"`
- Status string `json:"status"`
- Reason string `json:"reason,omitempty"`
- Url string `json:"url,omitempty"`
- Progress string `json:"progress,omitempty"`
- }
|