openai_request.go 19 KB

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