transform.ts 24 KB

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