relay-gemini.go 30 KB

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