transform.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. import type { APICallError, ModelMessage } from "ai"
  2. import { unique } from "remeda"
  3. import type { JSONSchema } from "zod/v4/core"
  4. import type { Provider } from "./provider"
  5. import type { ModelsDev } from "./models"
  6. import { iife } from "@/util/iife"
  7. type Modality = NonNullable<ModelsDev.Model["modalities"]>["input"][number]
  8. function mimeToModality(mime: string): Modality | undefined {
  9. if (mime.startsWith("image/")) return "image"
  10. if (mime.startsWith("audio/")) return "audio"
  11. if (mime.startsWith("video/")) return "video"
  12. if (mime === "application/pdf") return "pdf"
  13. return undefined
  14. }
  15. export namespace ProviderTransform {
  16. // Maps npm package to the key the AI SDK expects for providerOptions
  17. function sdkKey(npm: string): string | undefined {
  18. switch (npm) {
  19. case "@ai-sdk/github-copilot":
  20. case "@ai-sdk/openai":
  21. case "@ai-sdk/azure":
  22. return "openai"
  23. case "@ai-sdk/amazon-bedrock":
  24. return "bedrock"
  25. case "@ai-sdk/anthropic":
  26. return "anthropic"
  27. case "@ai-sdk/google-vertex":
  28. case "@ai-sdk/google":
  29. return "google"
  30. case "@ai-sdk/gateway":
  31. return "gateway"
  32. case "@openrouter/ai-sdk-provider":
  33. return "openrouter"
  34. }
  35. return undefined
  36. }
  37. function normalizeMessages(
  38. msgs: ModelMessage[],
  39. model: Provider.Model,
  40. options: Record<string, unknown>,
  41. ): ModelMessage[] {
  42. // Anthropic rejects messages with empty content - filter out empty string messages
  43. // and remove empty text/reasoning parts from array content
  44. if (model.api.npm === "@ai-sdk/anthropic") {
  45. msgs = msgs
  46. .map((msg) => {
  47. if (typeof msg.content === "string") {
  48. if (msg.content === "") return undefined
  49. return msg
  50. }
  51. if (!Array.isArray(msg.content)) return msg
  52. const filtered = msg.content.filter((part) => {
  53. if (part.type === "text" || part.type === "reasoning") {
  54. return part.text !== ""
  55. }
  56. return true
  57. })
  58. if (filtered.length === 0) return undefined
  59. return { ...msg, content: filtered }
  60. })
  61. .filter((msg): msg is ModelMessage => msg !== undefined && msg.content !== "")
  62. }
  63. if (model.api.id.includes("claude")) {
  64. return msgs.map((msg) => {
  65. if ((msg.role === "assistant" || msg.role === "tool") && Array.isArray(msg.content)) {
  66. msg.content = msg.content.map((part) => {
  67. if ((part.type === "tool-call" || part.type === "tool-result") && "toolCallId" in part) {
  68. return {
  69. ...part,
  70. toolCallId: part.toolCallId.replace(/[^a-zA-Z0-9_-]/g, "_"),
  71. }
  72. }
  73. return part
  74. })
  75. }
  76. return msg
  77. })
  78. }
  79. if (model.providerID === "mistral" || model.api.id.toLowerCase().includes("mistral")) {
  80. const result: ModelMessage[] = []
  81. for (let i = 0; i < msgs.length; i++) {
  82. const msg = msgs[i]
  83. const nextMsg = msgs[i + 1]
  84. if ((msg.role === "assistant" || msg.role === "tool") && Array.isArray(msg.content)) {
  85. msg.content = msg.content.map((part) => {
  86. if ((part.type === "tool-call" || part.type === "tool-result") && "toolCallId" in part) {
  87. // Mistral requires alphanumeric tool call IDs with exactly 9 characters
  88. const normalizedId = part.toolCallId
  89. .replace(/[^a-zA-Z0-9]/g, "") // Remove non-alphanumeric characters
  90. .substring(0, 9) // Take first 9 characters
  91. .padEnd(9, "0") // Pad with zeros if less than 9 characters
  92. return {
  93. ...part,
  94. toolCallId: normalizedId,
  95. }
  96. }
  97. return part
  98. })
  99. }
  100. result.push(msg)
  101. // Fix message sequence: tool messages cannot be followed by user messages
  102. if (msg.role === "tool" && nextMsg?.role === "user") {
  103. result.push({
  104. role: "assistant",
  105. content: [
  106. {
  107. type: "text",
  108. text: "Done.",
  109. },
  110. ],
  111. })
  112. }
  113. }
  114. return result
  115. }
  116. if (
  117. model.capabilities.interleaved &&
  118. typeof model.capabilities.interleaved === "object" &&
  119. model.capabilities.interleaved.field === "reasoning_content"
  120. ) {
  121. return msgs.map((msg) => {
  122. if (msg.role === "assistant" && Array.isArray(msg.content)) {
  123. const reasoningParts = msg.content.filter((part: any) => part.type === "reasoning")
  124. const reasoningText = reasoningParts.map((part: any) => part.text).join("")
  125. // Filter out reasoning parts from content
  126. const filteredContent = msg.content.filter((part: any) => part.type !== "reasoning")
  127. // Include reasoning_content directly on the message for all assistant messages
  128. if (reasoningText) {
  129. return {
  130. ...msg,
  131. content: filteredContent,
  132. providerOptions: {
  133. ...msg.providerOptions,
  134. openaiCompatible: {
  135. ...(msg.providerOptions as any)?.openaiCompatible,
  136. reasoning_content: reasoningText,
  137. },
  138. },
  139. }
  140. }
  141. return {
  142. ...msg,
  143. content: filteredContent,
  144. }
  145. }
  146. return msg
  147. })
  148. }
  149. return msgs
  150. }
  151. function applyCaching(msgs: ModelMessage[], providerID: string): ModelMessage[] {
  152. const system = msgs.filter((msg) => msg.role === "system").slice(0, 2)
  153. const final = msgs.filter((msg) => msg.role !== "system").slice(-2)
  154. const providerOptions = {
  155. anthropic: {
  156. cacheControl: { type: "ephemeral" },
  157. },
  158. openrouter: {
  159. cacheControl: { type: "ephemeral" },
  160. },
  161. bedrock: {
  162. cachePoint: { type: "ephemeral" },
  163. },
  164. openaiCompatible: {
  165. cache_control: { type: "ephemeral" },
  166. },
  167. }
  168. for (const msg of unique([...system, ...final])) {
  169. const shouldUseContentOptions = providerID !== "anthropic" && Array.isArray(msg.content) && msg.content.length > 0
  170. if (shouldUseContentOptions) {
  171. const lastContent = msg.content[msg.content.length - 1]
  172. if (lastContent && typeof lastContent === "object") {
  173. lastContent.providerOptions = {
  174. ...lastContent.providerOptions,
  175. ...providerOptions,
  176. }
  177. continue
  178. }
  179. }
  180. msg.providerOptions = {
  181. ...msg.providerOptions,
  182. ...providerOptions,
  183. }
  184. }
  185. return msgs
  186. }
  187. function unsupportedParts(msgs: ModelMessage[], model: Provider.Model): ModelMessage[] {
  188. return msgs.map((msg) => {
  189. if (msg.role !== "user" || !Array.isArray(msg.content)) return msg
  190. const filtered = msg.content.map((part) => {
  191. if (part.type !== "file" && part.type !== "image") return part
  192. // Check for empty base64 image data
  193. if (part.type === "image") {
  194. const imageStr = part.image.toString()
  195. if (imageStr.startsWith("data:")) {
  196. const match = imageStr.match(/^data:([^;]+);base64,(.*)$/)
  197. if (match && (!match[2] || match[2].length === 0)) {
  198. return {
  199. type: "text" as const,
  200. text: "ERROR: Image file is empty or corrupted. Please provide a valid image.",
  201. }
  202. }
  203. }
  204. }
  205. const mime = part.type === "image" ? part.image.toString().split(";")[0].replace("data:", "") : part.mediaType
  206. const filename = part.type === "file" ? part.filename : undefined
  207. const modality = mimeToModality(mime)
  208. if (!modality) return part
  209. if (model.capabilities.input[modality]) return part
  210. const name = filename ? `"${filename}"` : modality
  211. return {
  212. type: "text" as const,
  213. text: `ERROR: Cannot read ${name} (this model does not support ${modality} input). Inform the user.`,
  214. }
  215. })
  216. return { ...msg, content: filtered }
  217. })
  218. }
  219. export function message(msgs: ModelMessage[], model: Provider.Model, options: Record<string, unknown>) {
  220. msgs = unsupportedParts(msgs, model)
  221. msgs = normalizeMessages(msgs, model, options)
  222. if (
  223. model.providerID === "anthropic" ||
  224. model.api.id.includes("anthropic") ||
  225. model.api.id.includes("claude") ||
  226. model.api.npm === "@ai-sdk/anthropic"
  227. ) {
  228. msgs = applyCaching(msgs, model.providerID)
  229. }
  230. // Remap providerOptions keys from stored providerID to expected SDK key
  231. const key = sdkKey(model.api.npm)
  232. if (key && key !== model.providerID && model.api.npm !== "@ai-sdk/azure") {
  233. const remap = (opts: Record<string, any> | undefined) => {
  234. if (!opts) return opts
  235. if (!(model.providerID in opts)) return opts
  236. const result = { ...opts }
  237. result[key] = result[model.providerID]
  238. delete result[model.providerID]
  239. return result
  240. }
  241. msgs = msgs.map((msg) => {
  242. if (!Array.isArray(msg.content)) return { ...msg, providerOptions: remap(msg.providerOptions) }
  243. return {
  244. ...msg,
  245. providerOptions: remap(msg.providerOptions),
  246. content: msg.content.map((part) => ({ ...part, providerOptions: remap(part.providerOptions) })),
  247. } as typeof msg
  248. })
  249. }
  250. return msgs
  251. }
  252. export function temperature(model: Provider.Model) {
  253. const id = model.id.toLowerCase()
  254. if (id.includes("qwen")) return 0.55
  255. if (id.includes("claude")) return undefined
  256. if (id.includes("gemini")) return 1.0
  257. if (id.includes("glm-4.6")) return 1.0
  258. if (id.includes("glm-4.7")) return 1.0
  259. if (id.includes("minimax-m2")) return 1.0
  260. if (id.includes("kimi-k2")) {
  261. if (id.includes("thinking")) return 1.0
  262. return 0.6
  263. }
  264. return undefined
  265. }
  266. export function topP(model: Provider.Model) {
  267. const id = model.id.toLowerCase()
  268. if (id.includes("qwen")) return 1
  269. if (id.includes("minimax-m2")) {
  270. return 0.95
  271. }
  272. if (id.includes("gemini")) return 0.95
  273. return undefined
  274. }
  275. export function topK(model: Provider.Model) {
  276. const id = model.id.toLowerCase()
  277. if (id.includes("minimax-m2")) {
  278. if (id.includes("m2.1")) return 40
  279. return 20
  280. }
  281. if (id.includes("gemini")) return 64
  282. return undefined
  283. }
  284. const WIDELY_SUPPORTED_EFFORTS = ["low", "medium", "high"]
  285. const OPENAI_EFFORTS = ["none", "minimal", ...WIDELY_SUPPORTED_EFFORTS, "xhigh"]
  286. export function variants(model: Provider.Model): Record<string, Record<string, any>> {
  287. if (!model.capabilities.reasoning) return {}
  288. const id = model.id.toLowerCase()
  289. if (id.includes("deepseek") || id.includes("minimax") || id.includes("glm") || id.includes("mistral")) return {}
  290. switch (model.api.npm) {
  291. case "@openrouter/ai-sdk-provider":
  292. if (!model.id.includes("gpt") && !model.id.includes("gemini-3") && !model.id.includes("grok-4")) return {}
  293. return Object.fromEntries(OPENAI_EFFORTS.map((effort) => [effort, { reasoning: { effort } }]))
  294. // TODO: YOU CANNOT SET max_tokens if this is set!!!
  295. case "@ai-sdk/gateway":
  296. return Object.fromEntries(OPENAI_EFFORTS.map((effort) => [effort, { reasoningEffort: effort }]))
  297. case "@ai-sdk/cerebras":
  298. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/cerebras
  299. case "@ai-sdk/togetherai":
  300. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/togetherai
  301. case "@ai-sdk/xai":
  302. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/xai
  303. case "@ai-sdk/deepinfra":
  304. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/deepinfra
  305. case "@ai-sdk/openai-compatible":
  306. return Object.fromEntries(WIDELY_SUPPORTED_EFFORTS.map((effort) => [effort, { reasoningEffort: effort }]))
  307. case "@ai-sdk/azure":
  308. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/azure
  309. if (id === "o1-mini") return {}
  310. const azureEfforts = ["low", "medium", "high"]
  311. if (id.includes("gpt-5-") || id === "gpt-5") {
  312. azureEfforts.unshift("minimal")
  313. }
  314. return Object.fromEntries(
  315. azureEfforts.map((effort) => [
  316. effort,
  317. {
  318. reasoningEffort: effort,
  319. reasoningSummary: "auto",
  320. include: ["reasoning.encrypted_content"],
  321. },
  322. ]),
  323. )
  324. case "@ai-sdk/openai":
  325. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/openai
  326. if (id === "gpt-5-pro") return {}
  327. const openaiEfforts = iife(() => {
  328. if (id.includes("codex")) {
  329. if (id.includes("5.2")) return [...WIDELY_SUPPORTED_EFFORTS, "xhigh"]
  330. return WIDELY_SUPPORTED_EFFORTS
  331. }
  332. const arr = [...WIDELY_SUPPORTED_EFFORTS]
  333. if (id.includes("gpt-5-") || id === "gpt-5") {
  334. arr.unshift("minimal")
  335. }
  336. if (model.release_date >= "2025-11-13") {
  337. arr.unshift("none")
  338. }
  339. if (model.release_date >= "2025-12-04") {
  340. arr.push("xhigh")
  341. }
  342. return arr
  343. })
  344. return Object.fromEntries(
  345. openaiEfforts.map((effort) => [
  346. effort,
  347. {
  348. reasoningEffort: effort,
  349. reasoningSummary: "auto",
  350. include: ["reasoning.encrypted_content"],
  351. },
  352. ]),
  353. )
  354. case "@ai-sdk/anthropic":
  355. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/anthropic
  356. return {
  357. high: {
  358. thinking: {
  359. type: "enabled",
  360. budgetTokens: 16000,
  361. },
  362. },
  363. max: {
  364. thinking: {
  365. type: "enabled",
  366. budgetTokens: 31999,
  367. },
  368. },
  369. }
  370. case "@ai-sdk/amazon-bedrock":
  371. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/amazon-bedrock
  372. // For Anthropic models on Bedrock, use reasoningConfig with budgetTokens
  373. if (model.api.id.includes("anthropic")) {
  374. return {
  375. high: {
  376. reasoningConfig: {
  377. type: "enabled",
  378. budgetTokens: 16000,
  379. },
  380. },
  381. max: {
  382. reasoningConfig: {
  383. type: "enabled",
  384. budgetTokens: 31999,
  385. },
  386. },
  387. }
  388. }
  389. // For Amazon Nova models, use reasoningConfig with maxReasoningEffort
  390. return Object.fromEntries(
  391. WIDELY_SUPPORTED_EFFORTS.map((effort) => [
  392. effort,
  393. {
  394. reasoningConfig: {
  395. type: "enabled",
  396. maxReasoningEffort: effort,
  397. },
  398. },
  399. ]),
  400. )
  401. case "@ai-sdk/google-vertex":
  402. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/google-vertex
  403. case "@ai-sdk/google":
  404. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai
  405. if (id.includes("2.5")) {
  406. return {
  407. high: {
  408. thinkingConfig: {
  409. includeThoughts: true,
  410. thinkingBudget: 16000,
  411. },
  412. },
  413. max: {
  414. thinkingConfig: {
  415. includeThoughts: true,
  416. thinkingBudget: 24576,
  417. },
  418. },
  419. }
  420. }
  421. return Object.fromEntries(
  422. ["low", "high"].map((effort) => [
  423. effort,
  424. {
  425. includeThoughts: true,
  426. thinkingLevel: effort,
  427. },
  428. ]),
  429. )
  430. case "@ai-sdk/mistral":
  431. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/mistral
  432. return {}
  433. case "@ai-sdk/cohere":
  434. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/cohere
  435. return {}
  436. case "@ai-sdk/groq":
  437. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/groq
  438. const groqEffort = ["none", ...WIDELY_SUPPORTED_EFFORTS]
  439. return Object.fromEntries(
  440. groqEffort.map((effort) => [
  441. effort,
  442. {
  443. includeThoughts: true,
  444. thinkingLevel: effort,
  445. },
  446. ]),
  447. )
  448. case "@ai-sdk/perplexity":
  449. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/perplexity
  450. return {}
  451. }
  452. return {}
  453. }
  454. export function options(input: {
  455. model: Provider.Model
  456. sessionID: string
  457. providerOptions?: Record<string, any>
  458. }): Record<string, any> {
  459. const result: Record<string, any> = {}
  460. // openai and providers using openai package should set store to false by default.
  461. if (input.model.providerID === "openai" || input.model.api.npm === "@ai-sdk/openai") {
  462. result["store"] = false
  463. }
  464. if (input.model.api.npm === "@openrouter/ai-sdk-provider") {
  465. result["usage"] = {
  466. include: true,
  467. }
  468. if (input.model.api.id.includes("gemini-3")) {
  469. result["reasoning"] = { effort: "high" }
  470. }
  471. }
  472. if (
  473. input.model.providerID === "baseten" ||
  474. (input.model.providerID === "opencode" && ["kimi-k2-thinking", "glm-4.6"].includes(input.model.api.id))
  475. ) {
  476. result["chat_template_args"] = { enable_thinking: true }
  477. }
  478. if (["zai", "zhipuai"].includes(input.model.providerID) && input.model.api.npm === "@ai-sdk/openai-compatible") {
  479. result["thinking"] = {
  480. type: "enabled",
  481. clear_thinking: false,
  482. }
  483. }
  484. if (input.model.providerID === "openai" || input.providerOptions?.setCacheKey) {
  485. result["promptCacheKey"] = input.sessionID
  486. }
  487. if (input.model.api.npm === "@ai-sdk/google" || input.model.api.npm === "@ai-sdk/google-vertex") {
  488. result["thinkingConfig"] = {
  489. includeThoughts: true,
  490. }
  491. if (input.model.api.id.includes("gemini-3")) {
  492. result["thinkingConfig"]["thinkingLevel"] = "high"
  493. }
  494. }
  495. if (input.model.api.id.includes("gpt-5") && !input.model.api.id.includes("gpt-5-chat")) {
  496. if (input.model.providerID.includes("codex")) {
  497. result["store"] = false
  498. }
  499. if (!input.model.api.id.includes("codex") && !input.model.api.id.includes("gpt-5-pro")) {
  500. result["reasoningEffort"] = "medium"
  501. }
  502. if (input.model.api.id.endsWith("gpt-5.") && input.model.providerID !== "azure") {
  503. result["textVerbosity"] = "low"
  504. }
  505. if (input.model.providerID.startsWith("opencode")) {
  506. result["promptCacheKey"] = input.sessionID
  507. result["include"] = ["reasoning.encrypted_content"]
  508. result["reasoningSummary"] = "auto"
  509. }
  510. }
  511. return result
  512. }
  513. export function smallOptions(model: Provider.Model) {
  514. if (model.providerID === "openai" || model.api.id.includes("gpt-5")) {
  515. if (model.api.id.includes("5.")) {
  516. return { reasoningEffort: "low" }
  517. }
  518. return { reasoningEffort: "minimal" }
  519. }
  520. if (model.providerID === "google") {
  521. // gemini-3 uses thinkingLevel, gemini-2.5 uses thinkingBudget
  522. if (model.api.id.includes("gemini-3")) {
  523. return { thinkingConfig: { thinkingLevel: "minimal" } }
  524. }
  525. return { thinkingConfig: { thinkingBudget: 0 } }
  526. }
  527. if (model.providerID === "openrouter") {
  528. if (model.api.id.includes("google")) {
  529. return { reasoning: { enabled: false } }
  530. }
  531. return { reasoningEffort: "minimal" }
  532. }
  533. return {}
  534. }
  535. export function providerOptions(model: Provider.Model, options: { [x: string]: any }) {
  536. const key = sdkKey(model.api.npm) ?? model.providerID
  537. return { [key]: options }
  538. }
  539. export function maxOutputTokens(
  540. npm: string,
  541. options: Record<string, any>,
  542. modelLimit: number,
  543. globalLimit: number,
  544. ): number {
  545. const modelCap = modelLimit || globalLimit
  546. const standardLimit = Math.min(modelCap, globalLimit)
  547. if (npm === "@ai-sdk/anthropic") {
  548. const thinking = options?.["thinking"]
  549. const budgetTokens = typeof thinking?.["budgetTokens"] === "number" ? thinking["budgetTokens"] : 0
  550. const enabled = thinking?.["type"] === "enabled"
  551. if (enabled && budgetTokens > 0) {
  552. // Return text tokens so that text + thinking <= model cap, preferring 32k text when possible.
  553. if (budgetTokens + standardLimit <= modelCap) {
  554. return standardLimit
  555. }
  556. return modelCap - budgetTokens
  557. }
  558. }
  559. return standardLimit
  560. }
  561. export function schema(model: Provider.Model, schema: JSONSchema.BaseSchema) {
  562. /*
  563. if (["openai", "azure"].includes(providerID)) {
  564. if (schema.type === "object" && schema.properties) {
  565. for (const [key, value] of Object.entries(schema.properties)) {
  566. if (schema.required?.includes(key)) continue
  567. schema.properties[key] = {
  568. anyOf: [
  569. value as JSONSchema.JSONSchema,
  570. {
  571. type: "null",
  572. },
  573. ],
  574. }
  575. }
  576. }
  577. }
  578. */
  579. // Convert integer enums to string enums for Google/Gemini
  580. if (model.providerID === "google" || model.api.id.includes("gemini")) {
  581. const sanitizeGemini = (obj: any): any => {
  582. if (obj === null || typeof obj !== "object") {
  583. return obj
  584. }
  585. if (Array.isArray(obj)) {
  586. return obj.map(sanitizeGemini)
  587. }
  588. const result: any = {}
  589. for (const [key, value] of Object.entries(obj)) {
  590. if (key === "enum" && Array.isArray(value)) {
  591. // Convert all enum values to strings
  592. result[key] = value.map((v) => String(v))
  593. // If we have integer type with enum, change type to string
  594. if (result.type === "integer" || result.type === "number") {
  595. result.type = "string"
  596. }
  597. } else if (typeof value === "object" && value !== null) {
  598. result[key] = sanitizeGemini(value)
  599. } else {
  600. result[key] = value
  601. }
  602. }
  603. // Filter required array to only include fields that exist in properties
  604. if (result.type === "object" && result.properties && Array.isArray(result.required)) {
  605. result.required = result.required.filter((field: any) => field in result.properties)
  606. }
  607. if (result.type === "array" && result.items == null) {
  608. result.items = {}
  609. }
  610. return result
  611. }
  612. schema = sanitizeGemini(schema)
  613. }
  614. return schema
  615. }
  616. export function error(providerID: string, error: APICallError) {
  617. let message = error.message
  618. if (providerID.includes("github-copilot") && error.statusCode === 403) {
  619. return "Please reauthenticate with the copilot provider to ensure your credentials work properly with OpenCode."
  620. }
  621. if (providerID.includes("github-copilot") && message.includes("The requested model is not supported")) {
  622. return (
  623. message +
  624. "\n\nMake sure the model is enabled in your copilot settings: https://github.com/settings/copilot/features"
  625. )
  626. }
  627. return message
  628. }
  629. }