relay_info.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. // firstResponseTime = time.Now() - 1 second
  206. apiType, _ := common.ChannelType2APIType(channelType)
  207. info := &RelayInfo{
  208. UserQuota: common.GetContextKeyInt(c, constant.ContextKeyUserQuota),
  209. UserEmail: common.GetContextKeyString(c, constant.ContextKeyUserEmail),
  210. isFirstResponse: true,
  211. RelayMode: relayconstant.Path2RelayMode(c.Request.URL.Path),
  212. BaseUrl: common.GetContextKeyString(c, constant.ContextKeyChannelBaseUrl),
  213. RequestURLPath: c.Request.URL.String(),
  214. ChannelType: channelType,
  215. ChannelId: channelId,
  216. TokenId: tokenId,
  217. TokenKey: tokenKey,
  218. UserId: userId,
  219. UsingGroup: common.GetContextKeyString(c, constant.ContextKeyUsingGroup),
  220. UserGroup: common.GetContextKeyString(c, constant.ContextKeyUserGroup),
  221. TokenUnlimited: tokenUnlimited,
  222. StartTime: startTime,
  223. FirstResponseTime: startTime.Add(-time.Second),
  224. OriginModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
  225. UpstreamModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
  226. //RecodeModelName: c.GetString("original_model"),
  227. IsModelMapped: false,
  228. ApiType: apiType,
  229. ApiVersion: c.GetString("api_version"),
  230. ApiKey: common.GetContextKeyString(c, constant.ContextKeyChannelKey),
  231. Organization: c.GetString("channel_organization"),
  232. ChannelCreateTime: c.GetInt64("channel_create_time"),
  233. ParamOverride: paramOverride,
  234. RelayFormat: RelayFormatOpenAI,
  235. ThinkingContentInfo: ThinkingContentInfo{
  236. IsFirstThinkingContent: true,
  237. SendLastThinkingContent: false,
  238. },
  239. ChannelIsMultiKey: common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey),
  240. ChannelMultiKeyIndex: common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex),
  241. }
  242. if strings.HasPrefix(c.Request.URL.Path, "/pg") {
  243. info.IsPlayground = true
  244. info.RequestURLPath = strings.TrimPrefix(info.RequestURLPath, "/pg")
  245. info.RequestURLPath = "/v1" + info.RequestURLPath
  246. }
  247. if info.BaseUrl == "" {
  248. info.BaseUrl = constant.ChannelBaseURLs[channelType]
  249. }
  250. if info.ChannelType == constant.ChannelTypeAzure {
  251. info.ApiVersion = GetAPIVersion(c)
  252. }
  253. if info.ChannelType == constant.ChannelTypeVertexAi {
  254. info.ApiVersion = c.GetString("region")
  255. }
  256. if streamSupportedChannels[info.ChannelType] {
  257. info.SupportStreamOptions = true
  258. }
  259. channelSetting, ok := common.GetContextKeyType[dto.ChannelSettings](c, constant.ContextKeyChannelSetting)
  260. if ok {
  261. info.ChannelSetting = channelSetting
  262. }
  263. userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting)
  264. if ok {
  265. info.UserSetting = userSetting
  266. }
  267. return info
  268. }
  269. func (info *RelayInfo) SetPromptTokens(promptTokens int) {
  270. info.PromptTokens = promptTokens
  271. }
  272. func (info *RelayInfo) SetIsStream(isStream bool) {
  273. info.IsStream = isStream
  274. }
  275. func (info *RelayInfo) SetFirstResponseTime() {
  276. if info.isFirstResponse {
  277. info.FirstResponseTime = time.Now()
  278. info.isFirstResponse = false
  279. }
  280. }
  281. func (info *RelayInfo) HasSendResponse() bool {
  282. return info.FirstResponseTime.After(info.StartTime)
  283. }
  284. type TaskRelayInfo struct {
  285. *RelayInfo
  286. Action string
  287. OriginTaskID string
  288. ConsumeQuota bool
  289. }
  290. func GenTaskRelayInfo(c *gin.Context) *TaskRelayInfo {
  291. info := &TaskRelayInfo{
  292. RelayInfo: GenRelayInfo(c),
  293. }
  294. return info
  295. }
  296. type TaskSubmitReq struct {
  297. Prompt string `json:"prompt"`
  298. Model string `json:"model,omitempty"`
  299. Mode string `json:"mode,omitempty"`
  300. Image string `json:"image,omitempty"`
  301. Size string `json:"size,omitempty"`
  302. Duration int `json:"duration,omitempty"`
  303. Metadata map[string]interface{} `json:"metadata,omitempty"`
  304. }
  305. type TaskInfo struct {
  306. Code int `json:"code"`
  307. TaskID string `json:"task_id"`
  308. Status string `json:"status"`
  309. Reason string `json:"reason,omitempty"`
  310. Url string `json:"url,omitempty"`
  311. Progress string `json:"progress,omitempty"`
  312. }