openai_request.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. package dto
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/QuantumNous/new-api/types"
  8. "github.com/samber/lo"
  9. "github.com/gin-gonic/gin"
  10. )
  11. type ResponseFormat struct {
  12. Type string `json:"type,omitempty"`
  13. JsonSchema json.RawMessage `json:"json_schema,omitempty"`
  14. }
  15. type FormatJsonSchema struct {
  16. Description string `json:"description,omitempty"`
  17. Name string `json:"name"`
  18. Schema any `json:"schema,omitempty"`
  19. Strict json.RawMessage `json:"strict,omitempty"`
  20. }
  21. // GeneralOpenAIRequest represents a general request structure for OpenAI-compatible APIs.
  22. // 参数增加规范:无引用的参数必须使用json.RawMessage类型,并添加omitempty标签
  23. type GeneralOpenAIRequest struct {
  24. Model string `json:"model,omitempty"`
  25. Messages []Message `json:"messages,omitempty"`
  26. Prompt any `json:"prompt,omitempty"`
  27. Prefix any `json:"prefix,omitempty"`
  28. Suffix any `json:"suffix,omitempty"`
  29. Stream *bool `json:"stream,omitempty"`
  30. StreamOptions *StreamOptions `json:"stream_options,omitempty"`
  31. MaxTokens *uint `json:"max_tokens,omitempty"`
  32. MaxCompletionTokens *uint `json:"max_completion_tokens,omitempty"`
  33. ReasoningEffort string `json:"reasoning_effort,omitempty"`
  34. Verbosity json.RawMessage `json:"verbosity,omitempty"` // gpt-5
  35. Temperature *float64 `json:"temperature,omitempty"`
  36. TopP *float64 `json:"top_p,omitempty"`
  37. TopK *int `json:"top_k,omitempty"`
  38. Stop any `json:"stop,omitempty"`
  39. N *int `json:"n,omitempty"`
  40. Input any `json:"input,omitempty"`
  41. Instruction string `json:"instruction,omitempty"`
  42. Size string `json:"size,omitempty"`
  43. Functions json.RawMessage `json:"functions,omitempty"`
  44. FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
  45. PresencePenalty *float64 `json:"presence_penalty,omitempty"`
  46. ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
  47. EncodingFormat json.RawMessage `json:"encoding_format,omitempty"`
  48. Seed *float64 `json:"seed,omitempty"`
  49. ParallelTooCalls *bool `json:"parallel_tool_calls,omitempty"`
  50. Tools []ToolCallRequest `json:"tools,omitempty"`
  51. ToolChoice any `json:"tool_choice,omitempty"`
  52. FunctionCall json.RawMessage `json:"function_call,omitempty"`
  53. User json.RawMessage `json:"user,omitempty"`
  54. // ServiceTier specifies upstream service level and may affect billing.
  55. // This field is filtered by default and can be enabled via channel setting allow_service_tier.
  56. ServiceTier json.RawMessage `json:"service_tier,omitempty"`
  57. LogProbs *bool `json:"logprobs,omitempty"`
  58. TopLogProbs *int `json:"top_logprobs,omitempty"`
  59. Dimensions *int `json:"dimensions,omitempty"`
  60. Modalities json.RawMessage `json:"modalities,omitempty"`
  61. Audio json.RawMessage `json:"audio,omitempty"`
  62. // 安全标识符,用于帮助 OpenAI 检测可能违反使用政策的应用程序用户
  63. // 注意:此字段会向 OpenAI 发送用户标识信息,默认过滤,可通过 allow_safety_identifier 开启
  64. SafetyIdentifier json.RawMessage `json:"safety_identifier,omitempty"`
  65. // Whether or not to store the output of this chat completion request for use in our model distillation or evals products.
  66. // 是否存储此次请求数据供 OpenAI 用于评估和优化产品
  67. // 注意:默认允许透传,可通过 disable_store 禁用;禁用后可能导致 Codex 无法正常使用
  68. Store json.RawMessage `json:"store,omitempty"`
  69. // Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the user field
  70. PromptCacheKey string `json:"prompt_cache_key,omitempty"`
  71. PromptCacheRetention json.RawMessage `json:"prompt_cache_retention,omitempty"`
  72. LogitBias json.RawMessage `json:"logit_bias,omitempty"`
  73. Metadata json.RawMessage `json:"metadata,omitempty"`
  74. Prediction json.RawMessage `json:"prediction,omitempty"`
  75. // gemini
  76. ExtraBody json.RawMessage `json:"extra_body,omitempty"`
  77. //xai
  78. SearchParameters json.RawMessage `json:"search_parameters,omitempty"`
  79. // claude
  80. WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty"`
  81. // OpenRouter Params
  82. Usage json.RawMessage `json:"usage,omitempty"`
  83. Reasoning json.RawMessage `json:"reasoning,omitempty"`
  84. // Ali Qwen Params
  85. VlHighResolutionImages json.RawMessage `json:"vl_high_resolution_images,omitempty"`
  86. EnableThinking json.RawMessage `json:"enable_thinking,omitempty"`
  87. ChatTemplateKwargs json.RawMessage `json:"chat_template_kwargs,omitempty"`
  88. EnableSearch json.RawMessage `json:"enable_search,omitempty"`
  89. // ollama Params
  90. Think json.RawMessage `json:"think,omitempty"`
  91. // baidu v2
  92. WebSearch json.RawMessage `json:"web_search,omitempty"`
  93. // doubao,zhipu_v4
  94. THINKING json.RawMessage `json:"thinking,omitempty"`
  95. // pplx Params
  96. SearchDomainFilter json.RawMessage `json:"search_domain_filter,omitempty"`
  97. SearchRecencyFilter json.RawMessage `json:"search_recency_filter,omitempty"`
  98. ReturnImages *bool `json:"return_images,omitempty"`
  99. ReturnRelatedQuestions *bool `json:"return_related_questions,omitempty"`
  100. SearchMode json.RawMessage `json:"search_mode,omitempty"`
  101. // Minimax
  102. ReasoningSplit json.RawMessage `json:"reasoning_split,omitempty"`
  103. }
  104. func (r *GeneralOpenAIRequest) GetTokenCountMeta() *types.TokenCountMeta {
  105. var tokenCountMeta types.TokenCountMeta
  106. var texts = make([]string, 0)
  107. var fileMeta = make([]*types.FileMeta, 0)
  108. if r.Prompt != nil {
  109. switch v := r.Prompt.(type) {
  110. case string:
  111. texts = append(texts, v)
  112. case []any:
  113. for _, item := range v {
  114. if str, ok := item.(string); ok {
  115. texts = append(texts, str)
  116. }
  117. }
  118. default:
  119. texts = append(texts, fmt.Sprintf("%v", r.Prompt))
  120. }
  121. }
  122. if r.Input != nil {
  123. inputs := r.ParseInput()
  124. texts = append(texts, inputs...)
  125. }
  126. maxTokens := lo.FromPtrOr(r.MaxTokens, uint(0))
  127. maxCompletionTokens := lo.FromPtrOr(r.MaxCompletionTokens, uint(0))
  128. if maxCompletionTokens > maxTokens {
  129. tokenCountMeta.MaxTokens = int(maxCompletionTokens)
  130. } else {
  131. tokenCountMeta.MaxTokens = int(maxTokens)
  132. }
  133. for _, message := range r.Messages {
  134. tokenCountMeta.MessagesCount++
  135. texts = append(texts, message.Role)
  136. if message.Content != nil {
  137. if message.Name != nil {
  138. tokenCountMeta.NameCount++
  139. texts = append(texts, *message.Name)
  140. }
  141. arrayContent := message.ParseContent()
  142. for _, m := range arrayContent {
  143. source := m.ToFileSource()
  144. if source != nil {
  145. meta := &types.FileMeta{Source: source}
  146. switch m.Type {
  147. case ContentTypeImageURL:
  148. meta.FileType = types.FileTypeImage
  149. if img := m.GetImageMedia(); img != nil {
  150. meta.Detail = img.Detail
  151. }
  152. case ContentTypeInputAudio:
  153. meta.FileType = types.FileTypeAudio
  154. case ContentTypeFile:
  155. meta.FileType = types.FileTypeFile
  156. case ContentTypeVideoUrl:
  157. meta.FileType = types.FileTypeVideo
  158. }
  159. fileMeta = append(fileMeta, meta)
  160. } else if m.Type == ContentTypeText {
  161. texts = append(texts, m.Text)
  162. }
  163. }
  164. }
  165. }
  166. if r.Tools != nil {
  167. openaiTools := r.Tools
  168. for _, tool := range openaiTools {
  169. tokenCountMeta.ToolsCount++
  170. texts = append(texts, tool.Function.Name)
  171. if tool.Function.Description != "" {
  172. texts = append(texts, tool.Function.Description)
  173. }
  174. if tool.Function.Parameters != nil {
  175. texts = append(texts, fmt.Sprintf("%v", tool.Function.Parameters))
  176. }
  177. }
  178. //toolTokens := CountTokenInput(countStr, request.Model)
  179. //tkm += 8
  180. //tkm += toolTokens
  181. }
  182. tokenCountMeta.CombineText = strings.Join(texts, "\n")
  183. tokenCountMeta.Files = fileMeta
  184. return &tokenCountMeta
  185. }
  186. func (r *GeneralOpenAIRequest) IsStream(c *gin.Context) bool {
  187. return lo.FromPtrOr(r.Stream, false)
  188. }
  189. func (r *GeneralOpenAIRequest) SetModelName(modelName string) {
  190. if modelName != "" {
  191. r.Model = modelName
  192. }
  193. }
  194. func (r *GeneralOpenAIRequest) ToMap() map[string]any {
  195. result := make(map[string]any)
  196. data, _ := common.Marshal(r)
  197. _ = common.Unmarshal(data, &result)
  198. return result
  199. }
  200. func (r *GeneralOpenAIRequest) GetSystemRoleName() string {
  201. if strings.HasPrefix(r.Model, "o") {
  202. if !strings.HasPrefix(r.Model, "o1-mini") && !strings.HasPrefix(r.Model, "o1-preview") {
  203. return "developer"
  204. }
  205. } else if strings.HasPrefix(r.Model, "gpt-5") {
  206. return "developer"
  207. }
  208. return "system"
  209. }
  210. const CustomType = "custom"
  211. type ToolCallRequest struct {
  212. ID string `json:"id,omitempty"`
  213. Type string `json:"type"`
  214. Function FunctionRequest `json:"function,omitempty"`
  215. Custom json.RawMessage `json:"custom,omitempty"`
  216. }
  217. type FunctionRequest struct {
  218. Description string `json:"description,omitempty"`
  219. Name string `json:"name"`
  220. Parameters any `json:"parameters,omitempty"`
  221. Arguments string `json:"arguments,omitempty"`
  222. }
  223. type StreamOptions struct {
  224. IncludeUsage bool `json:"include_usage,omitempty"`
  225. // IncludeObfuscation is only for /v1/responses stream payload.
  226. // This field is filtered by default and can be enabled via channel setting allow_include_obfuscation.
  227. IncludeObfuscation bool `json:"include_obfuscation,omitempty"`
  228. }
  229. func (r *GeneralOpenAIRequest) GetMaxTokens() uint {
  230. maxCompletionTokens := lo.FromPtrOr(r.MaxCompletionTokens, uint(0))
  231. if maxCompletionTokens != 0 {
  232. return maxCompletionTokens
  233. }
  234. return lo.FromPtrOr(r.MaxTokens, uint(0))
  235. }
  236. func (r *GeneralOpenAIRequest) ParseInput() []string {
  237. if r.Input == nil {
  238. return nil
  239. }
  240. var input []string
  241. switch r.Input.(type) {
  242. case string:
  243. input = []string{r.Input.(string)}
  244. case []any:
  245. input = make([]string, 0, len(r.Input.([]any)))
  246. for _, item := range r.Input.([]any) {
  247. if str, ok := item.(string); ok {
  248. input = append(input, str)
  249. }
  250. }
  251. }
  252. return input
  253. }
  254. type Message struct {
  255. Role string `json:"role"`
  256. Content any `json:"content"`
  257. Name *string `json:"name,omitempty"`
  258. Prefix *bool `json:"prefix,omitempty"`
  259. ReasoningContent string `json:"reasoning_content,omitempty"`
  260. Reasoning string `json:"reasoning,omitempty"`
  261. ToolCalls json.RawMessage `json:"tool_calls,omitempty"`
  262. ToolCallId string `json:"tool_call_id,omitempty"`
  263. parsedContent []MediaContent
  264. //parsedStringContent *string
  265. }
  266. type MediaContent struct {
  267. Type string `json:"type"`
  268. Text string `json:"text,omitempty"`
  269. ImageUrl any `json:"image_url,omitempty"`
  270. InputAudio any `json:"input_audio,omitempty"`
  271. File any `json:"file,omitempty"`
  272. VideoUrl any `json:"video_url,omitempty"`
  273. // OpenRouter Params
  274. CacheControl json.RawMessage `json:"cache_control,omitempty"`
  275. }
  276. func (m *MediaContent) GetImageMedia() *MessageImageUrl {
  277. if m.ImageUrl != nil {
  278. if _, ok := m.ImageUrl.(*MessageImageUrl); ok {
  279. return m.ImageUrl.(*MessageImageUrl)
  280. }
  281. if itemMap, ok := m.ImageUrl.(map[string]any); ok {
  282. out := &MessageImageUrl{
  283. Url: common.Interface2String(itemMap["url"]),
  284. Detail: common.Interface2String(itemMap["detail"]),
  285. MimeType: common.Interface2String(itemMap["mime_type"]),
  286. }
  287. return out
  288. }
  289. }
  290. return nil
  291. }
  292. func (m *MediaContent) GetInputAudio() *MessageInputAudio {
  293. if m.InputAudio != nil {
  294. if _, ok := m.InputAudio.(*MessageInputAudio); ok {
  295. return m.InputAudio.(*MessageInputAudio)
  296. }
  297. if itemMap, ok := m.InputAudio.(map[string]any); ok {
  298. out := &MessageInputAudio{
  299. Data: common.Interface2String(itemMap["data"]),
  300. Format: common.Interface2String(itemMap["format"]),
  301. }
  302. return out
  303. }
  304. }
  305. return nil
  306. }
  307. func (m *MediaContent) GetFile() *MessageFile {
  308. if m.File != nil {
  309. if _, ok := m.File.(*MessageFile); ok {
  310. return m.File.(*MessageFile)
  311. }
  312. if itemMap, ok := m.File.(map[string]any); ok {
  313. out := &MessageFile{
  314. FileName: common.Interface2String(itemMap["file_name"]),
  315. FileData: common.Interface2String(itemMap["file_data"]),
  316. FileId: common.Interface2String(itemMap["file_id"]),
  317. }
  318. return out
  319. }
  320. }
  321. return nil
  322. }
  323. func (m *MediaContent) GetVideoUrl() *MessageVideoUrl {
  324. if m.VideoUrl != nil {
  325. if _, ok := m.VideoUrl.(*MessageVideoUrl); ok {
  326. return m.VideoUrl.(*MessageVideoUrl)
  327. }
  328. if itemMap, ok := m.VideoUrl.(map[string]any); ok {
  329. out := &MessageVideoUrl{
  330. Url: common.Interface2String(itemMap["url"]),
  331. }
  332. return out
  333. }
  334. }
  335. return nil
  336. }
  337. func (m *MediaContent) ToFileSource() types.FileSource {
  338. switch m.Type {
  339. case ContentTypeImageURL:
  340. img := m.GetImageMedia()
  341. if img == nil || img.Url == "" {
  342. return nil
  343. }
  344. return types.NewFileSourceFromData(img.Url, img.MimeType)
  345. case ContentTypeInputAudio:
  346. audio := m.GetInputAudio()
  347. if audio == nil || audio.Data == "" {
  348. return nil
  349. }
  350. mimeType := ""
  351. if audio.Format != "" {
  352. mimeType = "audio/" + audio.Format
  353. }
  354. return types.NewFileSourceFromData(audio.Data, mimeType)
  355. case ContentTypeFile:
  356. file := m.GetFile()
  357. if file == nil || file.FileData == "" {
  358. return nil
  359. }
  360. return types.NewFileSourceFromData(file.FileData, "")
  361. case ContentTypeVideoUrl:
  362. video := m.GetVideoUrl()
  363. if video == nil || video.Url == "" {
  364. return nil
  365. }
  366. return types.NewFileSourceFromData(video.Url, "")
  367. }
  368. return nil
  369. }
  370. type MessageImageUrl struct {
  371. Url string `json:"url"`
  372. Detail string `json:"detail,omitempty"`
  373. MimeType string
  374. }
  375. func (m *MessageImageUrl) IsRemoteImage() bool {
  376. return strings.HasPrefix(m.Url, "http")
  377. }
  378. type MessageInputAudio struct {
  379. Data string `json:"data"` //base64
  380. Format string `json:"format"`
  381. }
  382. type MessageFile struct {
  383. FileName string `json:"filename,omitempty"`
  384. FileData string `json:"file_data,omitempty"`
  385. FileId string `json:"file_id,omitempty"`
  386. }
  387. type MessageVideoUrl struct {
  388. Url string `json:"url"`
  389. }
  390. const (
  391. ContentTypeText = "text"
  392. ContentTypeImageURL = "image_url"
  393. ContentTypeInputAudio = "input_audio"
  394. ContentTypeFile = "file"
  395. ContentTypeVideoUrl = "video_url" // 阿里百炼视频识别
  396. //ContentTypeAudioUrl = "audio_url"
  397. )
  398. func (m *Message) GetPrefix() bool {
  399. if m.Prefix == nil {
  400. return false
  401. }
  402. return *m.Prefix
  403. }
  404. func (m *Message) SetPrefix(prefix bool) {
  405. m.Prefix = &prefix
  406. }
  407. func (m *Message) ParseToolCalls() []ToolCallRequest {
  408. if m.ToolCalls == nil {
  409. return nil
  410. }
  411. var toolCalls []ToolCallRequest
  412. if err := json.Unmarshal(m.ToolCalls, &toolCalls); err == nil {
  413. return toolCalls
  414. }
  415. return toolCalls
  416. }
  417. func (m *Message) SetToolCalls(toolCalls any) {
  418. toolCallsJson, _ := json.Marshal(toolCalls)
  419. m.ToolCalls = toolCallsJson
  420. }
  421. func (m *Message) StringContent() string {
  422. switch m.Content.(type) {
  423. case string:
  424. return m.Content.(string)
  425. case []any:
  426. var contentStr string
  427. for _, contentItem := range m.Content.([]any) {
  428. contentMap, ok := contentItem.(map[string]any)
  429. if !ok {
  430. continue
  431. }
  432. if contentMap["type"] == ContentTypeText {
  433. if subStr, ok := contentMap["text"].(string); ok {
  434. contentStr += subStr
  435. }
  436. }
  437. }
  438. return contentStr
  439. }
  440. return ""
  441. }
  442. func (m *Message) SetNullContent() {
  443. m.Content = nil
  444. m.parsedContent = nil
  445. }
  446. func (m *Message) SetStringContent(content string) {
  447. m.Content = content
  448. m.parsedContent = nil
  449. }
  450. func (m *Message) SetMediaContent(content []MediaContent) {
  451. m.Content = content
  452. m.parsedContent = content
  453. }
  454. func (m *Message) IsStringContent() bool {
  455. _, ok := m.Content.(string)
  456. if ok {
  457. return true
  458. }
  459. return false
  460. }
  461. func (m *Message) ParseContent() []MediaContent {
  462. if m.Content == nil {
  463. return nil
  464. }
  465. if len(m.parsedContent) > 0 {
  466. return m.parsedContent
  467. }
  468. var contentList []MediaContent
  469. // 先尝试解析为字符串
  470. content, ok := m.Content.(string)
  471. if ok {
  472. contentList = []MediaContent{{
  473. Type: ContentTypeText,
  474. Text: content,
  475. }}
  476. m.parsedContent = contentList
  477. return contentList
  478. }
  479. // 尝试解析为数组
  480. //var arrayContent []map[string]interface{}
  481. arrayContent, ok := m.Content.([]any)
  482. if !ok {
  483. return contentList
  484. }
  485. for _, contentItemAny := range arrayContent {
  486. mediaItem, ok := contentItemAny.(MediaContent)
  487. if ok {
  488. contentList = append(contentList, mediaItem)
  489. continue
  490. }
  491. contentItem, ok := contentItemAny.(map[string]any)
  492. if !ok {
  493. continue
  494. }
  495. contentType, ok := contentItem["type"].(string)
  496. if !ok {
  497. continue
  498. }
  499. switch contentType {
  500. case ContentTypeText:
  501. if text, ok := contentItem["text"].(string); ok {
  502. contentList = append(contentList, MediaContent{
  503. Type: ContentTypeText,
  504. Text: text,
  505. })
  506. }
  507. case ContentTypeImageURL:
  508. imageUrl := contentItem["image_url"]
  509. temp := &MessageImageUrl{
  510. Detail: "high",
  511. }
  512. switch v := imageUrl.(type) {
  513. case string:
  514. temp.Url = v
  515. case map[string]interface{}:
  516. url, ok1 := v["url"].(string)
  517. detail, ok2 := v["detail"].(string)
  518. if ok2 {
  519. temp.Detail = detail
  520. }
  521. if ok1 {
  522. temp.Url = url
  523. }
  524. }
  525. contentList = append(contentList, MediaContent{
  526. Type: ContentTypeImageURL,
  527. ImageUrl: temp,
  528. })
  529. case ContentTypeInputAudio:
  530. if audioData, ok := contentItem["input_audio"].(map[string]interface{}); ok {
  531. data, ok1 := audioData["data"].(string)
  532. format, ok2 := audioData["format"].(string)
  533. if ok1 && ok2 {
  534. temp := &MessageInputAudio{
  535. Data: data,
  536. Format: format,
  537. }
  538. contentList = append(contentList, MediaContent{
  539. Type: ContentTypeInputAudio,
  540. InputAudio: temp,
  541. })
  542. }
  543. }
  544. case ContentTypeFile:
  545. if fileData, ok := contentItem["file"].(map[string]interface{}); ok {
  546. fileId, ok3 := fileData["file_id"].(string)
  547. if ok3 {
  548. contentList = append(contentList, MediaContent{
  549. Type: ContentTypeFile,
  550. File: &MessageFile{
  551. FileId: fileId,
  552. },
  553. })
  554. } else {
  555. fileName, ok1 := fileData["filename"].(string)
  556. fileDataStr, ok2 := fileData["file_data"].(string)
  557. if ok1 && ok2 {
  558. contentList = append(contentList, MediaContent{
  559. Type: ContentTypeFile,
  560. File: &MessageFile{
  561. FileName: fileName,
  562. FileData: fileDataStr,
  563. },
  564. })
  565. }
  566. }
  567. }
  568. case ContentTypeVideoUrl:
  569. if videoUrl, ok := contentItem["video_url"].(string); ok {
  570. contentList = append(contentList, MediaContent{
  571. Type: ContentTypeVideoUrl,
  572. VideoUrl: &MessageVideoUrl{
  573. Url: videoUrl,
  574. },
  575. })
  576. }
  577. }
  578. }
  579. if len(contentList) > 0 {
  580. m.parsedContent = contentList
  581. }
  582. return contentList
  583. }
  584. // old code
  585. /*func (m *Message) StringContent() string {
  586. if m.parsedStringContent != nil {
  587. return *m.parsedStringContent
  588. }
  589. var stringContent string
  590. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  591. m.parsedStringContent = &stringContent
  592. return stringContent
  593. }
  594. contentStr := new(strings.Builder)
  595. arrayContent := m.ParseContent()
  596. for _, content := range arrayContent {
  597. if content.Type == ContentTypeText {
  598. contentStr.WriteString(content.Text)
  599. }
  600. }
  601. stringContent = contentStr.String()
  602. m.parsedStringContent = &stringContent
  603. return stringContent
  604. }
  605. func (m *Message) SetNullContent() {
  606. m.Content = nil
  607. m.parsedStringContent = nil
  608. m.parsedContent = nil
  609. }
  610. func (m *Message) SetStringContent(content string) {
  611. jsonContent, _ := json.Marshal(content)
  612. m.Content = jsonContent
  613. m.parsedStringContent = &content
  614. m.parsedContent = nil
  615. }
  616. func (m *Message) SetMediaContent(content []MediaContent) {
  617. jsonContent, _ := json.Marshal(content)
  618. m.Content = jsonContent
  619. m.parsedContent = nil
  620. m.parsedStringContent = nil
  621. }
  622. func (m *Message) IsStringContent() bool {
  623. if m.parsedStringContent != nil {
  624. return true
  625. }
  626. var stringContent string
  627. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  628. m.parsedStringContent = &stringContent
  629. return true
  630. }
  631. return false
  632. }
  633. func (m *Message) ParseContent() []MediaContent {
  634. if m.parsedContent != nil {
  635. return m.parsedContent
  636. }
  637. var contentList []MediaContent
  638. // 先尝试解析为字符串
  639. var stringContent string
  640. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  641. contentList = []MediaContent{{
  642. Type: ContentTypeText,
  643. Text: stringContent,
  644. }}
  645. m.parsedContent = contentList
  646. return contentList
  647. }
  648. // 尝试解析为数组
  649. var arrayContent []map[string]interface{}
  650. if err := json.Unmarshal(m.Content, &arrayContent); err == nil {
  651. for _, contentItem := range arrayContent {
  652. contentType, ok := contentItem["type"].(string)
  653. if !ok {
  654. continue
  655. }
  656. switch contentType {
  657. case ContentTypeText:
  658. if text, ok := contentItem["text"].(string); ok {
  659. contentList = append(contentList, MediaContent{
  660. Type: ContentTypeText,
  661. Text: text,
  662. })
  663. }
  664. case ContentTypeImageURL:
  665. imageUrl := contentItem["image_url"]
  666. temp := &MessageImageUrl{
  667. Detail: "high",
  668. }
  669. switch v := imageUrl.(type) {
  670. case string:
  671. temp.Url = v
  672. case map[string]interface{}:
  673. url, ok1 := v["url"].(string)
  674. detail, ok2 := v["detail"].(string)
  675. if ok2 {
  676. temp.Detail = detail
  677. }
  678. if ok1 {
  679. temp.Url = url
  680. }
  681. }
  682. contentList = append(contentList, MediaContent{
  683. Type: ContentTypeImageURL,
  684. ImageUrl: temp,
  685. })
  686. case ContentTypeInputAudio:
  687. if audioData, ok := contentItem["input_audio"].(map[string]interface{}); ok {
  688. data, ok1 := audioData["data"].(string)
  689. format, ok2 := audioData["format"].(string)
  690. if ok1 && ok2 {
  691. temp := &MessageInputAudio{
  692. Data: data,
  693. Format: format,
  694. }
  695. contentList = append(contentList, MediaContent{
  696. Type: ContentTypeInputAudio,
  697. InputAudio: temp,
  698. })
  699. }
  700. }
  701. case ContentTypeFile:
  702. if fileData, ok := contentItem["file"].(map[string]interface{}); ok {
  703. fileId, ok3 := fileData["file_id"].(string)
  704. if ok3 {
  705. contentList = append(contentList, MediaContent{
  706. Type: ContentTypeFile,
  707. File: &MessageFile{
  708. FileId: fileId,
  709. },
  710. })
  711. } else {
  712. fileName, ok1 := fileData["filename"].(string)
  713. fileDataStr, ok2 := fileData["file_data"].(string)
  714. if ok1 && ok2 {
  715. contentList = append(contentList, MediaContent{
  716. Type: ContentTypeFile,
  717. File: &MessageFile{
  718. FileName: fileName,
  719. FileData: fileDataStr,
  720. },
  721. })
  722. }
  723. }
  724. }
  725. case ContentTypeVideoUrl:
  726. if videoUrl, ok := contentItem["video_url"].(string); ok {
  727. contentList = append(contentList, MediaContent{
  728. Type: ContentTypeVideoUrl,
  729. VideoUrl: &MessageVideoUrl{
  730. Url: videoUrl,
  731. },
  732. })
  733. }
  734. }
  735. }
  736. }
  737. if len(contentList) > 0 {
  738. m.parsedContent = contentList
  739. }
  740. return contentList
  741. }*/
  742. type WebSearchOptions struct {
  743. SearchContextSize string `json:"search_context_size,omitempty"`
  744. UserLocation json.RawMessage `json:"user_location,omitempty"`
  745. }
  746. // https://platform.openai.com/docs/api-reference/responses/create
  747. type OpenAIResponsesRequest struct {
  748. Model string `json:"model"`
  749. Input json.RawMessage `json:"input,omitempty"`
  750. Include json.RawMessage `json:"include,omitempty"`
  751. // 在后台运行推理,暂时还不支持依赖的接口
  752. // Background json.RawMessage `json:"background,omitempty"`
  753. Conversation json.RawMessage `json:"conversation,omitempty"`
  754. ContextManagement json.RawMessage `json:"context_management,omitempty"`
  755. Instructions json.RawMessage `json:"instructions,omitempty"`
  756. MaxOutputTokens *uint `json:"max_output_tokens,omitempty"`
  757. TopLogProbs *int `json:"top_logprobs,omitempty"`
  758. Metadata json.RawMessage `json:"metadata,omitempty"`
  759. ParallelToolCalls json.RawMessage `json:"parallel_tool_calls,omitempty"`
  760. PreviousResponseID string `json:"previous_response_id,omitempty"`
  761. Reasoning *Reasoning `json:"reasoning,omitempty"`
  762. // ServiceTier specifies upstream service level and may affect billing.
  763. // This field is filtered by default and can be enabled via channel setting allow_service_tier.
  764. ServiceTier string `json:"service_tier,omitempty"`
  765. // Store controls whether upstream may store request/response data.
  766. // This field is allowed by default and can be disabled via channel setting disable_store.
  767. Store json.RawMessage `json:"store,omitempty"`
  768. PromptCacheKey json.RawMessage `json:"prompt_cache_key,omitempty"`
  769. PromptCacheRetention json.RawMessage `json:"prompt_cache_retention,omitempty"`
  770. // SafetyIdentifier carries client identity for policy abuse detection.
  771. // This field is filtered by default and can be enabled via channel setting allow_safety_identifier.
  772. SafetyIdentifier json.RawMessage `json:"safety_identifier,omitempty"`
  773. Stream *bool `json:"stream,omitempty"`
  774. StreamOptions *StreamOptions `json:"stream_options,omitempty"`
  775. Temperature *float64 `json:"temperature,omitempty"`
  776. Text json.RawMessage `json:"text,omitempty"`
  777. ToolChoice json.RawMessage `json:"tool_choice,omitempty"`
  778. Tools json.RawMessage `json:"tools,omitempty"` // 需要处理的参数很少,MCP 参数太多不确定,所以用 map
  779. TopP *float64 `json:"top_p,omitempty"`
  780. Truncation json.RawMessage `json:"truncation,omitempty"`
  781. User json.RawMessage `json:"user,omitempty"`
  782. MaxToolCalls *uint `json:"max_tool_calls,omitempty"`
  783. Prompt json.RawMessage `json:"prompt,omitempty"`
  784. // qwen
  785. EnableThinking json.RawMessage `json:"enable_thinking,omitempty"`
  786. // perplexity
  787. Preset json.RawMessage `json:"preset,omitempty"`
  788. }
  789. func (r *OpenAIResponsesRequest) GetTokenCountMeta() *types.TokenCountMeta {
  790. var fileMeta = make([]*types.FileMeta, 0)
  791. var texts = make([]string, 0)
  792. if r.Input != nil {
  793. inputs := r.ParseInput()
  794. for _, input := range inputs {
  795. if input.Type == "input_image" {
  796. if input.ImageUrl != "" {
  797. fileMeta = append(fileMeta, &types.FileMeta{
  798. FileType: types.FileTypeImage,
  799. Source: types.NewFileSourceFromData(input.ImageUrl, ""),
  800. Detail: input.Detail,
  801. })
  802. }
  803. } else if input.Type == "input_file" {
  804. if input.FileUrl != "" {
  805. fileMeta = append(fileMeta, &types.FileMeta{
  806. FileType: types.FileTypeFile,
  807. Source: types.NewFileSourceFromData(input.FileUrl, ""),
  808. })
  809. }
  810. } else {
  811. texts = append(texts, input.Text)
  812. }
  813. }
  814. }
  815. if len(r.Instructions) > 0 {
  816. texts = append(texts, string(r.Instructions))
  817. }
  818. if len(r.Metadata) > 0 {
  819. texts = append(texts, string(r.Metadata))
  820. }
  821. if len(r.Text) > 0 {
  822. texts = append(texts, string(r.Text))
  823. }
  824. if len(r.ToolChoice) > 0 {
  825. texts = append(texts, string(r.ToolChoice))
  826. }
  827. if len(r.Prompt) > 0 {
  828. texts = append(texts, string(r.Prompt))
  829. }
  830. if len(r.Tools) > 0 {
  831. texts = append(texts, string(r.Tools))
  832. }
  833. return &types.TokenCountMeta{
  834. CombineText: strings.Join(texts, "\n"),
  835. Files: fileMeta,
  836. MaxTokens: int(lo.FromPtrOr(r.MaxOutputTokens, uint(0))),
  837. }
  838. }
  839. func (r *OpenAIResponsesRequest) IsStream(c *gin.Context) bool {
  840. return lo.FromPtrOr(r.Stream, false)
  841. }
  842. func (r *OpenAIResponsesRequest) SetModelName(modelName string) {
  843. if modelName != "" {
  844. r.Model = modelName
  845. }
  846. }
  847. func (r *OpenAIResponsesRequest) GetToolsMap() []map[string]any {
  848. var toolsMap []map[string]any
  849. if len(r.Tools) > 0 {
  850. _ = common.Unmarshal(r.Tools, &toolsMap)
  851. }
  852. return toolsMap
  853. }
  854. type Reasoning struct {
  855. Effort string `json:"effort,omitempty"`
  856. Summary string `json:"summary,omitempty"`
  857. }
  858. type Input struct {
  859. Type string `json:"type,omitempty"`
  860. Role string `json:"role,omitempty"`
  861. Content json.RawMessage `json:"content,omitempty"`
  862. }
  863. type MediaInput struct {
  864. Type string `json:"type"`
  865. Text string `json:"text,omitempty"`
  866. FileUrl string `json:"file_url,omitempty"`
  867. ImageUrl string `json:"image_url,omitempty"`
  868. Detail string `json:"detail,omitempty"` // 仅 input_image 有效
  869. }
  870. // ParseInput parses the Responses API `input` field into a normalized slice of MediaInput.
  871. // Reference implementation mirrors Message.ParseContent:
  872. // - input can be a string, treated as an input_text item
  873. // - input can be an array of objects with a `type` field
  874. // supported types: input_text, input_image, input_file
  875. func (r *OpenAIResponsesRequest) ParseInput() []MediaInput {
  876. if r.Input == nil {
  877. return nil
  878. }
  879. var mediaInputs []MediaInput
  880. // Try string first
  881. // if str, ok := common.GetJsonType(r.Input); ok {
  882. // inputs = append(inputs, MediaInput{Type: "input_text", Text: str})
  883. // return inputs
  884. // }
  885. if common.GetJsonType(r.Input) == "string" {
  886. var str string
  887. _ = common.Unmarshal(r.Input, &str)
  888. mediaInputs = append(mediaInputs, MediaInput{Type: "input_text", Text: str})
  889. return mediaInputs
  890. }
  891. // Try array of parts
  892. if common.GetJsonType(r.Input) == "array" {
  893. var inputs []Input
  894. _ = common.Unmarshal(r.Input, &inputs)
  895. for _, input := range inputs {
  896. if common.GetJsonType(input.Content) == "string" {
  897. var str string
  898. _ = common.Unmarshal(input.Content, &str)
  899. mediaInputs = append(mediaInputs, MediaInput{Type: "input_text", Text: str})
  900. }
  901. if common.GetJsonType(input.Content) == "array" {
  902. var array []any
  903. _ = common.Unmarshal(input.Content, &array)
  904. for _, itemAny := range array {
  905. // Already parsed MediaContent
  906. if media, ok := itemAny.(MediaInput); ok {
  907. mediaInputs = append(mediaInputs, media)
  908. continue
  909. }
  910. // Generic map
  911. item, ok := itemAny.(map[string]any)
  912. if !ok {
  913. continue
  914. }
  915. typeVal, ok := item["type"].(string)
  916. if !ok {
  917. continue
  918. }
  919. switch typeVal {
  920. case "input_text":
  921. text, _ := item["text"].(string)
  922. mediaInputs = append(mediaInputs, MediaInput{Type: "input_text", Text: text})
  923. case "input_image":
  924. // image_url may be string or object with url field
  925. var imageUrl string
  926. switch v := item["image_url"].(type) {
  927. case string:
  928. imageUrl = v
  929. case map[string]any:
  930. if url, ok := v["url"].(string); ok {
  931. imageUrl = url
  932. }
  933. }
  934. mediaInputs = append(mediaInputs, MediaInput{Type: "input_image", ImageUrl: imageUrl})
  935. case "input_file":
  936. // file_url may be string or object with url field
  937. var fileUrl string
  938. switch v := item["file_url"].(type) {
  939. case string:
  940. fileUrl = v
  941. case map[string]any:
  942. if url, ok := v["url"].(string); ok {
  943. fileUrl = url
  944. }
  945. }
  946. mediaInputs = append(mediaInputs, MediaInput{Type: "input_file", FileUrl: fileUrl})
  947. }
  948. }
  949. }
  950. }
  951. }
  952. return mediaInputs
  953. }