openai_request.go 17 KB

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