openai_response.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package dto
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "one-api/common"
  7. "one-api/types"
  8. )
  9. type SimpleResponse struct {
  10. Usage `json:"usage"`
  11. Error any `json:"error"`
  12. }
  13. // GetOpenAIError 从动态错误类型中提取OpenAIError结构
  14. func (s *SimpleResponse) GetOpenAIError() *types.OpenAIError {
  15. return GetOpenAIError(s.Error)
  16. }
  17. type TextResponse struct {
  18. Id string `json:"id"`
  19. Object string `json:"object"`
  20. Created int64 `json:"created"`
  21. Model string `json:"model"`
  22. Choices []OpenAITextResponseChoice `json:"choices"`
  23. Usage `json:"usage"`
  24. }
  25. type OpenAITextResponseChoice struct {
  26. Index int `json:"index"`
  27. Message `json:"message"`
  28. FinishReason string `json:"finish_reason"`
  29. }
  30. type OpenAITextResponse struct {
  31. Id string `json:"id"`
  32. Model string `json:"model"`
  33. Object string `json:"object"`
  34. Created any `json:"created"`
  35. Choices []OpenAITextResponseChoice `json:"choices"`
  36. Error any `json:"error,omitempty"`
  37. Usage `json:"usage"`
  38. }
  39. // GetOpenAIError 从动态错误类型中提取OpenAIError结构
  40. func (o *OpenAITextResponse) GetOpenAIError() *types.OpenAIError {
  41. return GetOpenAIError(o.Error)
  42. }
  43. type OpenAIEmbeddingResponseItem struct {
  44. Object string `json:"object"`
  45. Index int `json:"index"`
  46. Embedding []float64 `json:"embedding"`
  47. }
  48. type OpenAIEmbeddingResponse struct {
  49. Object string `json:"object"`
  50. Data []OpenAIEmbeddingResponseItem `json:"data"`
  51. Model string `json:"model"`
  52. Usage `json:"usage"`
  53. }
  54. type FlexibleEmbeddingResponseItem struct {
  55. Object string `json:"object"`
  56. Index int `json:"index"`
  57. Embedding any `json:"embedding"`
  58. }
  59. type FlexibleEmbeddingResponse struct {
  60. Object string `json:"object"`
  61. Data []FlexibleEmbeddingResponseItem `json:"data"`
  62. Model string `json:"model"`
  63. Usage `json:"usage"`
  64. }
  65. type ChatCompletionsStreamResponseChoice struct {
  66. Delta ChatCompletionsStreamResponseChoiceDelta `json:"delta,omitempty"`
  67. Logprobs *any `json:"logprobs"`
  68. FinishReason *string `json:"finish_reason"`
  69. Index int `json:"index"`
  70. }
  71. type ChatCompletionsStreamResponseChoiceDelta struct {
  72. Content *string `json:"content,omitempty"`
  73. ReasoningContent *string `json:"reasoning_content,omitempty"`
  74. Reasoning *string `json:"reasoning,omitempty"`
  75. Role string `json:"role,omitempty"`
  76. ToolCalls []ToolCallResponse `json:"tool_calls,omitempty"`
  77. }
  78. func (c *ChatCompletionsStreamResponseChoiceDelta) SetContentString(s string) {
  79. c.Content = &s
  80. }
  81. func (c *ChatCompletionsStreamResponseChoiceDelta) GetContentString() string {
  82. if c.Content == nil {
  83. return ""
  84. }
  85. return *c.Content
  86. }
  87. func (c *ChatCompletionsStreamResponseChoiceDelta) GetReasoningContent() string {
  88. if c.ReasoningContent == nil && c.Reasoning == nil {
  89. return ""
  90. }
  91. if c.ReasoningContent != nil {
  92. return *c.ReasoningContent
  93. }
  94. return *c.Reasoning
  95. }
  96. func (c *ChatCompletionsStreamResponseChoiceDelta) SetReasoningContent(s string) {
  97. c.ReasoningContent = &s
  98. c.Reasoning = &s
  99. }
  100. type ToolCallResponse struct {
  101. // Index is not nil only in chat completion chunk object
  102. Index *int `json:"index,omitempty"`
  103. ID string `json:"id,omitempty"`
  104. Type any `json:"type"`
  105. Function FunctionResponse `json:"function"`
  106. }
  107. func (c *ToolCallResponse) SetIndex(i int) {
  108. c.Index = &i
  109. }
  110. type FunctionResponse struct {
  111. Description string `json:"description,omitempty"`
  112. Name string `json:"name,omitempty"`
  113. // call function with arguments in JSON format
  114. Parameters any `json:"parameters,omitempty"` // request
  115. Arguments string `json:"arguments"` // response
  116. }
  117. type ChatCompletionsStreamResponse struct {
  118. Id string `json:"id"`
  119. Object string `json:"object"`
  120. Created int64 `json:"created"`
  121. Model string `json:"model"`
  122. SystemFingerprint *string `json:"system_fingerprint"`
  123. Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
  124. Usage *Usage `json:"usage"`
  125. }
  126. func (c *ChatCompletionsStreamResponse) IsToolCall() bool {
  127. if len(c.Choices) == 0 {
  128. return false
  129. }
  130. return len(c.Choices[0].Delta.ToolCalls) > 0
  131. }
  132. func (c *ChatCompletionsStreamResponse) GetFirstToolCall() *ToolCallResponse {
  133. if c.IsToolCall() {
  134. return &c.Choices[0].Delta.ToolCalls[0]
  135. }
  136. return nil
  137. }
  138. func (c *ChatCompletionsStreamResponse) Copy() *ChatCompletionsStreamResponse {
  139. choices := make([]ChatCompletionsStreamResponseChoice, len(c.Choices))
  140. copy(choices, c.Choices)
  141. return &ChatCompletionsStreamResponse{
  142. Id: c.Id,
  143. Object: c.Object,
  144. Created: c.Created,
  145. Model: c.Model,
  146. SystemFingerprint: c.SystemFingerprint,
  147. Choices: choices,
  148. Usage: c.Usage,
  149. }
  150. }
  151. func (c *ChatCompletionsStreamResponse) GetSystemFingerprint() string {
  152. if c.SystemFingerprint == nil {
  153. return ""
  154. }
  155. return *c.SystemFingerprint
  156. }
  157. func (c *ChatCompletionsStreamResponse) SetSystemFingerprint(s string) {
  158. c.SystemFingerprint = &s
  159. }
  160. type ChatCompletionsStreamResponseSimple struct {
  161. Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
  162. Usage *Usage `json:"usage"`
  163. }
  164. type CompletionsStreamResponse struct {
  165. Choices []struct {
  166. Text string `json:"text"`
  167. FinishReason string `json:"finish_reason"`
  168. } `json:"choices"`
  169. }
  170. type Usage struct {
  171. PromptTokens int `json:"prompt_tokens"`
  172. CompletionTokens int `json:"completion_tokens"`
  173. TotalTokens int `json:"total_tokens"`
  174. PromptCacheHitTokens int `json:"prompt_cache_hit_tokens,omitempty"`
  175. PromptTokensDetails InputTokenDetails `json:"prompt_tokens_details"`
  176. CompletionTokenDetails OutputTokenDetails `json:"completion_tokens_details"`
  177. InputTokens any `json:"input_tokens"`
  178. OutputTokens any `json:"output_tokens"`
  179. //CacheReadInputTokens any `json:"cache_read_input_tokens,omitempty"`
  180. InputTokensDetails *InputTokenDetails `json:"input_tokens_details"`
  181. // OpenRouter Params
  182. Cost any `json:"cost,omitempty"`
  183. }
  184. func (u *Usage) UnmarshalJSON(data []byte) error {
  185. // first normal unmarshal
  186. if err := common.Unmarshal(data, u); err != nil {
  187. return fmt.Errorf("unmarshal Usage failed: %w", err)
  188. }
  189. // then ceil the input and output tokens
  190. ceil := func(val any) int {
  191. switch v := val.(type) {
  192. case float64:
  193. return int(math.Ceil(v))
  194. case int:
  195. return v
  196. case string:
  197. var intVal int
  198. _, err := fmt.Sscanf(v, "%d", &intVal)
  199. if err != nil {
  200. return 0 // or handle error appropriately
  201. }
  202. return intVal
  203. default:
  204. return 0 // or handle error appropriately
  205. }
  206. }
  207. // input_tokens must be int
  208. if u.InputTokens != nil {
  209. u.InputTokens = ceil(u.InputTokens)
  210. }
  211. if u.OutputTokens != nil {
  212. u.OutputTokens = ceil(u.OutputTokens)
  213. }
  214. return nil
  215. }
  216. func (u *Usage) GetInputTokens() int {
  217. if u.InputTokens == nil {
  218. return 0
  219. }
  220. switch v := u.InputTokens.(type) {
  221. case int:
  222. return v
  223. case float64:
  224. return int(math.Ceil(v))
  225. case string:
  226. var intVal int
  227. _, err := fmt.Sscanf(v, "%d", &intVal)
  228. if err != nil {
  229. return 0 // or handle error appropriately
  230. }
  231. return intVal
  232. default:
  233. return 0 // or handle error appropriately
  234. }
  235. }
  236. func (u *Usage) GetOutputTokens() int {
  237. if u.OutputTokens == nil {
  238. return 0
  239. }
  240. switch v := u.OutputTokens.(type) {
  241. case int:
  242. return v
  243. case float64:
  244. return int(math.Ceil(v))
  245. case string:
  246. var intVal int
  247. _, err := fmt.Sscanf(v, "%d", &intVal)
  248. if err != nil {
  249. return 0 // or handle error appropriately
  250. }
  251. return intVal
  252. default:
  253. return 0 // or handle error appropriately
  254. }
  255. }
  256. //func (u *Usage) MarshalJSON() ([]byte, error) {
  257. // ceil := func(val any) int {
  258. // switch v := val.(type) {
  259. // case float64:
  260. // return int(math.Ceil(v))
  261. // case int:
  262. // return v
  263. // case string:
  264. // var intVal int
  265. // _, err := fmt.Sscanf(v, "%d", &intVal)
  266. // if err != nil {
  267. // return 0 // or handle error appropriately
  268. // }
  269. // return intVal
  270. // default:
  271. // return 0 // or handle error appropriately
  272. // }
  273. // }
  274. //
  275. // // input_tokens must be int
  276. // if u.InputTokens != nil {
  277. // u.InputTokens = ceil(u.InputTokens)
  278. // }
  279. // if u.OutputTokens != nil {
  280. // u.OutputTokens = ceil(u.OutputTokens)
  281. // }
  282. //
  283. // // done
  284. // return common.Marshal(u)
  285. //}
  286. type InputTokenDetails struct {
  287. CachedTokens int `json:"cached_tokens"`
  288. CachedCreationTokens int `json:"-"`
  289. TextTokens int `json:"text_tokens"`
  290. AudioTokens int `json:"audio_tokens"`
  291. ImageTokens int `json:"image_tokens"`
  292. }
  293. type OutputTokenDetails struct {
  294. TextTokens int `json:"text_tokens"`
  295. AudioTokens int `json:"audio_tokens"`
  296. ReasoningTokens int `json:"reasoning_tokens"`
  297. }
  298. type OpenAIResponsesResponse struct {
  299. ID string `json:"id"`
  300. Object string `json:"object"`
  301. CreatedAt int `json:"created_at"`
  302. Status string `json:"status"`
  303. Error any `json:"error,omitempty"`
  304. IncompleteDetails *IncompleteDetails `json:"incomplete_details,omitempty"`
  305. Instructions string `json:"instructions"`
  306. MaxOutputTokens int `json:"max_output_tokens"`
  307. Model string `json:"model"`
  308. Output []ResponsesOutput `json:"output"`
  309. ParallelToolCalls bool `json:"parallel_tool_calls"`
  310. PreviousResponseID string `json:"previous_response_id"`
  311. Reasoning *Reasoning `json:"reasoning"`
  312. Store bool `json:"store"`
  313. Temperature float64 `json:"temperature"`
  314. ToolChoice string `json:"tool_choice"`
  315. Tools []map[string]any `json:"tools"`
  316. TopP float64 `json:"top_p"`
  317. Truncation string `json:"truncation"`
  318. Usage *Usage `json:"usage"`
  319. User json.RawMessage `json:"user"`
  320. Metadata json.RawMessage `json:"metadata"`
  321. }
  322. // GetOpenAIError 从动态错误类型中提取OpenAIError结构
  323. func (o *OpenAIResponsesResponse) GetOpenAIError() *types.OpenAIError {
  324. return GetOpenAIError(o.Error)
  325. }
  326. type IncompleteDetails struct {
  327. Reasoning string `json:"reasoning"`
  328. }
  329. type ResponsesOutput struct {
  330. Type string `json:"type"`
  331. ID string `json:"id"`
  332. Status string `json:"status"`
  333. Role string `json:"role"`
  334. Content []ResponsesOutputContent `json:"content"`
  335. }
  336. type ResponsesOutputContent struct {
  337. Type string `json:"type"`
  338. Text string `json:"text"`
  339. Annotations []interface{} `json:"annotations"`
  340. }
  341. const (
  342. BuildInToolWebSearchPreview = "web_search_preview"
  343. BuildInToolFileSearch = "file_search"
  344. )
  345. const (
  346. BuildInCallWebSearchCall = "web_search_call"
  347. )
  348. const (
  349. ResponsesOutputTypeItemAdded = "response.output_item.added"
  350. ResponsesOutputTypeItemDone = "response.output_item.done"
  351. )
  352. // ResponsesStreamResponse 用于处理 /v1/responses 流式响应
  353. type ResponsesStreamResponse struct {
  354. Type string `json:"type"`
  355. Response *OpenAIResponsesResponse `json:"response,omitempty"`
  356. Delta string `json:"delta,omitempty"`
  357. Item *ResponsesOutput `json:"item,omitempty"`
  358. }
  359. // GetOpenAIError 从动态错误类型中提取OpenAIError结构
  360. func GetOpenAIError(errorField any) *types.OpenAIError {
  361. if errorField == nil {
  362. return nil
  363. }
  364. switch err := errorField.(type) {
  365. case types.OpenAIError:
  366. return &err
  367. case *types.OpenAIError:
  368. return err
  369. case map[string]interface{}:
  370. // 处理从JSON解析来的map结构
  371. openaiErr := &types.OpenAIError{}
  372. if errType, ok := err["type"].(string); ok {
  373. openaiErr.Type = errType
  374. }
  375. if errMsg, ok := err["message"].(string); ok {
  376. openaiErr.Message = errMsg
  377. }
  378. if errParam, ok := err["param"].(string); ok {
  379. openaiErr.Param = errParam
  380. }
  381. if errCode, ok := err["code"]; ok {
  382. openaiErr.Code = errCode
  383. }
  384. return openaiErr
  385. case string:
  386. // 处理简单字符串错误
  387. return &types.OpenAIError{
  388. Type: "error",
  389. Message: err,
  390. }
  391. default:
  392. // 未知类型,尝试转换为字符串
  393. return &types.OpenAIError{
  394. Type: "unknown_error",
  395. Message: fmt.Sprintf("%v", err),
  396. }
  397. }
  398. }