openai_request.go 19 KB

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