openai_request.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. package dto
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "one-api/common"
  6. "one-api/types"
  7. "strings"
  8. "github.com/gin-gonic/gin"
  9. )
  10. type ResponseFormat struct {
  11. Type string `json:"type,omitempty"`
  12. JsonSchema json.RawMessage `json:"json_schema,omitempty"`
  13. }
  14. type FormatJsonSchema struct {
  15. Description string `json:"description,omitempty"`
  16. Name string `json:"name"`
  17. Schema any `json:"schema,omitempty"`
  18. Strict json.RawMessage `json:"strict,omitempty"`
  19. }
  20. type GeneralOpenAIRequest struct {
  21. Model string `json:"model,omitempty"`
  22. Messages []Message `json:"messages,omitempty"`
  23. Prompt any `json:"prompt,omitempty"`
  24. Prefix any `json:"prefix,omitempty"`
  25. Suffix any `json:"suffix,omitempty"`
  26. Stream bool `json:"stream,omitempty"`
  27. StreamOptions *StreamOptions `json:"stream_options,omitempty"`
  28. MaxTokens uint `json:"max_tokens,omitempty"`
  29. MaxCompletionTokens uint `json:"max_completion_tokens,omitempty"`
  30. ReasoningEffort string `json:"reasoning_effort,omitempty"`
  31. Verbosity json.RawMessage `json:"verbosity,omitempty"` // gpt-5
  32. Temperature *float64 `json:"temperature,omitempty"`
  33. TopP float64 `json:"top_p,omitempty"`
  34. TopK int `json:"top_k,omitempty"`
  35. Stop any `json:"stop,omitempty"`
  36. N int `json:"n,omitempty"`
  37. Input any `json:"input,omitempty"`
  38. Instruction string `json:"instruction,omitempty"`
  39. Size string `json:"size,omitempty"`
  40. Functions json.RawMessage `json:"functions,omitempty"`
  41. FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
  42. PresencePenalty float64 `json:"presence_penalty,omitempty"`
  43. ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
  44. EncodingFormat json.RawMessage `json:"encoding_format,omitempty"`
  45. Seed float64 `json:"seed,omitempty"`
  46. ParallelTooCalls *bool `json:"parallel_tool_calls,omitempty"`
  47. Tools []ToolCallRequest `json:"tools,omitempty"`
  48. ToolChoice any `json:"tool_choice,omitempty"`
  49. User string `json:"user,omitempty"`
  50. LogProbs bool `json:"logprobs,omitempty"`
  51. TopLogProbs int `json:"top_logprobs,omitempty"`
  52. Dimensions int `json:"dimensions,omitempty"`
  53. Modalities json.RawMessage `json:"modalities,omitempty"`
  54. Audio json.RawMessage `json:"audio,omitempty"`
  55. EnableThinking any `json:"enable_thinking,omitempty"` // ali
  56. THINKING json.RawMessage `json:"thinking,omitempty"` // doubao,zhipu_v4
  57. ExtraBody json.RawMessage `json:"extra_body,omitempty"`
  58. SearchParameters any `json:"search_parameters,omitempty"` //xai
  59. WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty"`
  60. // OpenRouter Params
  61. Usage json.RawMessage `json:"usage,omitempty"`
  62. Reasoning json.RawMessage `json:"reasoning,omitempty"`
  63. // Ali Qwen Params
  64. VlHighResolutionImages json.RawMessage `json:"vl_high_resolution_images,omitempty"`
  65. // 用匿名参数接收额外参数,例如ollama的think参数在此接收
  66. Extra map[string]json.RawMessage `json:"-"`
  67. }
  68. func (r *GeneralOpenAIRequest) GetTokenCountMeta() *types.TokenCountMeta {
  69. var tokenCountMeta types.TokenCountMeta
  70. var texts = make([]string, 0)
  71. var fileMeta = make([]*types.FileMeta, 0)
  72. if r.Prompt != nil {
  73. switch v := r.Prompt.(type) {
  74. case string:
  75. texts = append(texts, v)
  76. case []any:
  77. for _, item := range v {
  78. if str, ok := item.(string); ok {
  79. texts = append(texts, str)
  80. }
  81. }
  82. default:
  83. texts = append(texts, fmt.Sprintf("%v", r.Prompt))
  84. }
  85. }
  86. if r.Input != nil {
  87. inputs := r.ParseInput()
  88. texts = append(texts, inputs...)
  89. }
  90. if r.MaxCompletionTokens > r.MaxTokens {
  91. tokenCountMeta.MaxTokens = int(r.MaxCompletionTokens)
  92. } else {
  93. tokenCountMeta.MaxTokens = int(r.MaxTokens)
  94. }
  95. for _, message := range r.Messages {
  96. tokenCountMeta.MessagesCount++
  97. texts = append(texts, message.Role)
  98. if message.Content != nil {
  99. if message.Name != nil {
  100. tokenCountMeta.NameCount++
  101. texts = append(texts, *message.Name)
  102. }
  103. arrayContent := message.ParseContent()
  104. for _, m := range arrayContent {
  105. if m.Type == ContentTypeImageURL {
  106. imageUrl := m.GetImageMedia()
  107. if imageUrl != nil {
  108. if imageUrl.Url != "" {
  109. meta := &types.FileMeta{
  110. FileType: types.FileTypeImage,
  111. }
  112. meta.OriginData = imageUrl.Url
  113. meta.Detail = imageUrl.Detail
  114. fileMeta = append(fileMeta, meta)
  115. }
  116. }
  117. } else if m.Type == ContentTypeInputAudio {
  118. inputAudio := m.GetInputAudio()
  119. if inputAudio != nil {
  120. meta := &types.FileMeta{
  121. FileType: types.FileTypeAudio,
  122. }
  123. meta.OriginData = inputAudio.Data
  124. fileMeta = append(fileMeta, meta)
  125. }
  126. } else if m.Type == ContentTypeFile {
  127. file := m.GetFile()
  128. if file != nil {
  129. meta := &types.FileMeta{
  130. FileType: types.FileTypeFile,
  131. }
  132. meta.OriginData = file.FileData
  133. fileMeta = append(fileMeta, meta)
  134. }
  135. } else if m.Type == ContentTypeVideoUrl {
  136. videoUrl := m.GetVideoUrl()
  137. if videoUrl != nil && videoUrl.Url != "" {
  138. meta := &types.FileMeta{
  139. FileType: types.FileTypeVideo,
  140. }
  141. meta.OriginData = videoUrl.Url
  142. fileMeta = append(fileMeta, meta)
  143. }
  144. } else {
  145. texts = append(texts, m.Text)
  146. }
  147. }
  148. }
  149. }
  150. if r.Tools != nil {
  151. openaiTools := r.Tools
  152. for _, tool := range openaiTools {
  153. tokenCountMeta.ToolsCount++
  154. texts = append(texts, tool.Function.Name)
  155. if tool.Function.Description != "" {
  156. texts = append(texts, tool.Function.Description)
  157. }
  158. if tool.Function.Parameters != nil {
  159. texts = append(texts, fmt.Sprintf("%v", tool.Function.Parameters))
  160. }
  161. }
  162. //toolTokens := CountTokenInput(countStr, request.Model)
  163. //tkm += 8
  164. //tkm += toolTokens
  165. }
  166. tokenCountMeta.CombineText = strings.Join(texts, "\n")
  167. tokenCountMeta.Files = fileMeta
  168. return &tokenCountMeta
  169. }
  170. func (r *GeneralOpenAIRequest) IsStream(c *gin.Context) bool {
  171. return r.Stream
  172. }
  173. func (r *GeneralOpenAIRequest) ToMap() map[string]any {
  174. result := make(map[string]any)
  175. data, _ := common.Marshal(r)
  176. _ = common.Unmarshal(data, &result)
  177. return result
  178. }
  179. func (r *GeneralOpenAIRequest) GetSystemRoleName() string {
  180. if strings.HasPrefix(r.Model, "o") {
  181. if !strings.HasPrefix(r.Model, "o1-mini") && !strings.HasPrefix(r.Model, "o1-preview") {
  182. return "developer"
  183. }
  184. } else if strings.HasPrefix(r.Model, "gpt-5") {
  185. return "developer"
  186. }
  187. return "system"
  188. }
  189. type ToolCallRequest struct {
  190. ID string `json:"id,omitempty"`
  191. Type string `json:"type"`
  192. Function FunctionRequest `json:"function"`
  193. }
  194. type FunctionRequest struct {
  195. Description string `json:"description,omitempty"`
  196. Name string `json:"name"`
  197. Parameters any `json:"parameters,omitempty"`
  198. Arguments string `json:"arguments,omitempty"`
  199. }
  200. type StreamOptions struct {
  201. IncludeUsage bool `json:"include_usage,omitempty"`
  202. }
  203. func (r *GeneralOpenAIRequest) GetMaxTokens() uint {
  204. if r.MaxCompletionTokens != 0 {
  205. return r.MaxCompletionTokens
  206. }
  207. return r.MaxTokens
  208. }
  209. func (r *GeneralOpenAIRequest) ParseInput() []string {
  210. if r.Input == nil {
  211. return nil
  212. }
  213. var input []string
  214. switch r.Input.(type) {
  215. case string:
  216. input = []string{r.Input.(string)}
  217. case []any:
  218. input = make([]string, 0, len(r.Input.([]any)))
  219. for _, item := range r.Input.([]any) {
  220. if str, ok := item.(string); ok {
  221. input = append(input, str)
  222. }
  223. }
  224. }
  225. return input
  226. }
  227. type Message struct {
  228. Role string `json:"role"`
  229. Content any `json:"content"`
  230. Name *string `json:"name,omitempty"`
  231. Prefix *bool `json:"prefix,omitempty"`
  232. ReasoningContent string `json:"reasoning_content,omitempty"`
  233. Reasoning string `json:"reasoning,omitempty"`
  234. ToolCalls json.RawMessage `json:"tool_calls,omitempty"`
  235. ToolCallId string `json:"tool_call_id,omitempty"`
  236. parsedContent []MediaContent
  237. //parsedStringContent *string
  238. }
  239. type MediaContent struct {
  240. Type string `json:"type"`
  241. Text string `json:"text,omitempty"`
  242. ImageUrl any `json:"image_url,omitempty"`
  243. InputAudio any `json:"input_audio,omitempty"`
  244. File any `json:"file,omitempty"`
  245. VideoUrl any `json:"video_url,omitempty"`
  246. // OpenRouter Params
  247. CacheControl json.RawMessage `json:"cache_control,omitempty"`
  248. }
  249. func (m *MediaContent) GetImageMedia() *MessageImageUrl {
  250. if m.ImageUrl != nil {
  251. if _, ok := m.ImageUrl.(*MessageImageUrl); ok {
  252. return m.ImageUrl.(*MessageImageUrl)
  253. }
  254. if itemMap, ok := m.ImageUrl.(map[string]any); ok {
  255. out := &MessageImageUrl{
  256. Url: common.Interface2String(itemMap["url"]),
  257. Detail: common.Interface2String(itemMap["detail"]),
  258. MimeType: common.Interface2String(itemMap["mime_type"]),
  259. }
  260. return out
  261. }
  262. }
  263. return nil
  264. }
  265. func (m *MediaContent) GetInputAudio() *MessageInputAudio {
  266. if m.InputAudio != nil {
  267. if _, ok := m.InputAudio.(*MessageInputAudio); ok {
  268. return m.InputAudio.(*MessageInputAudio)
  269. }
  270. if itemMap, ok := m.InputAudio.(map[string]any); ok {
  271. out := &MessageInputAudio{
  272. Data: common.Interface2String(itemMap["data"]),
  273. Format: common.Interface2String(itemMap["format"]),
  274. }
  275. return out
  276. }
  277. }
  278. return nil
  279. }
  280. func (m *MediaContent) GetFile() *MessageFile {
  281. if m.File != nil {
  282. if _, ok := m.File.(*MessageFile); ok {
  283. return m.File.(*MessageFile)
  284. }
  285. if itemMap, ok := m.File.(map[string]any); ok {
  286. out := &MessageFile{
  287. FileName: common.Interface2String(itemMap["file_name"]),
  288. FileData: common.Interface2String(itemMap["file_data"]),
  289. FileId: common.Interface2String(itemMap["file_id"]),
  290. }
  291. return out
  292. }
  293. }
  294. return nil
  295. }
  296. func (m *MediaContent) GetVideoUrl() *MessageVideoUrl {
  297. if m.VideoUrl != nil {
  298. if _, ok := m.VideoUrl.(*MessageVideoUrl); ok {
  299. return m.VideoUrl.(*MessageVideoUrl)
  300. }
  301. if itemMap, ok := m.VideoUrl.(map[string]any); ok {
  302. out := &MessageVideoUrl{
  303. Url: common.Interface2String(itemMap["url"]),
  304. }
  305. return out
  306. }
  307. }
  308. return nil
  309. }
  310. type MessageImageUrl struct {
  311. Url string `json:"url"`
  312. Detail string `json:"detail"`
  313. MimeType string
  314. }
  315. func (m *MessageImageUrl) IsRemoteImage() bool {
  316. return strings.HasPrefix(m.Url, "http")
  317. }
  318. type MessageInputAudio struct {
  319. Data string `json:"data"` //base64
  320. Format string `json:"format"`
  321. }
  322. type MessageFile struct {
  323. FileName string `json:"filename,omitempty"`
  324. FileData string `json:"file_data,omitempty"`
  325. FileId string `json:"file_id,omitempty"`
  326. }
  327. type MessageVideoUrl struct {
  328. Url string `json:"url"`
  329. }
  330. const (
  331. ContentTypeText = "text"
  332. ContentTypeImageURL = "image_url"
  333. ContentTypeInputAudio = "input_audio"
  334. ContentTypeFile = "file"
  335. ContentTypeVideoUrl = "video_url" // 阿里百炼视频识别
  336. //ContentTypeAudioUrl = "audio_url"
  337. )
  338. func (m *Message) GetPrefix() bool {
  339. if m.Prefix == nil {
  340. return false
  341. }
  342. return *m.Prefix
  343. }
  344. func (m *Message) SetPrefix(prefix bool) {
  345. m.Prefix = &prefix
  346. }
  347. func (m *Message) ParseToolCalls() []ToolCallRequest {
  348. if m.ToolCalls == nil {
  349. return nil
  350. }
  351. var toolCalls []ToolCallRequest
  352. if err := json.Unmarshal(m.ToolCalls, &toolCalls); err == nil {
  353. return toolCalls
  354. }
  355. return toolCalls
  356. }
  357. func (m *Message) SetToolCalls(toolCalls any) {
  358. toolCallsJson, _ := json.Marshal(toolCalls)
  359. m.ToolCalls = toolCallsJson
  360. }
  361. func (m *Message) StringContent() string {
  362. switch m.Content.(type) {
  363. case string:
  364. return m.Content.(string)
  365. case []any:
  366. var contentStr string
  367. for _, contentItem := range m.Content.([]any) {
  368. contentMap, ok := contentItem.(map[string]any)
  369. if !ok {
  370. continue
  371. }
  372. if contentMap["type"] == ContentTypeText {
  373. if subStr, ok := contentMap["text"].(string); ok {
  374. contentStr += subStr
  375. }
  376. }
  377. }
  378. return contentStr
  379. }
  380. return ""
  381. }
  382. func (m *Message) SetNullContent() {
  383. m.Content = nil
  384. m.parsedContent = nil
  385. }
  386. func (m *Message) SetStringContent(content string) {
  387. m.Content = content
  388. m.parsedContent = nil
  389. }
  390. func (m *Message) SetMediaContent(content []MediaContent) {
  391. m.Content = content
  392. m.parsedContent = content
  393. }
  394. func (m *Message) IsStringContent() bool {
  395. _, ok := m.Content.(string)
  396. if ok {
  397. return true
  398. }
  399. return false
  400. }
  401. func (m *Message) ParseContent() []MediaContent {
  402. if m.Content == nil {
  403. return nil
  404. }
  405. if len(m.parsedContent) > 0 {
  406. return m.parsedContent
  407. }
  408. var contentList []MediaContent
  409. // 先尝试解析为字符串
  410. content, ok := m.Content.(string)
  411. if ok {
  412. contentList = []MediaContent{{
  413. Type: ContentTypeText,
  414. Text: content,
  415. }}
  416. m.parsedContent = contentList
  417. return contentList
  418. }
  419. // 尝试解析为数组
  420. //var arrayContent []map[string]interface{}
  421. arrayContent, ok := m.Content.([]any)
  422. if !ok {
  423. return contentList
  424. }
  425. for _, contentItemAny := range arrayContent {
  426. mediaItem, ok := contentItemAny.(MediaContent)
  427. if ok {
  428. contentList = append(contentList, mediaItem)
  429. continue
  430. }
  431. contentItem, ok := contentItemAny.(map[string]any)
  432. if !ok {
  433. continue
  434. }
  435. contentType, ok := contentItem["type"].(string)
  436. if !ok {
  437. continue
  438. }
  439. switch contentType {
  440. case ContentTypeText:
  441. if text, ok := contentItem["text"].(string); ok {
  442. contentList = append(contentList, MediaContent{
  443. Type: ContentTypeText,
  444. Text: text,
  445. })
  446. }
  447. case ContentTypeImageURL:
  448. imageUrl := contentItem["image_url"]
  449. temp := &MessageImageUrl{
  450. Detail: "high",
  451. }
  452. switch v := imageUrl.(type) {
  453. case string:
  454. temp.Url = v
  455. case map[string]interface{}:
  456. url, ok1 := v["url"].(string)
  457. detail, ok2 := v["detail"].(string)
  458. if ok2 {
  459. temp.Detail = detail
  460. }
  461. if ok1 {
  462. temp.Url = url
  463. }
  464. }
  465. contentList = append(contentList, MediaContent{
  466. Type: ContentTypeImageURL,
  467. ImageUrl: temp,
  468. })
  469. case ContentTypeInputAudio:
  470. if audioData, ok := contentItem["input_audio"].(map[string]interface{}); ok {
  471. data, ok1 := audioData["data"].(string)
  472. format, ok2 := audioData["format"].(string)
  473. if ok1 && ok2 {
  474. temp := &MessageInputAudio{
  475. Data: data,
  476. Format: format,
  477. }
  478. contentList = append(contentList, MediaContent{
  479. Type: ContentTypeInputAudio,
  480. InputAudio: temp,
  481. })
  482. }
  483. }
  484. case ContentTypeFile:
  485. if fileData, ok := contentItem["file"].(map[string]interface{}); ok {
  486. fileId, ok3 := fileData["file_id"].(string)
  487. if ok3 {
  488. contentList = append(contentList, MediaContent{
  489. Type: ContentTypeFile,
  490. File: &MessageFile{
  491. FileId: fileId,
  492. },
  493. })
  494. } else {
  495. fileName, ok1 := fileData["filename"].(string)
  496. fileDataStr, ok2 := fileData["file_data"].(string)
  497. if ok1 && ok2 {
  498. contentList = append(contentList, MediaContent{
  499. Type: ContentTypeFile,
  500. File: &MessageFile{
  501. FileName: fileName,
  502. FileData: fileDataStr,
  503. },
  504. })
  505. }
  506. }
  507. }
  508. case ContentTypeVideoUrl:
  509. if videoUrl, ok := contentItem["video_url"].(string); ok {
  510. contentList = append(contentList, MediaContent{
  511. Type: ContentTypeVideoUrl,
  512. VideoUrl: &MessageVideoUrl{
  513. Url: videoUrl,
  514. },
  515. })
  516. }
  517. }
  518. }
  519. if len(contentList) > 0 {
  520. m.parsedContent = contentList
  521. }
  522. return contentList
  523. }
  524. // old code
  525. /*func (m *Message) StringContent() string {
  526. if m.parsedStringContent != nil {
  527. return *m.parsedStringContent
  528. }
  529. var stringContent string
  530. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  531. m.parsedStringContent = &stringContent
  532. return stringContent
  533. }
  534. contentStr := new(strings.Builder)
  535. arrayContent := m.ParseContent()
  536. for _, content := range arrayContent {
  537. if content.Type == ContentTypeText {
  538. contentStr.WriteString(content.Text)
  539. }
  540. }
  541. stringContent = contentStr.String()
  542. m.parsedStringContent = &stringContent
  543. return stringContent
  544. }
  545. func (m *Message) SetNullContent() {
  546. m.Content = nil
  547. m.parsedStringContent = nil
  548. m.parsedContent = nil
  549. }
  550. func (m *Message) SetStringContent(content string) {
  551. jsonContent, _ := json.Marshal(content)
  552. m.Content = jsonContent
  553. m.parsedStringContent = &content
  554. m.parsedContent = nil
  555. }
  556. func (m *Message) SetMediaContent(content []MediaContent) {
  557. jsonContent, _ := json.Marshal(content)
  558. m.Content = jsonContent
  559. m.parsedContent = nil
  560. m.parsedStringContent = nil
  561. }
  562. func (m *Message) IsStringContent() bool {
  563. if m.parsedStringContent != nil {
  564. return true
  565. }
  566. var stringContent string
  567. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  568. m.parsedStringContent = &stringContent
  569. return true
  570. }
  571. return false
  572. }
  573. func (m *Message) ParseContent() []MediaContent {
  574. if m.parsedContent != nil {
  575. return m.parsedContent
  576. }
  577. var contentList []MediaContent
  578. // 先尝试解析为字符串
  579. var stringContent string
  580. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  581. contentList = []MediaContent{{
  582. Type: ContentTypeText,
  583. Text: stringContent,
  584. }}
  585. m.parsedContent = contentList
  586. return contentList
  587. }
  588. // 尝试解析为数组
  589. var arrayContent []map[string]interface{}
  590. if err := json.Unmarshal(m.Content, &arrayContent); err == nil {
  591. for _, contentItem := range arrayContent {
  592. contentType, ok := contentItem["type"].(string)
  593. if !ok {
  594. continue
  595. }
  596. switch contentType {
  597. case ContentTypeText:
  598. if text, ok := contentItem["text"].(string); ok {
  599. contentList = append(contentList, MediaContent{
  600. Type: ContentTypeText,
  601. Text: text,
  602. })
  603. }
  604. case ContentTypeImageURL:
  605. imageUrl := contentItem["image_url"]
  606. temp := &MessageImageUrl{
  607. Detail: "high",
  608. }
  609. switch v := imageUrl.(type) {
  610. case string:
  611. temp.Url = v
  612. case map[string]interface{}:
  613. url, ok1 := v["url"].(string)
  614. detail, ok2 := v["detail"].(string)
  615. if ok2 {
  616. temp.Detail = detail
  617. }
  618. if ok1 {
  619. temp.Url = url
  620. }
  621. }
  622. contentList = append(contentList, MediaContent{
  623. Type: ContentTypeImageURL,
  624. ImageUrl: temp,
  625. })
  626. case ContentTypeInputAudio:
  627. if audioData, ok := contentItem["input_audio"].(map[string]interface{}); ok {
  628. data, ok1 := audioData["data"].(string)
  629. format, ok2 := audioData["format"].(string)
  630. if ok1 && ok2 {
  631. temp := &MessageInputAudio{
  632. Data: data,
  633. Format: format,
  634. }
  635. contentList = append(contentList, MediaContent{
  636. Type: ContentTypeInputAudio,
  637. InputAudio: temp,
  638. })
  639. }
  640. }
  641. case ContentTypeFile:
  642. if fileData, ok := contentItem["file"].(map[string]interface{}); ok {
  643. fileId, ok3 := fileData["file_id"].(string)
  644. if ok3 {
  645. contentList = append(contentList, MediaContent{
  646. Type: ContentTypeFile,
  647. File: &MessageFile{
  648. FileId: fileId,
  649. },
  650. })
  651. } else {
  652. fileName, ok1 := fileData["filename"].(string)
  653. fileDataStr, ok2 := fileData["file_data"].(string)
  654. if ok1 && ok2 {
  655. contentList = append(contentList, MediaContent{
  656. Type: ContentTypeFile,
  657. File: &MessageFile{
  658. FileName: fileName,
  659. FileData: fileDataStr,
  660. },
  661. })
  662. }
  663. }
  664. }
  665. case ContentTypeVideoUrl:
  666. if videoUrl, ok := contentItem["video_url"].(string); ok {
  667. contentList = append(contentList, MediaContent{
  668. Type: ContentTypeVideoUrl,
  669. VideoUrl: &MessageVideoUrl{
  670. Url: videoUrl,
  671. },
  672. })
  673. }
  674. }
  675. }
  676. }
  677. if len(contentList) > 0 {
  678. m.parsedContent = contentList
  679. }
  680. return contentList
  681. }*/
  682. type WebSearchOptions struct {
  683. SearchContextSize string `json:"search_context_size,omitempty"`
  684. UserLocation json.RawMessage `json:"user_location,omitempty"`
  685. }
  686. // https://platform.openai.com/docs/api-reference/responses/create
  687. type OpenAIResponsesRequest struct {
  688. Model string `json:"model"`
  689. Input any `json:"input,omitempty"`
  690. Include json.RawMessage `json:"include,omitempty"`
  691. Instructions json.RawMessage `json:"instructions,omitempty"`
  692. MaxOutputTokens uint `json:"max_output_tokens,omitempty"`
  693. Metadata json.RawMessage `json:"metadata,omitempty"`
  694. ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
  695. PreviousResponseID string `json:"previous_response_id,omitempty"`
  696. Reasoning *Reasoning `json:"reasoning,omitempty"`
  697. ServiceTier string `json:"service_tier,omitempty"`
  698. Store bool `json:"store,omitempty"`
  699. Stream bool `json:"stream,omitempty"`
  700. Temperature float64 `json:"temperature,omitempty"`
  701. Text json.RawMessage `json:"text,omitempty"`
  702. ToolChoice json.RawMessage `json:"tool_choice,omitempty"`
  703. Tools []map[string]any `json:"tools,omitempty"` // 需要处理的参数很少,MCP 参数太多不确定,所以用 map
  704. TopP float64 `json:"top_p,omitempty"`
  705. Truncation string `json:"truncation,omitempty"`
  706. User string `json:"user,omitempty"`
  707. MaxToolCalls uint `json:"max_tool_calls,omitempty"`
  708. Prompt json.RawMessage `json:"prompt,omitempty"`
  709. }
  710. func (r *OpenAIResponsesRequest) GetTokenCountMeta() *types.TokenCountMeta {
  711. var fileMeta = make([]*types.FileMeta, 0)
  712. var texts = make([]string, 0)
  713. if r.Input != nil {
  714. inputs := r.ParseInput()
  715. for _, input := range inputs {
  716. if input.Type == "input_image" {
  717. if input.ImageUrl != "" {
  718. fileMeta = append(fileMeta, &types.FileMeta{
  719. FileType: types.FileTypeImage,
  720. OriginData: input.ImageUrl,
  721. Detail: input.Detail,
  722. })
  723. }
  724. } else if input.Type == "input_file" {
  725. if input.FileUrl != "" {
  726. fileMeta = append(fileMeta, &types.FileMeta{
  727. FileType: types.FileTypeFile,
  728. OriginData: input.FileUrl,
  729. })
  730. }
  731. } else {
  732. texts = append(texts, input.Text)
  733. }
  734. }
  735. }
  736. if len(r.Instructions) > 0 {
  737. texts = append(texts, string(r.Instructions))
  738. }
  739. if len(r.Metadata) > 0 {
  740. texts = append(texts, string(r.Metadata))
  741. }
  742. if len(r.Text) > 0 {
  743. texts = append(texts, string(r.Text))
  744. }
  745. if len(r.ToolChoice) > 0 {
  746. texts = append(texts, string(r.ToolChoice))
  747. }
  748. if len(r.Prompt) > 0 {
  749. texts = append(texts, string(r.Prompt))
  750. }
  751. if len(r.Tools) > 0 {
  752. toolStr, _ := common.Marshal(r.Tools)
  753. texts = append(texts, string(toolStr))
  754. }
  755. return &types.TokenCountMeta{
  756. CombineText: strings.Join(texts, "\n"),
  757. Files: fileMeta,
  758. MaxTokens: int(r.MaxOutputTokens),
  759. }
  760. }
  761. func (r *OpenAIResponsesRequest) IsStream(c *gin.Context) bool {
  762. return r.Stream
  763. }
  764. type Reasoning struct {
  765. Effort string `json:"effort,omitempty"`
  766. Summary string `json:"summary,omitempty"`
  767. }
  768. type MediaInput struct {
  769. Type string `json:"type"`
  770. Text string `json:"text,omitempty"`
  771. FileUrl string `json:"file_url,omitempty"`
  772. ImageUrl string `json:"image_url,omitempty"`
  773. Detail string `json:"detail,omitempty"` // 仅 input_image 有效
  774. }
  775. // ParseInput parses the Responses API `input` field into a normalized slice of MediaInput.
  776. // Reference implementation mirrors Message.ParseContent:
  777. // - input can be a string, treated as an input_text item
  778. // - input can be an array of objects with a `type` field
  779. // supported types: input_text, input_image, input_file
  780. func (r *OpenAIResponsesRequest) ParseInput() []MediaInput {
  781. if r.Input == nil {
  782. return nil
  783. }
  784. var inputs []MediaInput
  785. // Try string first
  786. if str, ok := r.Input.(string); ok {
  787. inputs = append(inputs, MediaInput{Type: "input_text", Text: str})
  788. return inputs
  789. }
  790. // Try array of parts
  791. if array, ok := r.Input.([]any); ok {
  792. for _, itemAny := range array {
  793. // Already parsed MediaInput
  794. if media, ok := itemAny.(MediaInput); ok {
  795. inputs = append(inputs, media)
  796. continue
  797. }
  798. // Generic map
  799. item, ok := itemAny.(map[string]any)
  800. if !ok {
  801. continue
  802. }
  803. typeVal, ok := item["type"].(string)
  804. if !ok {
  805. continue
  806. }
  807. switch typeVal {
  808. case "input_text":
  809. text, _ := item["text"].(string)
  810. inputs = append(inputs, MediaInput{Type: "input_text", Text: text})
  811. case "input_image":
  812. // image_url may be string or object with url field
  813. var imageUrl string
  814. switch v := item["image_url"].(type) {
  815. case string:
  816. imageUrl = v
  817. case map[string]any:
  818. if url, ok := v["url"].(string); ok {
  819. imageUrl = url
  820. }
  821. }
  822. inputs = append(inputs, MediaInput{Type: "input_image", ImageUrl: imageUrl})
  823. case "input_file":
  824. // file_url may be string or object with url field
  825. var fileUrl string
  826. switch v := item["file_url"].(type) {
  827. case string:
  828. fileUrl = v
  829. case map[string]any:
  830. if url, ok := v["url"].(string); ok {
  831. fileUrl = url
  832. }
  833. }
  834. inputs = append(inputs, MediaInput{Type: "input_file", FileUrl: fileUrl})
  835. }
  836. }
  837. }
  838. return inputs
  839. }