openai_request.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package dto
  2. import (
  3. "encoding/json"
  4. "strings"
  5. )
  6. type ResponseFormat struct {
  7. Type string `json:"type,omitempty"`
  8. JsonSchema *FormatJsonSchema `json:"json_schema,omitempty"`
  9. }
  10. type FormatJsonSchema struct {
  11. Description string `json:"description,omitempty"`
  12. Name string `json:"name"`
  13. Schema any `json:"schema,omitempty"`
  14. Strict any `json:"strict,omitempty"`
  15. }
  16. type GeneralOpenAIRequest struct {
  17. Model string `json:"model,omitempty"`
  18. Messages []Message `json:"messages,omitempty"`
  19. Prompt any `json:"prompt,omitempty"`
  20. Prefix any `json:"prefix,omitempty"`
  21. Suffix any `json:"suffix,omitempty"`
  22. Stream bool `json:"stream,omitempty"`
  23. StreamOptions *StreamOptions `json:"stream_options,omitempty"`
  24. MaxTokens uint `json:"max_tokens,omitempty"`
  25. MaxCompletionTokens uint `json:"max_completion_tokens,omitempty"`
  26. ReasoningEffort string `json:"reasoning_effort,omitempty"`
  27. Temperature *float64 `json:"temperature,omitempty"`
  28. TopP float64 `json:"top_p,omitempty"`
  29. TopK int `json:"top_k,omitempty"`
  30. Stop any `json:"stop,omitempty"`
  31. N int `json:"n,omitempty"`
  32. Input any `json:"input,omitempty"`
  33. Instruction string `json:"instruction,omitempty"`
  34. Size string `json:"size,omitempty"`
  35. Functions any `json:"functions,omitempty"`
  36. FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
  37. PresencePenalty float64 `json:"presence_penalty,omitempty"`
  38. ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
  39. EncodingFormat any `json:"encoding_format,omitempty"`
  40. Seed float64 `json:"seed,omitempty"`
  41. ParallelTooCalls *bool `json:"parallel_tool_calls,omitempty"`
  42. Tools []ToolCallRequest `json:"tools,omitempty"`
  43. ToolChoice any `json:"tool_choice,omitempty"`
  44. User string `json:"user,omitempty"`
  45. LogProbs bool `json:"logprobs,omitempty"`
  46. TopLogProbs int `json:"top_logprobs,omitempty"`
  47. Dimensions int `json:"dimensions,omitempty"`
  48. Modalities any `json:"modalities,omitempty"`
  49. Audio any `json:"audio,omitempty"`
  50. EnableThinking any `json:"enable_thinking,omitempty"` // ali
  51. ExtraBody any `json:"extra_body,omitempty"`
  52. WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty"`
  53. // OpenRouter Params
  54. Usage json.RawMessage `json:"usage,omitempty"`
  55. Reasoning json.RawMessage `json:"reasoning,omitempty"`
  56. }
  57. type ToolCallRequest struct {
  58. ID string `json:"id,omitempty"`
  59. Type string `json:"type"`
  60. Function FunctionRequest `json:"function"`
  61. }
  62. type FunctionRequest struct {
  63. Description string `json:"description,omitempty"`
  64. Name string `json:"name"`
  65. Parameters any `json:"parameters,omitempty"`
  66. Arguments string `json:"arguments,omitempty"`
  67. }
  68. type StreamOptions struct {
  69. IncludeUsage bool `json:"include_usage,omitempty"`
  70. }
  71. func (r GeneralOpenAIRequest) GetMaxTokens() int {
  72. return int(r.MaxTokens)
  73. }
  74. func (r GeneralOpenAIRequest) ParseInput() []string {
  75. if r.Input == nil {
  76. return nil
  77. }
  78. var input []string
  79. switch r.Input.(type) {
  80. case string:
  81. input = []string{r.Input.(string)}
  82. case []any:
  83. input = make([]string, 0, len(r.Input.([]any)))
  84. for _, item := range r.Input.([]any) {
  85. if str, ok := item.(string); ok {
  86. input = append(input, str)
  87. }
  88. }
  89. }
  90. return input
  91. }
  92. type Message struct {
  93. Role string `json:"role"`
  94. Content json.RawMessage `json:"content"`
  95. Name *string `json:"name,omitempty"`
  96. Prefix *bool `json:"prefix,omitempty"`
  97. ReasoningContent string `json:"reasoning_content,omitempty"`
  98. Reasoning string `json:"reasoning,omitempty"`
  99. ToolCalls json.RawMessage `json:"tool_calls,omitempty"`
  100. ToolCallId string `json:"tool_call_id,omitempty"`
  101. parsedContent []MediaContent
  102. parsedStringContent *string
  103. }
  104. type MediaContent struct {
  105. Type string `json:"type"`
  106. Text string `json:"text,omitempty"`
  107. ImageUrl any `json:"image_url,omitempty"`
  108. InputAudio any `json:"input_audio,omitempty"`
  109. File any `json:"file,omitempty"`
  110. VideoUrl any `json:"video_url,omitempty"`
  111. }
  112. func (m *MediaContent) GetImageMedia() *MessageImageUrl {
  113. if m.ImageUrl != nil {
  114. return m.ImageUrl.(*MessageImageUrl)
  115. }
  116. return nil
  117. }
  118. func (m *MediaContent) GetInputAudio() *MessageInputAudio {
  119. if m.InputAudio != nil {
  120. return m.InputAudio.(*MessageInputAudio)
  121. }
  122. return nil
  123. }
  124. func (m *MediaContent) GetFile() *MessageFile {
  125. if m.File != nil {
  126. return m.File.(*MessageFile)
  127. }
  128. return nil
  129. }
  130. type MessageImageUrl struct {
  131. Url string `json:"url"`
  132. Detail string `json:"detail"`
  133. MimeType string
  134. }
  135. func (m *MessageImageUrl) IsRemoteImage() bool {
  136. return strings.HasPrefix(m.Url, "http")
  137. }
  138. type MessageInputAudio struct {
  139. Data string `json:"data"` //base64
  140. Format string `json:"format"`
  141. }
  142. type MessageFile struct {
  143. FileName string `json:"filename,omitempty"`
  144. FileData string `json:"file_data,omitempty"`
  145. FileId string `json:"file_id,omitempty"`
  146. }
  147. type MessageVideoUrl struct {
  148. Url string `json:"url"`
  149. }
  150. const (
  151. ContentTypeText = "text"
  152. ContentTypeImageURL = "image_url"
  153. ContentTypeInputAudio = "input_audio"
  154. ContentTypeFile = "file"
  155. ContentTypeVideoUrl = "video_url" // 阿里百炼视频识别
  156. )
  157. func (m *Message) GetPrefix() bool {
  158. if m.Prefix == nil {
  159. return false
  160. }
  161. return *m.Prefix
  162. }
  163. func (m *Message) SetPrefix(prefix bool) {
  164. m.Prefix = &prefix
  165. }
  166. func (m *Message) ParseToolCalls() []ToolCallRequest {
  167. if m.ToolCalls == nil {
  168. return nil
  169. }
  170. var toolCalls []ToolCallRequest
  171. if err := json.Unmarshal(m.ToolCalls, &toolCalls); err == nil {
  172. return toolCalls
  173. }
  174. return toolCalls
  175. }
  176. func (m *Message) SetToolCalls(toolCalls any) {
  177. toolCallsJson, _ := json.Marshal(toolCalls)
  178. m.ToolCalls = toolCallsJson
  179. }
  180. func (m *Message) StringContent() string {
  181. if m.parsedStringContent != nil {
  182. return *m.parsedStringContent
  183. }
  184. var stringContent string
  185. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  186. m.parsedStringContent = &stringContent
  187. return stringContent
  188. }
  189. contentStr := new(strings.Builder)
  190. arrayContent := m.ParseContent()
  191. for _, content := range arrayContent {
  192. if content.Type == ContentTypeText {
  193. contentStr.WriteString(content.Text)
  194. }
  195. }
  196. stringContent = contentStr.String()
  197. m.parsedStringContent = &stringContent
  198. return stringContent
  199. }
  200. func (m *Message) SetNullContent() {
  201. m.Content = nil
  202. m.parsedStringContent = nil
  203. m.parsedContent = nil
  204. }
  205. func (m *Message) SetStringContent(content string) {
  206. jsonContent, _ := json.Marshal(content)
  207. m.Content = jsonContent
  208. m.parsedStringContent = &content
  209. m.parsedContent = nil
  210. }
  211. func (m *Message) SetMediaContent(content []MediaContent) {
  212. jsonContent, _ := json.Marshal(content)
  213. m.Content = jsonContent
  214. m.parsedContent = nil
  215. m.parsedStringContent = nil
  216. }
  217. func (m *Message) IsStringContent() bool {
  218. if m.parsedStringContent != nil {
  219. return true
  220. }
  221. var stringContent string
  222. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  223. m.parsedStringContent = &stringContent
  224. return true
  225. }
  226. return false
  227. }
  228. func (m *Message) ParseContent() []MediaContent {
  229. if m.parsedContent != nil {
  230. return m.parsedContent
  231. }
  232. var contentList []MediaContent
  233. // 先尝试解析为字符串
  234. var stringContent string
  235. if err := json.Unmarshal(m.Content, &stringContent); err == nil {
  236. contentList = []MediaContent{{
  237. Type: ContentTypeText,
  238. Text: stringContent,
  239. }}
  240. m.parsedContent = contentList
  241. return contentList
  242. }
  243. // 尝试解析为数组
  244. var arrayContent []map[string]interface{}
  245. if err := json.Unmarshal(m.Content, &arrayContent); err == nil {
  246. for _, contentItem := range arrayContent {
  247. contentType, ok := contentItem["type"].(string)
  248. if !ok {
  249. continue
  250. }
  251. switch contentType {
  252. case ContentTypeText:
  253. if text, ok := contentItem["text"].(string); ok {
  254. contentList = append(contentList, MediaContent{
  255. Type: ContentTypeText,
  256. Text: text,
  257. })
  258. }
  259. case ContentTypeImageURL:
  260. imageUrl := contentItem["image_url"]
  261. temp := &MessageImageUrl{
  262. Detail: "high",
  263. }
  264. switch v := imageUrl.(type) {
  265. case string:
  266. temp.Url = v
  267. case map[string]interface{}:
  268. url, ok1 := v["url"].(string)
  269. detail, ok2 := v["detail"].(string)
  270. if ok2 {
  271. temp.Detail = detail
  272. }
  273. if ok1 {
  274. temp.Url = url
  275. }
  276. }
  277. contentList = append(contentList, MediaContent{
  278. Type: ContentTypeImageURL,
  279. ImageUrl: temp,
  280. })
  281. case ContentTypeInputAudio:
  282. if audioData, ok := contentItem["input_audio"].(map[string]interface{}); ok {
  283. data, ok1 := audioData["data"].(string)
  284. format, ok2 := audioData["format"].(string)
  285. if ok1 && ok2 {
  286. temp := &MessageInputAudio{
  287. Data: data,
  288. Format: format,
  289. }
  290. contentList = append(contentList, MediaContent{
  291. Type: ContentTypeInputAudio,
  292. InputAudio: temp,
  293. })
  294. }
  295. }
  296. case ContentTypeFile:
  297. if fileData, ok := contentItem["file"].(map[string]interface{}); ok {
  298. fileId, ok3 := fileData["file_id"].(string)
  299. if ok3 {
  300. contentList = append(contentList, MediaContent{
  301. Type: ContentTypeFile,
  302. File: &MessageFile{
  303. FileId: fileId,
  304. },
  305. })
  306. } else {
  307. fileName, ok1 := fileData["filename"].(string)
  308. fileDataStr, ok2 := fileData["file_data"].(string)
  309. if ok1 && ok2 {
  310. contentList = append(contentList, MediaContent{
  311. Type: ContentTypeFile,
  312. File: &MessageFile{
  313. FileName: fileName,
  314. FileData: fileDataStr,
  315. },
  316. })
  317. }
  318. }
  319. }
  320. case ContentTypeVideoUrl:
  321. if videoUrl, ok := contentItem["video_url"].(string); ok {
  322. contentList = append(contentList, MediaContent{
  323. Type: ContentTypeVideoUrl,
  324. VideoUrl: &MessageVideoUrl{
  325. Url: videoUrl,
  326. },
  327. })
  328. }
  329. }
  330. }
  331. }
  332. if len(contentList) > 0 {
  333. m.parsedContent = contentList
  334. }
  335. return contentList
  336. }
  337. type WebSearchOptions struct {
  338. SearchContextSize string `json:"search_context_size,omitempty"`
  339. UserLocation json.RawMessage `json:"user_location,omitempty"`
  340. }
  341. type OpenAIResponsesRequest struct {
  342. Model string `json:"model"`
  343. Input json.RawMessage `json:"input,omitempty"`
  344. Include json.RawMessage `json:"include,omitempty"`
  345. Instructions json.RawMessage `json:"instructions,omitempty"`
  346. MaxOutputTokens uint `json:"max_output_tokens,omitempty"`
  347. Metadata json.RawMessage `json:"metadata,omitempty"`
  348. ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
  349. PreviousResponseID string `json:"previous_response_id,omitempty"`
  350. Reasoning *Reasoning `json:"reasoning,omitempty"`
  351. ServiceTier string `json:"service_tier,omitempty"`
  352. Store bool `json:"store,omitempty"`
  353. Stream bool `json:"stream,omitempty"`
  354. Temperature float64 `json:"temperature,omitempty"`
  355. Text json.RawMessage `json:"text,omitempty"`
  356. ToolChoice json.RawMessage `json:"tool_choice,omitempty"`
  357. Tools []ResponsesToolsCall `json:"tools,omitempty"`
  358. TopP float64 `json:"top_p,omitempty"`
  359. Truncation string `json:"truncation,omitempty"`
  360. User string `json:"user,omitempty"`
  361. }
  362. type Reasoning struct {
  363. Effort string `json:"effort,omitempty"`
  364. Summary string `json:"summary,omitempty"`
  365. }
  366. type ResponsesToolsCall struct {
  367. Type string `json:"type"`
  368. // Web Search
  369. UserLocation json.RawMessage `json:"user_location,omitempty"`
  370. SearchContextSize string `json:"search_context_size,omitempty"`
  371. // File Search
  372. VectorStoreIds []string `json:"vector_store_ids,omitempty"`
  373. MaxNumResults uint `json:"max_num_results,omitempty"`
  374. Filters json.RawMessage `json:"filters,omitempty"`
  375. // Computer Use
  376. DisplayWidth uint `json:"display_width,omitempty"`
  377. DisplayHeight uint `json:"display_height,omitempty"`
  378. Environment string `json:"environment,omitempty"`
  379. // Function
  380. Name string `json:"name,omitempty"`
  381. Description string `json:"description,omitempty"`
  382. Parameters json.RawMessage `json:"parameters,omitempty"`
  383. }