relay_info.go 9.9 KB

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