openai_request.go 18 KB

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