openai_request.go 13 KB

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