openai_request.go 13 KB

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