relay-gemini.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. package gemini
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "one-api/common"
  8. "one-api/constant"
  9. "one-api/dto"
  10. relaycommon "one-api/relay/common"
  11. "one-api/relay/helper"
  12. "one-api/service"
  13. "one-api/setting/model_setting"
  14. "strconv"
  15. "strings"
  16. "unicode/utf8"
  17. "github.com/gin-gonic/gin"
  18. )
  19. var geminiSupportedMimeTypes = map[string]bool{
  20. "application/pdf": true,
  21. "audio/mpeg": true,
  22. "audio/mp3": true,
  23. "audio/wav": true,
  24. "image/png": true,
  25. "image/jpeg": true,
  26. "text/plain": true,
  27. "video/mov": true,
  28. "video/mpeg": true,
  29. "video/mp4": true,
  30. "video/mpg": true,
  31. "video/avi": true,
  32. "video/wmv": true,
  33. "video/mpegps": true,
  34. "video/flv": true,
  35. }
  36. // Gemini 允许的思考预算范围
  37. const (
  38. pro25MinBudget = 128
  39. pro25MaxBudget = 32768
  40. flash25MaxBudget = 24576
  41. flash25LiteMinBudget = 512
  42. flash25LiteMaxBudget = 24576
  43. )
  44. // clampThinkingBudget 根据模型名称将预算限制在允许的范围内
  45. func clampThinkingBudget(modelName string, budget int) int {
  46. isNew25Pro := strings.HasPrefix(modelName, "gemini-2.5-pro") &&
  47. !strings.HasPrefix(modelName, "gemini-2.5-pro-preview-05-06") &&
  48. !strings.HasPrefix(modelName, "gemini-2.5-pro-preview-03-25")
  49. is25FlashLite := strings.HasPrefix(modelName, "gemini-2.5-flash-lite")
  50. if is25FlashLite {
  51. if budget < flash25LiteMinBudget {
  52. return flash25LiteMinBudget
  53. }
  54. if budget > flash25LiteMaxBudget {
  55. return flash25LiteMaxBudget
  56. }
  57. } else if isNew25Pro {
  58. if budget < pro25MinBudget {
  59. return pro25MinBudget
  60. }
  61. if budget > pro25MaxBudget {
  62. return pro25MaxBudget
  63. }
  64. } else { // 其他模型
  65. if budget < 0 {
  66. return 0
  67. }
  68. if budget > flash25MaxBudget {
  69. return flash25MaxBudget
  70. }
  71. }
  72. return budget
  73. }
  74. // Setting safety to the lowest possible values since Gemini is already powerless enough
  75. func CovertGemini2OpenAI(textRequest dto.GeneralOpenAIRequest, info *relaycommon.RelayInfo) (*GeminiChatRequest, error) {
  76. geminiRequest := GeminiChatRequest{
  77. Contents: make([]GeminiChatContent, 0, len(textRequest.Messages)),
  78. GenerationConfig: GeminiChatGenerationConfig{
  79. Temperature: textRequest.Temperature,
  80. TopP: textRequest.TopP,
  81. MaxOutputTokens: textRequest.MaxTokens,
  82. Seed: int64(textRequest.Seed),
  83. },
  84. }
  85. if model_setting.IsGeminiModelSupportImagine(info.UpstreamModelName) {
  86. geminiRequest.GenerationConfig.ResponseModalities = []string{
  87. "TEXT",
  88. "IMAGE",
  89. }
  90. }
  91. if model_setting.GetGeminiSettings().ThinkingAdapterEnabled {
  92. modelName := info.OriginModelName
  93. isNew25Pro := strings.HasPrefix(modelName, "gemini-2.5-pro") &&
  94. !strings.HasPrefix(modelName, "gemini-2.5-pro-preview-05-06") &&
  95. !strings.HasPrefix(modelName, "gemini-2.5-pro-preview-03-25")
  96. is25FlashLite := strings.HasPrefix(modelName, "gemini-2.5-flash-lite")
  97. if strings.Contains(modelName, "-thinking-") {
  98. parts := strings.SplitN(modelName, "-thinking-", 2)
  99. if len(parts) == 2 && parts[1] != "" {
  100. if budgetTokens, err := strconv.Atoi(parts[1]); err == nil {
  101. clampedBudget := clampThinkingBudget(modelName, budgetTokens)
  102. geminiRequest.GenerationConfig.ThinkingConfig = &GeminiThinkingConfig{
  103. ThinkingBudget: common.GetPointer(clampedBudget),
  104. IncludeThoughts: true,
  105. }
  106. }
  107. }
  108. } else if strings.HasSuffix(modelName, "-thinking") {
  109. unsupportedModels := []string{
  110. "gemini-2.5-pro-preview-05-06",
  111. "gemini-2.5-pro-preview-03-25",
  112. }
  113. isUnsupported := false
  114. for _, unsupportedModel := range unsupportedModels {
  115. if strings.HasPrefix(modelName, unsupportedModel) {
  116. isUnsupported = true
  117. break
  118. }
  119. }
  120. if isUnsupported {
  121. geminiRequest.GenerationConfig.ThinkingConfig = &GeminiThinkingConfig{
  122. IncludeThoughts: true,
  123. }
  124. } else {
  125. budgetTokens := model_setting.GetGeminiSettings().ThinkingAdapterBudgetTokensPercentage * float64(geminiRequest.GenerationConfig.MaxOutputTokens)
  126. clampedBudget := clampThinkingBudget(modelName, int(budgetTokens))
  127. geminiRequest.GenerationConfig.ThinkingConfig = &GeminiThinkingConfig{
  128. ThinkingBudget: common.GetPointer(clampedBudget),
  129. IncludeThoughts: true,
  130. }
  131. }
  132. } else if strings.HasSuffix(modelName, "-nothinking") {
  133. if !isNew25Pro && !is25FlashLite {
  134. geminiRequest.GenerationConfig.ThinkingConfig = &GeminiThinkingConfig{
  135. ThinkingBudget: common.GetPointer(0),
  136. }
  137. }
  138. }
  139. }
  140. safetySettings := make([]GeminiChatSafetySettings, 0, len(SafetySettingList))
  141. for _, category := range SafetySettingList {
  142. safetySettings = append(safetySettings, GeminiChatSafetySettings{
  143. Category: category,
  144. Threshold: model_setting.GetGeminiSafetySetting(category),
  145. })
  146. }
  147. geminiRequest.SafetySettings = safetySettings
  148. // openaiContent.FuncToToolCalls()
  149. if textRequest.Tools != nil {
  150. functions := make([]dto.FunctionRequest, 0, len(textRequest.Tools))
  151. googleSearch := false
  152. codeExecution := false
  153. for _, tool := range textRequest.Tools {
  154. if tool.Function.Name == "googleSearch" {
  155. googleSearch = true
  156. continue
  157. }
  158. if tool.Function.Name == "codeExecution" {
  159. codeExecution = true
  160. continue
  161. }
  162. if tool.Function.Parameters != nil {
  163. params, ok := tool.Function.Parameters.(map[string]interface{})
  164. if ok {
  165. if props, hasProps := params["properties"].(map[string]interface{}); hasProps {
  166. if len(props) == 0 {
  167. tool.Function.Parameters = nil
  168. }
  169. }
  170. }
  171. }
  172. // Clean the parameters before appending
  173. cleanedParams := cleanFunctionParameters(tool.Function.Parameters)
  174. tool.Function.Parameters = cleanedParams
  175. functions = append(functions, tool.Function)
  176. }
  177. if codeExecution {
  178. geminiRequest.Tools = append(geminiRequest.Tools, GeminiChatTool{
  179. CodeExecution: make(map[string]string),
  180. })
  181. }
  182. if googleSearch {
  183. geminiRequest.Tools = append(geminiRequest.Tools, GeminiChatTool{
  184. GoogleSearch: make(map[string]string),
  185. })
  186. }
  187. if len(functions) > 0 {
  188. geminiRequest.Tools = append(geminiRequest.Tools, GeminiChatTool{
  189. FunctionDeclarations: functions,
  190. })
  191. }
  192. // common.SysLog("tools: " + fmt.Sprintf("%+v", geminiRequest.Tools))
  193. // json_data, _ := json.Marshal(geminiRequest.Tools)
  194. // common.SysLog("tools_json: " + string(json_data))
  195. }
  196. if textRequest.ResponseFormat != nil && (textRequest.ResponseFormat.Type == "json_schema" || textRequest.ResponseFormat.Type == "json_object") {
  197. geminiRequest.GenerationConfig.ResponseMimeType = "application/json"
  198. if textRequest.ResponseFormat.JsonSchema != nil && textRequest.ResponseFormat.JsonSchema.Schema != nil {
  199. cleanedSchema := removeAdditionalPropertiesWithDepth(textRequest.ResponseFormat.JsonSchema.Schema, 0)
  200. geminiRequest.GenerationConfig.ResponseSchema = cleanedSchema
  201. }
  202. }
  203. tool_call_ids := make(map[string]string)
  204. var system_content []string
  205. //shouldAddDummyModelMessage := false
  206. for _, message := range textRequest.Messages {
  207. if message.Role == "system" {
  208. system_content = append(system_content, message.StringContent())
  209. continue
  210. } else if message.Role == "tool" || message.Role == "function" {
  211. if len(geminiRequest.Contents) == 0 || geminiRequest.Contents[len(geminiRequest.Contents)-1].Role == "model" {
  212. geminiRequest.Contents = append(geminiRequest.Contents, GeminiChatContent{
  213. Role: "user",
  214. })
  215. }
  216. var parts = &geminiRequest.Contents[len(geminiRequest.Contents)-1].Parts
  217. name := ""
  218. if message.Name != nil {
  219. name = *message.Name
  220. } else if val, exists := tool_call_ids[message.ToolCallId]; exists {
  221. name = val
  222. }
  223. var contentMap map[string]interface{}
  224. contentStr := message.StringContent()
  225. // 1. 尝试解析为 JSON 对象
  226. if err := json.Unmarshal([]byte(contentStr), &contentMap); err != nil {
  227. // 2. 如果失败,尝试解析为 JSON 数组
  228. var contentSlice []interface{}
  229. if err := json.Unmarshal([]byte(contentStr), &contentSlice); err == nil {
  230. // 如果是数组,包装成对象
  231. contentMap = map[string]interface{}{"result": contentSlice}
  232. } else {
  233. // 3. 如果再次失败,作为纯文本处理
  234. contentMap = map[string]interface{}{"content": contentStr}
  235. }
  236. }
  237. functionResp := &FunctionResponse{
  238. Name: name,
  239. Response: contentMap,
  240. }
  241. *parts = append(*parts, GeminiPart{
  242. FunctionResponse: functionResp,
  243. })
  244. continue
  245. }
  246. var parts []GeminiPart
  247. content := GeminiChatContent{
  248. Role: message.Role,
  249. }
  250. // isToolCall := false
  251. if message.ToolCalls != nil {
  252. // message.Role = "model"
  253. // isToolCall = true
  254. for _, call := range message.ParseToolCalls() {
  255. args := map[string]interface{}{}
  256. if call.Function.Arguments != "" {
  257. if json.Unmarshal([]byte(call.Function.Arguments), &args) != nil {
  258. return nil, fmt.Errorf("invalid arguments for function %s, args: %s", call.Function.Name, call.Function.Arguments)
  259. }
  260. }
  261. toolCall := GeminiPart{
  262. FunctionCall: &FunctionCall{
  263. FunctionName: call.Function.Name,
  264. Arguments: args,
  265. },
  266. }
  267. parts = append(parts, toolCall)
  268. tool_call_ids[call.ID] = call.Function.Name
  269. }
  270. }
  271. openaiContent := message.ParseContent()
  272. imageNum := 0
  273. for _, part := range openaiContent {
  274. if part.Type == dto.ContentTypeText {
  275. if part.Text == "" {
  276. continue
  277. }
  278. parts = append(parts, GeminiPart{
  279. Text: part.Text,
  280. })
  281. } else if part.Type == dto.ContentTypeImageURL {
  282. imageNum += 1
  283. if constant.GeminiVisionMaxImageNum != -1 && imageNum > constant.GeminiVisionMaxImageNum {
  284. return nil, fmt.Errorf("too many images in the message, max allowed is %d", constant.GeminiVisionMaxImageNum)
  285. }
  286. // 判断是否是url
  287. if strings.HasPrefix(part.GetImageMedia().Url, "http") {
  288. // 是url,获取文件的类型和base64编码的数据
  289. fileData, err := service.GetFileBase64FromUrl(part.GetImageMedia().Url)
  290. if err != nil {
  291. return nil, fmt.Errorf("get file base64 from url '%s' failed: %w", part.GetImageMedia().Url, err)
  292. }
  293. // 校验 MimeType 是否在 Gemini 支持的白名单中
  294. if _, ok := geminiSupportedMimeTypes[strings.ToLower(fileData.MimeType)]; !ok {
  295. url := part.GetImageMedia().Url
  296. return nil, fmt.Errorf("mime type is not supported by Gemini: '%s', url: '%s', supported types are: %v", fileData.MimeType, url, getSupportedMimeTypesList())
  297. }
  298. parts = append(parts, GeminiPart{
  299. InlineData: &GeminiInlineData{
  300. MimeType: fileData.MimeType, // 使用原始的 MimeType,因为大小写可能对API有意义
  301. Data: fileData.Base64Data,
  302. },
  303. })
  304. } else {
  305. format, base64String, err := service.DecodeBase64FileData(part.GetImageMedia().Url)
  306. if err != nil {
  307. return nil, fmt.Errorf("decode base64 image data failed: %s", err.Error())
  308. }
  309. parts = append(parts, GeminiPart{
  310. InlineData: &GeminiInlineData{
  311. MimeType: format,
  312. Data: base64String,
  313. },
  314. })
  315. }
  316. } else if part.Type == dto.ContentTypeFile {
  317. if part.GetFile().FileId != "" {
  318. return nil, fmt.Errorf("only base64 file is supported in gemini")
  319. }
  320. format, base64String, err := service.DecodeBase64FileData(part.GetFile().FileData)
  321. if err != nil {
  322. return nil, fmt.Errorf("decode base64 file data failed: %s", err.Error())
  323. }
  324. parts = append(parts, GeminiPart{
  325. InlineData: &GeminiInlineData{
  326. MimeType: format,
  327. Data: base64String,
  328. },
  329. })
  330. } else if part.Type == dto.ContentTypeInputAudio {
  331. if part.GetInputAudio().Data == "" {
  332. return nil, fmt.Errorf("only base64 audio is supported in gemini")
  333. }
  334. base64String, err := service.DecodeBase64AudioData(part.GetInputAudio().Data)
  335. if err != nil {
  336. return nil, fmt.Errorf("decode base64 audio data failed: %s", err.Error())
  337. }
  338. parts = append(parts, GeminiPart{
  339. InlineData: &GeminiInlineData{
  340. MimeType: "audio/" + part.GetInputAudio().Format,
  341. Data: base64String,
  342. },
  343. })
  344. }
  345. }
  346. content.Parts = parts
  347. // there's no assistant role in gemini and API shall vomit if Role is not user or model
  348. if content.Role == "assistant" {
  349. content.Role = "model"
  350. }
  351. geminiRequest.Contents = append(geminiRequest.Contents, content)
  352. }
  353. if len(system_content) > 0 {
  354. geminiRequest.SystemInstructions = &GeminiChatContent{
  355. Parts: []GeminiPart{
  356. {
  357. Text: strings.Join(system_content, "\n"),
  358. },
  359. },
  360. }
  361. }
  362. return &geminiRequest, nil
  363. }
  364. // Helper function to get a list of supported MIME types for error messages
  365. func getSupportedMimeTypesList() []string {
  366. keys := make([]string, 0, len(geminiSupportedMimeTypes))
  367. for k := range geminiSupportedMimeTypes {
  368. keys = append(keys, k)
  369. }
  370. return keys
  371. }
  372. // cleanFunctionParameters recursively removes unsupported fields from Gemini function parameters.
  373. func cleanFunctionParameters(params interface{}) interface{} {
  374. if params == nil {
  375. return nil
  376. }
  377. switch v := params.(type) {
  378. case map[string]interface{}:
  379. // Create a copy to avoid modifying the original
  380. cleanedMap := make(map[string]interface{})
  381. for k, val := range v {
  382. cleanedMap[k] = val
  383. }
  384. // Remove unsupported root-level fields
  385. delete(cleanedMap, "default")
  386. delete(cleanedMap, "exclusiveMaximum")
  387. delete(cleanedMap, "exclusiveMinimum")
  388. delete(cleanedMap, "$schema")
  389. delete(cleanedMap, "additionalProperties")
  390. // Check and clean 'format' for string types
  391. if propType, typeExists := cleanedMap["type"].(string); typeExists && propType == "string" {
  392. if formatValue, formatExists := cleanedMap["format"].(string); formatExists {
  393. if formatValue != "enum" && formatValue != "date-time" {
  394. delete(cleanedMap, "format")
  395. }
  396. }
  397. }
  398. // Clean properties
  399. if props, ok := cleanedMap["properties"].(map[string]interface{}); ok && props != nil {
  400. cleanedProps := make(map[string]interface{})
  401. for propName, propValue := range props {
  402. cleanedProps[propName] = cleanFunctionParameters(propValue)
  403. }
  404. cleanedMap["properties"] = cleanedProps
  405. }
  406. // Recursively clean items in arrays
  407. if items, ok := cleanedMap["items"].(map[string]interface{}); ok && items != nil {
  408. cleanedMap["items"] = cleanFunctionParameters(items)
  409. }
  410. // Also handle items if it's an array of schemas
  411. if itemsArray, ok := cleanedMap["items"].([]interface{}); ok {
  412. cleanedItemsArray := make([]interface{}, len(itemsArray))
  413. for i, item := range itemsArray {
  414. cleanedItemsArray[i] = cleanFunctionParameters(item)
  415. }
  416. cleanedMap["items"] = cleanedItemsArray
  417. }
  418. // Recursively clean other schema composition keywords
  419. for _, field := range []string{"allOf", "anyOf", "oneOf"} {
  420. if nested, ok := cleanedMap[field].([]interface{}); ok {
  421. cleanedNested := make([]interface{}, len(nested))
  422. for i, item := range nested {
  423. cleanedNested[i] = cleanFunctionParameters(item)
  424. }
  425. cleanedMap[field] = cleanedNested
  426. }
  427. }
  428. // Recursively clean patternProperties
  429. if patternProps, ok := cleanedMap["patternProperties"].(map[string]interface{}); ok {
  430. cleanedPatternProps := make(map[string]interface{})
  431. for pattern, schema := range patternProps {
  432. cleanedPatternProps[pattern] = cleanFunctionParameters(schema)
  433. }
  434. cleanedMap["patternProperties"] = cleanedPatternProps
  435. }
  436. // Recursively clean definitions
  437. if definitions, ok := cleanedMap["definitions"].(map[string]interface{}); ok {
  438. cleanedDefinitions := make(map[string]interface{})
  439. for defName, defSchema := range definitions {
  440. cleanedDefinitions[defName] = cleanFunctionParameters(defSchema)
  441. }
  442. cleanedMap["definitions"] = cleanedDefinitions
  443. }
  444. // Recursively clean $defs (newer JSON Schema draft)
  445. if defs, ok := cleanedMap["$defs"].(map[string]interface{}); ok {
  446. cleanedDefs := make(map[string]interface{})
  447. for defName, defSchema := range defs {
  448. cleanedDefs[defName] = cleanFunctionParameters(defSchema)
  449. }
  450. cleanedMap["$defs"] = cleanedDefs
  451. }
  452. // Clean conditional keywords
  453. for _, field := range []string{"if", "then", "else", "not"} {
  454. if nested, ok := cleanedMap[field]; ok {
  455. cleanedMap[field] = cleanFunctionParameters(nested)
  456. }
  457. }
  458. return cleanedMap
  459. case []interface{}:
  460. // Handle arrays of schemas
  461. cleanedArray := make([]interface{}, len(v))
  462. for i, item := range v {
  463. cleanedArray[i] = cleanFunctionParameters(item)
  464. }
  465. return cleanedArray
  466. default:
  467. // Not a map or array, return as is (e.g., could be a primitive)
  468. return params
  469. }
  470. }
  471. func removeAdditionalPropertiesWithDepth(schema interface{}, depth int) interface{} {
  472. if depth >= 5 {
  473. return schema
  474. }
  475. v, ok := schema.(map[string]interface{})
  476. if !ok || len(v) == 0 {
  477. return schema
  478. }
  479. // 删除所有的title字段
  480. delete(v, "title")
  481. delete(v, "$schema")
  482. // 如果type不为object和array,则直接返回
  483. if typeVal, exists := v["type"]; !exists || (typeVal != "object" && typeVal != "array") {
  484. return schema
  485. }
  486. switch v["type"] {
  487. case "object":
  488. delete(v, "additionalProperties")
  489. // 处理 properties
  490. if properties, ok := v["properties"].(map[string]interface{}); ok {
  491. for key, value := range properties {
  492. properties[key] = removeAdditionalPropertiesWithDepth(value, depth+1)
  493. }
  494. }
  495. for _, field := range []string{"allOf", "anyOf", "oneOf"} {
  496. if nested, ok := v[field].([]interface{}); ok {
  497. for i, item := range nested {
  498. nested[i] = removeAdditionalPropertiesWithDepth(item, depth+1)
  499. }
  500. }
  501. }
  502. case "array":
  503. if items, ok := v["items"].(map[string]interface{}); ok {
  504. v["items"] = removeAdditionalPropertiesWithDepth(items, depth+1)
  505. }
  506. }
  507. return v
  508. }
  509. func unescapeString(s string) (string, error) {
  510. var result []rune
  511. escaped := false
  512. i := 0
  513. for i < len(s) {
  514. r, size := utf8.DecodeRuneInString(s[i:]) // 正确解码UTF-8字符
  515. if r == utf8.RuneError {
  516. return "", fmt.Errorf("invalid UTF-8 encoding")
  517. }
  518. if escaped {
  519. // 如果是转义符后的字符,检查其类型
  520. switch r {
  521. case '"':
  522. result = append(result, '"')
  523. case '\\':
  524. result = append(result, '\\')
  525. case '/':
  526. result = append(result, '/')
  527. case 'b':
  528. result = append(result, '\b')
  529. case 'f':
  530. result = append(result, '\f')
  531. case 'n':
  532. result = append(result, '\n')
  533. case 'r':
  534. result = append(result, '\r')
  535. case 't':
  536. result = append(result, '\t')
  537. case '\'':
  538. result = append(result, '\'')
  539. default:
  540. // 如果遇到一个非法的转义字符,直接按原样输出
  541. result = append(result, '\\', r)
  542. }
  543. escaped = false
  544. } else {
  545. if r == '\\' {
  546. escaped = true // 记录反斜杠作为转义符
  547. } else {
  548. result = append(result, r)
  549. }
  550. }
  551. i += size // 移动到下一个字符
  552. }
  553. return string(result), nil
  554. }
  555. func unescapeMapOrSlice(data interface{}) interface{} {
  556. switch v := data.(type) {
  557. case map[string]interface{}:
  558. for k, val := range v {
  559. v[k] = unescapeMapOrSlice(val)
  560. }
  561. case []interface{}:
  562. for i, val := range v {
  563. v[i] = unescapeMapOrSlice(val)
  564. }
  565. case string:
  566. if unescaped, err := unescapeString(v); err != nil {
  567. return v
  568. } else {
  569. return unescaped
  570. }
  571. }
  572. return data
  573. }
  574. func getResponseToolCall(item *GeminiPart) *dto.ToolCallResponse {
  575. var argsBytes []byte
  576. var err error
  577. if result, ok := item.FunctionCall.Arguments.(map[string]interface{}); ok {
  578. argsBytes, err = json.Marshal(unescapeMapOrSlice(result))
  579. } else {
  580. argsBytes, err = json.Marshal(item.FunctionCall.Arguments)
  581. }
  582. if err != nil {
  583. return nil
  584. }
  585. return &dto.ToolCallResponse{
  586. ID: fmt.Sprintf("call_%s", common.GetUUID()),
  587. Type: "function",
  588. Function: dto.FunctionResponse{
  589. Arguments: string(argsBytes),
  590. Name: item.FunctionCall.FunctionName,
  591. },
  592. }
  593. }
  594. func responseGeminiChat2OpenAI(c *gin.Context, response *GeminiChatResponse) *dto.OpenAITextResponse {
  595. fullTextResponse := dto.OpenAITextResponse{
  596. Id: helper.GetResponseID(c),
  597. Object: "chat.completion",
  598. Created: common.GetTimestamp(),
  599. Choices: make([]dto.OpenAITextResponseChoice, 0, len(response.Candidates)),
  600. }
  601. isToolCall := false
  602. for _, candidate := range response.Candidates {
  603. choice := dto.OpenAITextResponseChoice{
  604. Index: int(candidate.Index),
  605. Message: dto.Message{
  606. Role: "assistant",
  607. Content: "",
  608. },
  609. FinishReason: constant.FinishReasonStop,
  610. }
  611. if len(candidate.Content.Parts) > 0 {
  612. var texts []string
  613. var toolCalls []dto.ToolCallResponse
  614. for _, part := range candidate.Content.Parts {
  615. if part.FunctionCall != nil {
  616. choice.FinishReason = constant.FinishReasonToolCalls
  617. if call := getResponseToolCall(&part); call != nil {
  618. toolCalls = append(toolCalls, *call)
  619. }
  620. } else if part.Thought {
  621. choice.Message.ReasoningContent = part.Text
  622. } else {
  623. if part.ExecutableCode != nil {
  624. texts = append(texts, "```"+part.ExecutableCode.Language+"\n"+part.ExecutableCode.Code+"\n```")
  625. } else if part.CodeExecutionResult != nil {
  626. texts = append(texts, "```output\n"+part.CodeExecutionResult.Output+"\n```")
  627. } else {
  628. // 过滤掉空行
  629. if part.Text != "\n" {
  630. texts = append(texts, part.Text)
  631. }
  632. }
  633. }
  634. }
  635. if len(toolCalls) > 0 {
  636. choice.Message.SetToolCalls(toolCalls)
  637. isToolCall = true
  638. }
  639. choice.Message.SetStringContent(strings.Join(texts, "\n"))
  640. }
  641. if candidate.FinishReason != nil {
  642. switch *candidate.FinishReason {
  643. case "STOP":
  644. choice.FinishReason = constant.FinishReasonStop
  645. case "MAX_TOKENS":
  646. choice.FinishReason = constant.FinishReasonLength
  647. default:
  648. choice.FinishReason = constant.FinishReasonContentFilter
  649. }
  650. }
  651. if isToolCall {
  652. choice.FinishReason = constant.FinishReasonToolCalls
  653. }
  654. fullTextResponse.Choices = append(fullTextResponse.Choices, choice)
  655. }
  656. return &fullTextResponse
  657. }
  658. func streamResponseGeminiChat2OpenAI(geminiResponse *GeminiChatResponse) (*dto.ChatCompletionsStreamResponse, bool, bool) {
  659. choices := make([]dto.ChatCompletionsStreamResponseChoice, 0, len(geminiResponse.Candidates))
  660. isStop := false
  661. hasImage := false
  662. for _, candidate := range geminiResponse.Candidates {
  663. if candidate.FinishReason != nil && *candidate.FinishReason == "STOP" {
  664. isStop = true
  665. candidate.FinishReason = nil
  666. }
  667. choice := dto.ChatCompletionsStreamResponseChoice{
  668. Index: int(candidate.Index),
  669. Delta: dto.ChatCompletionsStreamResponseChoiceDelta{
  670. Role: "assistant",
  671. },
  672. }
  673. var texts []string
  674. isTools := false
  675. isThought := false
  676. if candidate.FinishReason != nil {
  677. // p := GeminiConvertFinishReason(*candidate.FinishReason)
  678. switch *candidate.FinishReason {
  679. case "STOP":
  680. choice.FinishReason = &constant.FinishReasonStop
  681. case "MAX_TOKENS":
  682. choice.FinishReason = &constant.FinishReasonLength
  683. default:
  684. choice.FinishReason = &constant.FinishReasonContentFilter
  685. }
  686. }
  687. for _, part := range candidate.Content.Parts {
  688. if part.InlineData != nil {
  689. if strings.HasPrefix(part.InlineData.MimeType, "image") {
  690. imgText := "![image](data:" + part.InlineData.MimeType + ";base64," + part.InlineData.Data + ")"
  691. texts = append(texts, imgText)
  692. hasImage = true
  693. }
  694. } else if part.FunctionCall != nil {
  695. isTools = true
  696. if call := getResponseToolCall(&part); call != nil {
  697. call.SetIndex(len(choice.Delta.ToolCalls))
  698. choice.Delta.ToolCalls = append(choice.Delta.ToolCalls, *call)
  699. }
  700. } else if part.Thought {
  701. isThought = true
  702. texts = append(texts, part.Text)
  703. } else {
  704. if part.ExecutableCode != nil {
  705. texts = append(texts, "```"+part.ExecutableCode.Language+"\n"+part.ExecutableCode.Code+"\n```\n")
  706. } else if part.CodeExecutionResult != nil {
  707. texts = append(texts, "```output\n"+part.CodeExecutionResult.Output+"\n```\n")
  708. } else {
  709. if part.Text != "\n" {
  710. texts = append(texts, part.Text)
  711. }
  712. }
  713. }
  714. }
  715. if isThought {
  716. choice.Delta.SetReasoningContent(strings.Join(texts, "\n"))
  717. } else {
  718. choice.Delta.SetContentString(strings.Join(texts, "\n"))
  719. }
  720. if isTools {
  721. choice.FinishReason = &constant.FinishReasonToolCalls
  722. }
  723. choices = append(choices, choice)
  724. }
  725. var response dto.ChatCompletionsStreamResponse
  726. response.Object = "chat.completion.chunk"
  727. response.Choices = choices
  728. return &response, isStop, hasImage
  729. }
  730. func GeminiChatStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.OpenAIErrorWithStatusCode, *dto.Usage) {
  731. // responseText := ""
  732. id := helper.GetResponseID(c)
  733. createAt := common.GetTimestamp()
  734. var usage = &dto.Usage{}
  735. var imageCount int
  736. helper.StreamScannerHandler(c, resp, info, func(data string) bool {
  737. var geminiResponse GeminiChatResponse
  738. err := common.DecodeJsonStr(data, &geminiResponse)
  739. if err != nil {
  740. common.LogError(c, "error unmarshalling stream response: "+err.Error())
  741. return false
  742. }
  743. response, isStop, hasImage := streamResponseGeminiChat2OpenAI(&geminiResponse)
  744. if hasImage {
  745. imageCount++
  746. }
  747. response.Id = id
  748. response.Created = createAt
  749. response.Model = info.UpstreamModelName
  750. if geminiResponse.UsageMetadata.TotalTokenCount != 0 {
  751. usage.PromptTokens = geminiResponse.UsageMetadata.PromptTokenCount
  752. usage.CompletionTokens = geminiResponse.UsageMetadata.CandidatesTokenCount
  753. usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
  754. usage.TotalTokens = geminiResponse.UsageMetadata.TotalTokenCount
  755. for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
  756. if detail.Modality == "AUDIO" {
  757. usage.PromptTokensDetails.AudioTokens = detail.TokenCount
  758. } else if detail.Modality == "TEXT" {
  759. usage.PromptTokensDetails.TextTokens = detail.TokenCount
  760. }
  761. }
  762. }
  763. err = helper.ObjectData(c, response)
  764. if err != nil {
  765. common.LogError(c, err.Error())
  766. }
  767. if isStop {
  768. response := helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, constant.FinishReasonStop)
  769. helper.ObjectData(c, response)
  770. }
  771. return true
  772. })
  773. var response *dto.ChatCompletionsStreamResponse
  774. if imageCount != 0 {
  775. if usage.CompletionTokens == 0 {
  776. usage.CompletionTokens = imageCount * 258
  777. }
  778. }
  779. usage.PromptTokensDetails.TextTokens = usage.PromptTokens
  780. usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
  781. if info.ShouldIncludeUsage {
  782. response = helper.GenerateFinalUsageResponse(id, createAt, info.UpstreamModelName, *usage)
  783. err := helper.ObjectData(c, response)
  784. if err != nil {
  785. common.SysError("send final response failed: " + err.Error())
  786. }
  787. }
  788. helper.Done(c)
  789. //resp.Body.Close()
  790. return nil, usage
  791. }
  792. func GeminiChatHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.OpenAIErrorWithStatusCode, *dto.Usage) {
  793. responseBody, err := io.ReadAll(resp.Body)
  794. if err != nil {
  795. return service.OpenAIErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError), nil
  796. }
  797. err = resp.Body.Close()
  798. if err != nil {
  799. return service.OpenAIErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), nil
  800. }
  801. if common.DebugEnabled {
  802. println(string(responseBody))
  803. }
  804. var geminiResponse GeminiChatResponse
  805. err = common.DecodeJson(responseBody, &geminiResponse)
  806. if err != nil {
  807. return service.OpenAIErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError), nil
  808. }
  809. if len(geminiResponse.Candidates) == 0 {
  810. return &dto.OpenAIErrorWithStatusCode{
  811. Error: dto.OpenAIError{
  812. Message: "No candidates returned",
  813. Type: "server_error",
  814. Param: "",
  815. Code: 500,
  816. },
  817. StatusCode: resp.StatusCode,
  818. }, nil
  819. }
  820. fullTextResponse := responseGeminiChat2OpenAI(c, &geminiResponse)
  821. fullTextResponse.Model = info.UpstreamModelName
  822. usage := dto.Usage{
  823. PromptTokens: geminiResponse.UsageMetadata.PromptTokenCount,
  824. CompletionTokens: geminiResponse.UsageMetadata.CandidatesTokenCount,
  825. TotalTokens: geminiResponse.UsageMetadata.TotalTokenCount,
  826. }
  827. usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
  828. usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
  829. for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
  830. if detail.Modality == "AUDIO" {
  831. usage.PromptTokensDetails.AudioTokens = detail.TokenCount
  832. } else if detail.Modality == "TEXT" {
  833. usage.PromptTokensDetails.TextTokens = detail.TokenCount
  834. }
  835. }
  836. fullTextResponse.Usage = usage
  837. jsonResponse, err := json.Marshal(fullTextResponse)
  838. if err != nil {
  839. return service.OpenAIErrorWrapper(err, "marshal_response_body_failed", http.StatusInternalServerError), nil
  840. }
  841. c.Writer.Header().Set("Content-Type", "application/json")
  842. c.Writer.WriteHeader(resp.StatusCode)
  843. _, err = c.Writer.Write(jsonResponse)
  844. return nil, &usage
  845. }
  846. func GeminiEmbeddingHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  847. responseBody, readErr := io.ReadAll(resp.Body)
  848. if readErr != nil {
  849. return nil, service.OpenAIErrorWrapper(readErr, "read_response_body_failed", http.StatusInternalServerError)
  850. }
  851. _ = resp.Body.Close()
  852. var geminiResponse GeminiEmbeddingResponse
  853. if jsonErr := json.Unmarshal(responseBody, &geminiResponse); jsonErr != nil {
  854. return nil, service.OpenAIErrorWrapper(jsonErr, "unmarshal_response_body_failed", http.StatusInternalServerError)
  855. }
  856. // convert to openai format response
  857. openAIResponse := dto.OpenAIEmbeddingResponse{
  858. Object: "list",
  859. Data: []dto.OpenAIEmbeddingResponseItem{
  860. {
  861. Object: "embedding",
  862. Embedding: geminiResponse.Embedding.Values,
  863. Index: 0,
  864. },
  865. },
  866. Model: info.UpstreamModelName,
  867. }
  868. // calculate usage
  869. // https://ai.google.dev/gemini-api/docs/pricing?hl=zh-cn#text-embedding-004
  870. // Google has not yet clarified how embedding models will be billed
  871. // refer to openai billing method to use input tokens billing
  872. // https://platform.openai.com/docs/guides/embeddings#what-are-embeddings
  873. usage = &dto.Usage{
  874. PromptTokens: info.PromptTokens,
  875. CompletionTokens: 0,
  876. TotalTokens: info.PromptTokens,
  877. }
  878. openAIResponse.Usage = *usage.(*dto.Usage)
  879. jsonResponse, jsonErr := json.Marshal(openAIResponse)
  880. if jsonErr != nil {
  881. return nil, service.OpenAIErrorWrapper(jsonErr, "marshal_response_failed", http.StatusInternalServerError)
  882. }
  883. c.Writer.Header().Set("Content-Type", "application/json")
  884. c.Writer.WriteHeader(resp.StatusCode)
  885. _, _ = c.Writer.Write(jsonResponse)
  886. return usage, nil
  887. }