openai_request.go 18 KB

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