openai_request.go 19 KB

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