relay_info.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. info.ResponsesUsageInfo.BuiltInTools[tool.Type] = &BuildInToolInfo{
  166. ToolName: tool.Type,
  167. CallCount: 0,
  168. }
  169. switch tool.Type {
  170. case dto.BuildInToolWebSearchPreview:
  171. if tool.SearchContextSize == "" {
  172. tool.SearchContextSize = "medium"
  173. }
  174. info.ResponsesUsageInfo.BuiltInTools[tool.Type].SearchContextSize = tool.SearchContextSize
  175. }
  176. }
  177. }
  178. info.IsStream = req.Stream
  179. return info
  180. }
  181. func GenRelayInfoGemini(c *gin.Context) *RelayInfo {
  182. info := GenRelayInfo(c)
  183. info.RelayFormat = RelayFormatGemini
  184. info.ShouldIncludeUsage = false
  185. return info
  186. }
  187. func GenRelayInfoImage(c *gin.Context) *RelayInfo {
  188. info := GenRelayInfo(c)
  189. info.RelayFormat = RelayFormatOpenAIImage
  190. return info
  191. }
  192. func GenRelayInfo(c *gin.Context) *RelayInfo {
  193. channelType := common.GetContextKeyInt(c, constant.ContextKeyChannelType)
  194. channelId := common.GetContextKeyInt(c, constant.ContextKeyChannelId)
  195. paramOverride := common.GetContextKeyStringMap(c, constant.ContextKeyChannelParamOverride)
  196. tokenId := common.GetContextKeyInt(c, constant.ContextKeyTokenId)
  197. tokenKey := common.GetContextKeyString(c, constant.ContextKeyTokenKey)
  198. userId := common.GetContextKeyInt(c, constant.ContextKeyUserId)
  199. tokenUnlimited := common.GetContextKeyBool(c, constant.ContextKeyTokenUnlimited)
  200. startTime := common.GetContextKeyTime(c, constant.ContextKeyRequestStartTime)
  201. // firstResponseTime = time.Now() - 1 second
  202. apiType, _ := common.ChannelType2APIType(channelType)
  203. info := &RelayInfo{
  204. UserQuota: common.GetContextKeyInt(c, constant.ContextKeyUserQuota),
  205. UserEmail: common.GetContextKeyString(c, constant.ContextKeyUserEmail),
  206. isFirstResponse: true,
  207. RelayMode: relayconstant.Path2RelayMode(c.Request.URL.Path),
  208. BaseUrl: common.GetContextKeyString(c, constant.ContextKeyChannelBaseUrl),
  209. RequestURLPath: c.Request.URL.String(),
  210. ChannelType: channelType,
  211. ChannelId: channelId,
  212. TokenId: tokenId,
  213. TokenKey: tokenKey,
  214. UserId: userId,
  215. UsingGroup: common.GetContextKeyString(c, constant.ContextKeyUsingGroup),
  216. UserGroup: common.GetContextKeyString(c, constant.ContextKeyUserGroup),
  217. TokenUnlimited: tokenUnlimited,
  218. StartTime: startTime,
  219. FirstResponseTime: startTime.Add(-time.Second),
  220. OriginModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
  221. UpstreamModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
  222. //RecodeModelName: c.GetString("original_model"),
  223. IsModelMapped: false,
  224. ApiType: apiType,
  225. ApiVersion: c.GetString("api_version"),
  226. ApiKey: common.GetContextKeyString(c, constant.ContextKeyChannelKey),
  227. Organization: c.GetString("channel_organization"),
  228. ChannelCreateTime: c.GetInt64("channel_create_time"),
  229. ParamOverride: paramOverride,
  230. RelayFormat: RelayFormatOpenAI,
  231. ThinkingContentInfo: ThinkingContentInfo{
  232. IsFirstThinkingContent: true,
  233. SendLastThinkingContent: false,
  234. },
  235. }
  236. if strings.HasPrefix(c.Request.URL.Path, "/pg") {
  237. info.IsPlayground = true
  238. info.RequestURLPath = strings.TrimPrefix(info.RequestURLPath, "/pg")
  239. info.RequestURLPath = "/v1" + info.RequestURLPath
  240. }
  241. if info.BaseUrl == "" {
  242. info.BaseUrl = constant.ChannelBaseURLs[channelType]
  243. }
  244. if info.ChannelType == constant.ChannelTypeAzure {
  245. info.ApiVersion = GetAPIVersion(c)
  246. }
  247. if info.ChannelType == constant.ChannelTypeVertexAi {
  248. info.ApiVersion = c.GetString("region")
  249. }
  250. if streamSupportedChannels[info.ChannelType] {
  251. info.SupportStreamOptions = true
  252. }
  253. channelSetting, ok := common.GetContextKeyType[dto.ChannelSettings](c, constant.ContextKeyChannelSetting)
  254. if ok {
  255. info.ChannelSetting = channelSetting
  256. }
  257. userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting)
  258. if ok {
  259. info.UserSetting = userSetting
  260. }
  261. return info
  262. }
  263. func (info *RelayInfo) SetPromptTokens(promptTokens int) {
  264. info.PromptTokens = promptTokens
  265. }
  266. func (info *RelayInfo) SetIsStream(isStream bool) {
  267. info.IsStream = isStream
  268. }
  269. func (info *RelayInfo) SetFirstResponseTime() {
  270. if info.isFirstResponse {
  271. info.FirstResponseTime = time.Now()
  272. info.isFirstResponse = false
  273. }
  274. }
  275. func (info *RelayInfo) HasSendResponse() bool {
  276. return info.FirstResponseTime.After(info.StartTime)
  277. }
  278. type TaskRelayInfo struct {
  279. *RelayInfo
  280. Action string
  281. OriginTaskID string
  282. ConsumeQuota bool
  283. }
  284. func GenTaskRelayInfo(c *gin.Context) *TaskRelayInfo {
  285. info := &TaskRelayInfo{
  286. RelayInfo: GenRelayInfo(c),
  287. }
  288. return info
  289. }
  290. type TaskSubmitReq struct {
  291. Prompt string `json:"prompt"`
  292. Model string `json:"model,omitempty"`
  293. Mode string `json:"mode,omitempty"`
  294. Image string `json:"image,omitempty"`
  295. Size string `json:"size,omitempty"`
  296. Duration int `json:"duration,omitempty"`
  297. Metadata map[string]interface{} `json:"metadata,omitempty"`
  298. }
  299. type TaskInfo struct {
  300. Code int `json:"code"`
  301. TaskID string `json:"task_id"`
  302. Status string `json:"status"`
  303. Reason string `json:"reason,omitempty"`
  304. Url string `json:"url,omitempty"`
  305. Progress string `json:"progress,omitempty"`
  306. }