relay_info.go 10 KB

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