openai_request.go 12 KB

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