openai_request.go 13 KB

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