openai_request.go 18 KB

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