openai_response.go 12 KB

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