openai_request.go 19 KB

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