openai_request.go 18 KB

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