openai_request.go 13 KB

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