openai_request.go 13 KB

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