relay-gemini.go 30 KB

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