relay_info.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. package common
  2. import (
  3. "one-api/common"
  4. "one-api/constant"
  5. "one-api/dto"
  6. relayconstant "one-api/relay/constant"
  7. "strings"
  8. "time"
  9. "github.com/gin-gonic/gin"
  10. "github.com/gorilla/websocket"
  11. )
  12. type ThinkingContentInfo struct {
  13. IsFirstThinkingContent bool
  14. SendLastThinkingContent bool
  15. HasSentThinkingContent bool
  16. }
  17. const (
  18. LastMessageTypeNone = "none"
  19. LastMessageTypeText = "text"
  20. LastMessageTypeTools = "tools"
  21. LastMessageTypeThinking = "thinking"
  22. )
  23. type ClaudeConvertInfo struct {
  24. LastMessagesType string
  25. Index int
  26. Usage *dto.Usage
  27. FinishReason string
  28. Done bool
  29. }
  30. const (
  31. RelayFormatOpenAI = "openai"
  32. RelayFormatClaude = "claude"
  33. RelayFormatGemini = "gemini"
  34. RelayFormatOpenAIResponses = "openai_responses"
  35. RelayFormatOpenAIAudio = "openai_audio"
  36. RelayFormatOpenAIImage = "openai_image"
  37. RelayFormatRerank = "rerank"
  38. RelayFormatEmbedding = "embedding"
  39. )
  40. type RerankerInfo struct {
  41. Documents []any
  42. ReturnDocuments bool
  43. }
  44. type BuildInToolInfo struct {
  45. ToolName string
  46. CallCount int
  47. SearchContextSize string
  48. }
  49. type ResponsesUsageInfo struct {
  50. BuiltInTools map[string]*BuildInToolInfo
  51. }
  52. type RelayInfo struct {
  53. ChannelType int
  54. ChannelId int
  55. ChannelIsMultiKey bool // 是否多密钥
  56. ChannelMultiKeyIndex int // 多密钥索引
  57. TokenId int
  58. TokenKey string
  59. UserId int
  60. UsingGroup string // 使用的分组
  61. UserGroup string // 用户所在分组
  62. TokenUnlimited bool
  63. StartTime time.Time
  64. FirstResponseTime time.Time
  65. isFirstResponse bool
  66. //SendLastReasoningResponse bool
  67. ApiType int
  68. IsStream bool
  69. IsPlayground bool
  70. UsePrice bool
  71. RelayMode int
  72. UpstreamModelName string
  73. OriginModelName string
  74. //RecodeModelName string
  75. RequestURLPath string
  76. ApiVersion string
  77. PromptTokens int
  78. ApiKey string
  79. Organization string
  80. BaseUrl string
  81. SupportStreamOptions bool
  82. ShouldIncludeUsage bool
  83. DisablePing bool // 是否禁止向下游发送自定义 Ping
  84. IsModelMapped bool
  85. ClientWs *websocket.Conn
  86. TargetWs *websocket.Conn
  87. InputAudioFormat string
  88. OutputAudioFormat string
  89. RealtimeTools []dto.RealTimeTool
  90. IsFirstRequest bool
  91. AudioUsage bool
  92. ReasoningEffort string
  93. ChannelSetting dto.ChannelSettings
  94. ParamOverride map[string]interface{}
  95. UserSetting dto.UserSetting
  96. UserEmail string
  97. UserQuota int
  98. RelayFormat string
  99. SendResponseCount int
  100. ChannelCreateTime int64
  101. ThinkingContentInfo
  102. *ClaudeConvertInfo
  103. *RerankerInfo
  104. *ResponsesUsageInfo
  105. }
  106. // 定义支持流式选项的通道类型
  107. var streamSupportedChannels = map[int]bool{
  108. constant.ChannelTypeOpenAI: true,
  109. constant.ChannelTypeAnthropic: true,
  110. constant.ChannelTypeAws: true,
  111. constant.ChannelTypeGemini: true,
  112. constant.ChannelCloudflare: true,
  113. constant.ChannelTypeAzure: true,
  114. constant.ChannelTypeVolcEngine: true,
  115. constant.ChannelTypeOllama: true,
  116. constant.ChannelTypeXai: true,
  117. constant.ChannelTypeDeepSeek: true,
  118. constant.ChannelTypeBaiduV2: true,
  119. }
  120. func GenRelayInfoWs(c *gin.Context, ws *websocket.Conn) *RelayInfo {
  121. info := GenRelayInfo(c)
  122. info.ClientWs = ws
  123. info.InputAudioFormat = "pcm16"
  124. info.OutputAudioFormat = "pcm16"
  125. info.IsFirstRequest = true
  126. return info
  127. }
  128. func GenRelayInfoClaude(c *gin.Context) *RelayInfo {
  129. info := GenRelayInfo(c)
  130. info.RelayFormat = RelayFormatClaude
  131. info.ShouldIncludeUsage = false
  132. info.ClaudeConvertInfo = &ClaudeConvertInfo{
  133. LastMessagesType: LastMessageTypeNone,
  134. }
  135. return info
  136. }
  137. func GenRelayInfoRerank(c *gin.Context, req *dto.RerankRequest) *RelayInfo {
  138. info := GenRelayInfo(c)
  139. info.RelayMode = relayconstant.RelayModeRerank
  140. info.RelayFormat = RelayFormatRerank
  141. info.RerankerInfo = &RerankerInfo{
  142. Documents: req.Documents,
  143. ReturnDocuments: req.GetReturnDocuments(),
  144. }
  145. return info
  146. }
  147. func GenRelayInfoOpenAIAudio(c *gin.Context) *RelayInfo {
  148. info := GenRelayInfo(c)
  149. info.RelayFormat = RelayFormatOpenAIAudio
  150. return info
  151. }
  152. func GenRelayInfoEmbedding(c *gin.Context) *RelayInfo {
  153. info := GenRelayInfo(c)
  154. info.RelayFormat = RelayFormatEmbedding
  155. return info
  156. }
  157. func GenRelayInfoResponses(c *gin.Context, req *dto.OpenAIResponsesRequest) *RelayInfo {
  158. info := GenRelayInfo(c)
  159. info.RelayMode = relayconstant.RelayModeResponses
  160. info.RelayFormat = RelayFormatOpenAIResponses
  161. info.SupportStreamOptions = false
  162. info.ResponsesUsageInfo = &ResponsesUsageInfo{
  163. BuiltInTools: make(map[string]*BuildInToolInfo),
  164. }
  165. if len(req.Tools) > 0 {
  166. for _, tool := range req.Tools {
  167. toolType := common.Interface2String(tool["type"])
  168. info.ResponsesUsageInfo.BuiltInTools[toolType] = &BuildInToolInfo{
  169. ToolName: toolType,
  170. CallCount: 0,
  171. }
  172. switch toolType {
  173. case dto.BuildInToolWebSearchPreview:
  174. searchContextSize := common.Interface2String(tool["search_context_size"])
  175. if searchContextSize == "" {
  176. searchContextSize = "medium"
  177. }
  178. info.ResponsesUsageInfo.BuiltInTools[toolType].SearchContextSize = searchContextSize
  179. }
  180. }
  181. }
  182. info.IsStream = req.Stream
  183. return info
  184. }
  185. func GenRelayInfoGemini(c *gin.Context) *RelayInfo {
  186. info := GenRelayInfo(c)
  187. info.RelayFormat = RelayFormatGemini
  188. info.ShouldIncludeUsage = false
  189. return info
  190. }
  191. func GenRelayInfoImage(c *gin.Context) *RelayInfo {
  192. info := GenRelayInfo(c)
  193. info.RelayFormat = RelayFormatOpenAIImage
  194. return info
  195. }
  196. func GenRelayInfo(c *gin.Context) *RelayInfo {
  197. channelType := common.GetContextKeyInt(c, constant.ContextKeyChannelType)
  198. channelId := common.GetContextKeyInt(c, constant.ContextKeyChannelId)
  199. paramOverride := common.GetContextKeyStringMap(c, constant.ContextKeyChannelParamOverride)
  200. tokenId := common.GetContextKeyInt(c, constant.ContextKeyTokenId)
  201. tokenKey := common.GetContextKeyString(c, constant.ContextKeyTokenKey)
  202. userId := common.GetContextKeyInt(c, constant.ContextKeyUserId)
  203. tokenUnlimited := common.GetContextKeyBool(c, constant.ContextKeyTokenUnlimited)
  204. startTime := common.GetContextKeyTime(c, constant.ContextKeyRequestStartTime)
  205. if startTime.IsZero() {
  206. startTime = time.Now()
  207. }
  208. // firstResponseTime = time.Now() - 1 second
  209. apiType, _ := common.ChannelType2APIType(channelType)
  210. info := &RelayInfo{
  211. UserQuota: common.GetContextKeyInt(c, constant.ContextKeyUserQuota),
  212. UserEmail: common.GetContextKeyString(c, constant.ContextKeyUserEmail),
  213. isFirstResponse: true,
  214. RelayMode: relayconstant.Path2RelayMode(c.Request.URL.Path),
  215. BaseUrl: common.GetContextKeyString(c, constant.ContextKeyChannelBaseUrl),
  216. RequestURLPath: c.Request.URL.String(),
  217. ChannelType: channelType,
  218. ChannelId: channelId,
  219. TokenId: tokenId,
  220. TokenKey: tokenKey,
  221. UserId: userId,
  222. UsingGroup: common.GetContextKeyString(c, constant.ContextKeyUsingGroup),
  223. UserGroup: common.GetContextKeyString(c, constant.ContextKeyUserGroup),
  224. TokenUnlimited: tokenUnlimited,
  225. StartTime: startTime,
  226. FirstResponseTime: startTime.Add(-time.Second),
  227. OriginModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
  228. UpstreamModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
  229. //RecodeModelName: c.GetString("original_model"),
  230. IsModelMapped: false,
  231. ApiType: apiType,
  232. ApiVersion: c.GetString("api_version"),
  233. ApiKey: common.GetContextKeyString(c, constant.ContextKeyChannelKey),
  234. Organization: c.GetString("channel_organization"),
  235. ChannelCreateTime: c.GetInt64("channel_create_time"),
  236. ParamOverride: paramOverride,
  237. RelayFormat: RelayFormatOpenAI,
  238. ThinkingContentInfo: ThinkingContentInfo{
  239. IsFirstThinkingContent: true,
  240. SendLastThinkingContent: false,
  241. },
  242. ChannelIsMultiKey: common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey),
  243. ChannelMultiKeyIndex: common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex),
  244. }
  245. if strings.HasPrefix(c.Request.URL.Path, "/pg") {
  246. info.IsPlayground = true
  247. info.RequestURLPath = strings.TrimPrefix(info.RequestURLPath, "/pg")
  248. info.RequestURLPath = "/v1" + info.RequestURLPath
  249. }
  250. if info.BaseUrl == "" {
  251. info.BaseUrl = constant.ChannelBaseURLs[channelType]
  252. }
  253. if info.ChannelType == constant.ChannelTypeAzure {
  254. info.ApiVersion = GetAPIVersion(c)
  255. }
  256. if info.ChannelType == constant.ChannelTypeVertexAi {
  257. info.ApiVersion = c.GetString("region")
  258. }
  259. if streamSupportedChannels[info.ChannelType] {
  260. info.SupportStreamOptions = true
  261. }
  262. channelSetting, ok := common.GetContextKeyType[dto.ChannelSettings](c, constant.ContextKeyChannelSetting)
  263. if ok {
  264. info.ChannelSetting = channelSetting
  265. }
  266. userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting)
  267. if ok {
  268. info.UserSetting = userSetting
  269. }
  270. return info
  271. }
  272. func (info *RelayInfo) SetPromptTokens(promptTokens int) {
  273. info.PromptTokens = promptTokens
  274. }
  275. func (info *RelayInfo) SetIsStream(isStream bool) {
  276. info.IsStream = isStream
  277. }
  278. func (info *RelayInfo) SetFirstResponseTime() {
  279. if info.isFirstResponse {
  280. info.FirstResponseTime = time.Now()
  281. info.isFirstResponse = false
  282. }
  283. }
  284. func (info *RelayInfo) HasSendResponse() bool {
  285. return info.FirstResponseTime.After(info.StartTime)
  286. }
  287. type TaskRelayInfo struct {
  288. *RelayInfo
  289. Action string
  290. OriginTaskID string
  291. ConsumeQuota bool
  292. }
  293. func GenTaskRelayInfo(c *gin.Context) *TaskRelayInfo {
  294. info := &TaskRelayInfo{
  295. RelayInfo: GenRelayInfo(c),
  296. }
  297. return info
  298. }
  299. type TaskSubmitReq struct {
  300. Prompt string `json:"prompt"`
  301. Model string `json:"model,omitempty"`
  302. Mode string `json:"mode,omitempty"`
  303. Image string `json:"image,omitempty"`
  304. Size string `json:"size,omitempty"`
  305. Duration int `json:"duration,omitempty"`
  306. Metadata map[string]interface{} `json:"metadata,omitempty"`
  307. }
  308. type TaskInfo struct {
  309. Code int `json:"code"`
  310. TaskID string `json:"task_id"`
  311. Status string `json:"status"`
  312. Reason string `json:"reason,omitempty"`
  313. Url string `json:"url,omitempty"`
  314. Progress string `json:"progress,omitempty"`
  315. }