openai_request.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. package dto
  2. import (
  3. "encoding/json"
  4. "one-api/common"
  5. "strings"
  6. )
  7. type ResponseFormat struct {
  8. Type string `json:"type,omitempty"`
  9. JsonSchema *FormatJsonSchema `json:"json_schema,omitempty"`
  10. }
  11. type FormatJsonSchema struct {
  12. Description string `json:"description,omitempty"`
  13. Name string `json:"name"`
  14. Schema any `json:"schema,omitempty"`
  15. Strict any `json:"strict,omitempty"`
  16. }
  17. type GeneralOpenAIRequest struct {
  18. Model string `json:"model,omitempty"`
  19. Messages []Message `json:"messages,omitempty"`
  20. Prompt any `json:"prompt,omitempty"`
  21. Prefix any `json:"prefix,omitempty"`
  22. Suffix any `json:"suffix,omitempty"`
  23. Stream bool `json:"stream,omitempty"`
  24. StreamOptions *StreamOptions `json:"stream_options,omitempty"`
  25. MaxTokens uint `json:"max_tokens,omitempty"`
  26. MaxCompletionTokens uint `json:"max_completion_tokens,omitempty"`
  27. ReasoningEffort string `json:"reasoning_effort,omitempty"`
  28. Temperature *float64 `json:"temperature,omitempty"`
  29. TopP float64 `json:"top_p,omitempty"`
  30. TopK int `json:"top_k,omitempty"`
  31. Stop any `json:"stop,omitempty"`
  32. N int `json:"n,omitempty"`
  33. Input any `json:"input,omitempty"`
  34. Instruction string `json:"instruction,omitempty"`
  35. Size string `json:"size,omitempty"`
  36. Functions json.RawMessage `json:"functions,omitempty"`
  37. FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
  38. PresencePenalty float64 `json:"presence_penalty,omitempty"`
  39. ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
  40. EncodingFormat json.RawMessage `json:"encoding_format,omitempty"`
  41. Seed float64 `json:"seed,omitempty"`
  42. ParallelTooCalls *bool `json:"parallel_tool_calls,omitempty"`
  43. Tools []ToolCallRequest `json:"tools,omitempty"`
  44. ToolChoice any `json:"tool_choice,omitempty"`
  45. User string `json:"user,omitempty"`
  46. LogProbs bool `json:"logprobs,omitempty"`
  47. TopLogProbs int `json:"top_logprobs,omitempty"`
  48. Dimensions int `json:"dimensions,omitempty"`
  49. Modalities json.RawMessage `json:"modalities,omitempty"`
  50. Audio json.RawMessage `json:"audio,omitempty"`
  51. EnableThinking any `json:"enable_thinking,omitempty"` // ali
  52. THINKING json.RawMessage `json:"thinking,omitempty"` // doubao
  53. ExtraBody json.RawMessage `json:"extra_body,omitempty"`
  54. SearchParameters any `json:"search_parameters,omitempty"` //xai
  55. WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty"`
  56. // OpenRouter Params
  57. Usage json.RawMessage `json:"usage,omitempty"`
  58. Reasoning json.RawMessage `json:"reasoning,omitempty"`
  59. // Ali Qwen Params
  60. VlHighResolutionImages json.RawMessage `json:"vl_high_resolution_images,omitempty"`
  61. }
  62. func (r *GeneralOpenAIRequest) ToMap() map[string]any {
  63. result := make(map[string]any)
  64. data, _ := common.Marshal(r)
  65. _ = common.Unmarshal(data, &result)
  66. return result
  67. }
  68. type ToolCallRequest struct {
  69. ID string `json:"id,omitempty"`
  70. Type string `json:"type"`
  71. Function FunctionRequest `json:"function"`
  72. }
  73. type FunctionRequest struct {
  74. Description string `json:"description,omitempty"`
  75. Name string `json:"name"`
  76. Parameters any `json:"parameters,omitempty"`
  77. Arguments string `json:"arguments,omitempty"`
  78. }
  79. type StreamOptions struct {
  80. IncludeUsage bool `json:"include_usage,omitempty"`
  81. }
  82. func (r *GeneralOpenAIRequest) GetMaxTokens() int {
  83. return int(r.MaxTokens)
  84. }
  85. func (r *GeneralOpenAIRequest) ParseInput() []string {
  86. if r.Input == nil {
  87. return nil
  88. }
  89. var input []string
  90. switch r.Input.(type) {
  91. case string:
  92. input = []string{r.Input.(string)}
  93. case []any:
  94. input = make([]string, 0, len(r.Input.([]any)))
  95. for _, item := range r.Input.([]any) {
  96. if str, ok := item.(string); ok {
  97. input = append(input, str)
  98. }
  99. }
  100. }
  101. return input
  102. }
  103. type Message struct {
  104. Role string `json:"role"`
  105. Content any `json:"content"`
  106. Name *string `json:"name,omitempty"`
  107. Prefix *bool `json:"prefix,omitempty"`
  108. ReasoningContent string `json:"reasoning_content,omitempty"`
  109. Reasoning string `json:"reasoning,omitempty"`
  110. ToolCalls json.RawMessage `json:"tool_calls,omitempty"`
  111. ToolCallId string `json:"tool_call_id,omitempty"`
  112. parsedContent []MediaContent
  113. //parsedStringContent *string
  114. }
  115. type MediaContent struct {
  116. Type string `json:"type"`
  117. Text string `json:"text,omitempty"`
  118. ImageUrl any `json:"image_url,omitempty"`
  119. InputAudio any `json:"input_audio,omitempty"`
  120. File any `json:"file,omitempty"`
  121. VideoUrl any `json:"video_url,omitempty"`
  122. // OpenRouter Params
  123. CacheControl json.RawMessage `json:"cache_control,omitempty"`
  124. }
  125. func (m *MediaContent) GetImageMedia() *MessageImageUrl {
  126. if m.ImageUrl != nil {
  127. if _, ok := m.ImageUrl.(*MessageImageUrl); ok {
  128. return m.ImageUrl.(*MessageImageUrl)
  129. }
  130. if itemMap, ok := m.ImageUrl.(map[string]any); ok {
  131. out := &MessageImageUrl{
  132. Url: common.Interface2String(itemMap["url"]),
  133. Detail: common.Interface2String(itemMap["detail"]),
  134. MimeType: common.Interface2String(itemMap["mime_type"]),
  135. }
  136. return out
  137. }
  138. }
  139. return nil
  140. }
  141. func (m *MediaContent) GetInputAudio() *MessageInputAudio {
  142. if m.InputAudio != nil {
  143. if _, ok := m.InputAudio.(*MessageInputAudio); ok {
  144. return m.InputAudio.(*MessageInputAudio)
  145. }
  146. if itemMap, ok := m.InputAudio.(map[string]any); ok {
  147. out := &MessageInputAudio{
  148. Data: common.Interface2String(itemMap["data"]),
  149. Format: common.Interface2String(itemMap["format"]),
  150. }
  151. return out
  152. }
  153. }
  154. return nil
  155. }
  156. func (m *MediaContent) GetFile() *MessageFile {
  157. if m.File != nil {
  158. if _, ok := m.File.(*MessageFile); ok {
  159. return m.File.(*MessageFile)
  160. }
  161. if itemMap, ok := m.File.(map[string]any); ok {
  162. out := &MessageFile{
  163. FileName: common.Interface2String(itemMap["file_name"]),
  164. FileData: common.Interface2String(itemMap["file_data"]),
  165. FileId: common.Interface2String(itemMap["file_id"]),
  166. }
  167. return out
  168. }
  169. }
  170. return nil
  171. }
  172. type MessageImageUrl struct {
  173. Url string `json:"url"`
  174. Detail string `json:"detail"`
  175. MimeType string
  176. }
  177. func (m *MessageImageUrl) IsRemoteImage() bool {
  178. return strings.HasPrefix(m.Url, "http")
  179. }
  180. type MessageInputAudio struct {
  181. Data string `json:"data"` //base64
  182. Format string `json:"format"`
  183. }
  184. type MessageFile struct {
  185. FileName string `json:"filename,omitempty"`
  186. FileData string `json:"file_data,omitempty"`
  187. FileId string `json:"file_id,omitempty"`
  188. }
  189. type MessageVideoUrl struct {
  190. Url string `json:"url"`
  191. }
  192. const (
  193. ContentTypeText = "text"
  194. ContentTypeImageURL = "image_url"
  195. ContentTypeInputAudio = "input_audio"
  196. ContentTypeFile = "file"
  197. ContentTypeVideoUrl = "video_url" // 阿里百炼视频识别
  198. )
  199. func (m *Message) GetPrefix() bool {
  200. if m.Prefix == nil {
  201. return false
  202. }
  203. return *m.Prefix
  204. }
  205. func (m *Message) SetPrefix(prefix bool) {
  206. m.Prefix = &prefix
  207. }
  208. func (m *Message) ParseToolCalls() []ToolCallRequest {
  209. if m.ToolCalls == nil {
  210. return nil
  211. }
  212. var toolCalls []ToolCallRequest
  213. if err := json.Unmarshal(m.ToolCalls, &toolCalls); err == nil {
  214. return toolCalls
  215. }
  216. return toolCalls
  217. }
  218. func (m *Message) SetToolCalls(toolCalls any) {
  219. toolCallsJson, _ := json.Marshal(toolCalls)
  220. m.ToolCalls = toolCallsJson
  221. }
  222. func (m *Message) StringContent() string {
  223. switch m.Content.(type) {
  224. case string:
  225. return m.Content.(string)
  226. case []any:
  227. var contentStr string
  228. for _, contentItem := range m.Content.([]any) {
  229. contentMap, ok := contentItem.(map[string]any)
  230. if !ok {
  231. continue
  232. }
  233. if contentMap["type"] == ContentTypeText {
  234. if subStr, ok := contentMap["text"].(string); ok {
  235. contentStr += subStr
  236. }
  237. }
  238. }
  239. return contentStr
  240. }
  241. return ""
  242. }
  243. func (m *Message) SetNullContent() {
  244. m.Content = nil
  245. m.parsedContent = nil
  246. }
  247. func (m *Message) SetStringContent(content string) {
  248. m.Content = content
  249. m.parsedContent = nil
  250. }
  251. func (m *Message) SetMediaContent(content []MediaContent) {
  252. m.Content = content
  253. m.parsedContent = content
  254. }
  255. func (m *Message) IsStringContent() bool {
  256. _, ok := m.Content.(string)
  257. if ok {
  258. return true
  259. }
  260. return false
  261. }
  262. func (m *Message) ParseContent() []MediaContent {
  263. if m.Content == nil {
  264. return nil
  265. }
  266. if len(m.parsedContent) > 0 {
  267. return m.parsedContent
  268. }
  269. var contentList []MediaContent
  270. // 先尝试解析为字符串
  271. content, ok := m.Content.(string)
  272. if ok {
  273. contentList = []MediaContent{{
  274. Type: ContentTypeText,
  275. Text: content,
  276. }}
  277. m.parsedContent = contentList
  278. return contentList
  279. }
  280. // 尝试解析为数组
  281. //var arrayContent []map[string]interface{}
  282. arrayContent, ok := m.Content.([]any)
  283. if !ok {
  284. return contentList
  285. }
  286. for _, contentItemAny := range arrayContent {
  287. mediaItem, ok := contentItemAny.(MediaContent)
  288. if ok {
  289. contentList = append(contentList, mediaItem)
  290. continue
  291. }
  292. contentItem, ok := contentItemAny.(map[string]any)
  293. if !ok {
  294. continue
  295. }
  296. contentType, ok := contentItem["type"].(string)
  297. if !ok {
  298. continue
  299. }
  300. switch contentType {
  301. case ContentTypeText:
  302. if text, ok := contentItem["text"].(string); ok {
  303. contentList = append(contentList, MediaContent{
  304. Type: ContentTypeText,
  305. Text: text,
  306. })
  307. }
  308. case ContentTypeImageURL:
  309. imageUrl := contentItem["image_url"]
  310. temp := &MessageImageUrl{
  311. Detail: "high",
  312. }
  313. switch v := imageUrl.(type) {
  314. case string:
  315. temp.Url = v
  316. case map[string]interface{}:
  317. url, ok1 := v["url"].(string)
  318. detail, ok2 := v["detail"].(string)
  319. if ok2 {
  320. temp.Detail = detail
  321. }
  322. if ok1 {
  323. temp.Url = url
  324. }
  325. }
  326. contentList = append(contentList, MediaContent{
  327. Type: ContentTypeImageURL,
  328. ImageUrl: temp,
  329. })
  330. case ContentTypeInputAudio:
  331. if audioData, ok := contentItem["input_audio"].(map[string]interface{}); ok {
  332. data, ok1 := audioData["data"].(string)
  333. format, ok2 := audioData["format"].(string)
  334. if ok1 && ok2 {
  335. temp := &MessageInputAudio{
  336. Data: data,
  337. Format: format,
  338. }
  339. contentList = append(contentList, MediaContent{
  340. Type: ContentTypeInputAudio,
  341. InputAudio: temp,
  342. })
  343. }
  344. }
  345. case ContentTypeFile:
  346. if fileData, ok := contentItem["file"].(map[string]interface{}); ok {
  347. fileId, ok3 := fileData["file_id"].(string)
  348. if ok3 {
  349. contentList = append(contentList, MediaContent{
  350. Type: ContentTypeFile,
  351. File: &MessageFile{
  352. FileId: fileId,
  353. },
  354. })
  355. } else {
  356. fileName, ok1 := fileData["filename"].(string)
  357. fileDataStr, ok2 := fileData["file_data"].(string)
  358. if ok1 && ok2 {
  359. contentList = append(contentList, MediaContent{
  360. Type: ContentTypeFile,
  361. File: &MessageFile{
  362. FileName: fileName,
  363. FileData: fileDataStr,
  364. },
  365. })
  366. }
  367. }
  368. }
  369. case ContentTypeVideoUrl:
  370. if videoUrl, ok := contentItem["video_url"].(string); ok {
  371. contentList = append(contentList, MediaContent{
  372. Type: ContentTypeVideoUrl,
  373. VideoUrl: &MessageVideoUrl{
  374. Url: videoUrl,
  375. },
  376. })
  377. }
  378. }
  379. }
  380. if len(contentList) > 0 {
  381. m.parsedContent = contentList
  382. }
  383. return contentList
  384. }
  385. // old code
  386. /*func (m *Message) StringContent() string {
  387. if m.parsedStringContent != nil {
  388. return *m.parsedStringContent
  389. }
  390. var stringContent string
  391. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  392. m.parsedStringContent = &stringContent
  393. return stringContent
  394. }
  395. contentStr := new(strings.Builder)
  396. arrayContent := m.ParseContent()
  397. for _, content := range arrayContent {
  398. if content.Type == ContentTypeText {
  399. contentStr.WriteString(content.Text)
  400. }
  401. }
  402. stringContent = contentStr.String()
  403. m.parsedStringContent = &stringContent
  404. return stringContent
  405. }
  406. func (m *Message) SetNullContent() {
  407. m.Content = nil
  408. m.parsedStringContent = nil
  409. m.parsedContent = nil
  410. }
  411. func (m *Message) SetStringContent(content string) {
  412. jsonContent, _ := json.Marshal(content)
  413. m.Content = jsonContent
  414. m.parsedStringContent = &content
  415. m.parsedContent = nil
  416. }
  417. func (m *Message) SetMediaContent(content []MediaContent) {
  418. jsonContent, _ := json.Marshal(content)
  419. m.Content = jsonContent
  420. m.parsedContent = nil
  421. m.parsedStringContent = nil
  422. }
  423. func (m *Message) IsStringContent() bool {
  424. if m.parsedStringContent != nil {
  425. return true
  426. }
  427. var stringContent string
  428. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  429. m.parsedStringContent = &stringContent
  430. return true
  431. }
  432. return false
  433. }
  434. func (m *Message) ParseContent() []MediaContent {
  435. if m.parsedContent != nil {
  436. return m.parsedContent
  437. }
  438. var contentList []MediaContent
  439. // 先尝试解析为字符串
  440. var stringContent string
  441. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  442. contentList = []MediaContent{{
  443. Type: ContentTypeText,
  444. Text: stringContent,
  445. }}
  446. m.parsedContent = contentList
  447. return contentList
  448. }
  449. // 尝试解析为数组
  450. var arrayContent []map[string]interface{}
  451. if err := json.Unmarshal(m.Content, &arrayContent); err == nil {
  452. for _, contentItem := range arrayContent {
  453. contentType, ok := contentItem["type"].(string)
  454. if !ok {
  455. continue
  456. }
  457. switch contentType {
  458. case ContentTypeText:
  459. if text, ok := contentItem["text"].(string); ok {
  460. contentList = append(contentList, MediaContent{
  461. Type: ContentTypeText,
  462. Text: text,
  463. })
  464. }
  465. case ContentTypeImageURL:
  466. imageUrl := contentItem["image_url"]
  467. temp := &MessageImageUrl{
  468. Detail: "high",
  469. }
  470. switch v := imageUrl.(type) {
  471. case string:
  472. temp.Url = v
  473. case map[string]interface{}:
  474. url, ok1 := v["url"].(string)
  475. detail, ok2 := v["detail"].(string)
  476. if ok2 {
  477. temp.Detail = detail
  478. }
  479. if ok1 {
  480. temp.Url = url
  481. }
  482. }
  483. contentList = append(contentList, MediaContent{
  484. Type: ContentTypeImageURL,
  485. ImageUrl: temp,
  486. })
  487. case ContentTypeInputAudio:
  488. if audioData, ok := contentItem["input_audio"].(map[string]interface{}); ok {
  489. data, ok1 := audioData["data"].(string)
  490. format, ok2 := audioData["format"].(string)
  491. if ok1 && ok2 {
  492. temp := &MessageInputAudio{
  493. Data: data,
  494. Format: format,
  495. }
  496. contentList = append(contentList, MediaContent{
  497. Type: ContentTypeInputAudio,
  498. InputAudio: temp,
  499. })
  500. }
  501. }
  502. case ContentTypeFile:
  503. if fileData, ok := contentItem["file"].(map[string]interface{}); ok {
  504. fileId, ok3 := fileData["file_id"].(string)
  505. if ok3 {
  506. contentList = append(contentList, MediaContent{
  507. Type: ContentTypeFile,
  508. File: &MessageFile{
  509. FileId: fileId,
  510. },
  511. })
  512. } else {
  513. fileName, ok1 := fileData["filename"].(string)
  514. fileDataStr, ok2 := fileData["file_data"].(string)
  515. if ok1 && ok2 {
  516. contentList = append(contentList, MediaContent{
  517. Type: ContentTypeFile,
  518. File: &MessageFile{
  519. FileName: fileName,
  520. FileData: fileDataStr,
  521. },
  522. })
  523. }
  524. }
  525. }
  526. case ContentTypeVideoUrl:
  527. if videoUrl, ok := contentItem["video_url"].(string); ok {
  528. contentList = append(contentList, MediaContent{
  529. Type: ContentTypeVideoUrl,
  530. VideoUrl: &MessageVideoUrl{
  531. Url: videoUrl,
  532. },
  533. })
  534. }
  535. }
  536. }
  537. }
  538. if len(contentList) > 0 {
  539. m.parsedContent = contentList
  540. }
  541. return contentList
  542. }*/
  543. type WebSearchOptions struct {
  544. SearchContextSize string `json:"search_context_size,omitempty"`
  545. UserLocation json.RawMessage `json:"user_location,omitempty"`
  546. }
  547. // https://platform.openai.com/docs/api-reference/responses/create
  548. type OpenAIResponsesRequest struct {
  549. Model string `json:"model"`
  550. Input json.RawMessage `json:"input,omitempty"`
  551. Include json.RawMessage `json:"include,omitempty"`
  552. Instructions json.RawMessage `json:"instructions,omitempty"`
  553. MaxOutputTokens uint `json:"max_output_tokens,omitempty"`
  554. Metadata json.RawMessage `json:"metadata,omitempty"`
  555. ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
  556. PreviousResponseID string `json:"previous_response_id,omitempty"`
  557. Reasoning *Reasoning `json:"reasoning,omitempty"`
  558. ServiceTier string `json:"service_tier,omitempty"`
  559. Store bool `json:"store,omitempty"`
  560. Stream bool `json:"stream,omitempty"`
  561. Temperature float64 `json:"temperature,omitempty"`
  562. Text json.RawMessage `json:"text,omitempty"`
  563. ToolChoice json.RawMessage `json:"tool_choice,omitempty"`
  564. Tools []map[string]any `json:"tools,omitempty"` // 需要处理的参数很少,MCP 参数太多不确定,所以用 map
  565. TopP float64 `json:"top_p,omitempty"`
  566. Truncation string `json:"truncation,omitempty"`
  567. User string `json:"user,omitempty"`
  568. MaxToolCalls uint `json:"max_tool_calls,omitempty"`
  569. Prompt json.RawMessage `json:"prompt,omitempty"`
  570. }
  571. type Reasoning struct {
  572. Effort string `json:"effort,omitempty"`
  573. Summary string `json:"summary,omitempty"`
  574. }
  575. //type ResponsesToolsCall struct {
  576. // Type string `json:"type"`
  577. // // Web Search
  578. // UserLocation json.RawMessage `json:"user_location,omitempty"`
  579. // SearchContextSize string `json:"search_context_size,omitempty"`
  580. // // File Search
  581. // VectorStoreIds []string `json:"vector_store_ids,omitempty"`
  582. // MaxNumResults uint `json:"max_num_results,omitempty"`
  583. // Filters json.RawMessage `json:"filters,omitempty"`
  584. // // Computer Use
  585. // DisplayWidth uint `json:"display_width,omitempty"`
  586. // DisplayHeight uint `json:"display_height,omitempty"`
  587. // Environment string `json:"environment,omitempty"`
  588. // // Function
  589. // Name string `json:"name,omitempty"`
  590. // Description string `json:"description,omitempty"`
  591. // Parameters json.RawMessage `json:"parameters,omitempty"`
  592. // Function json.RawMessage `json:"function,omitempty"`
  593. // Container json.RawMessage `json:"container,omitempty"`
  594. //}