transform.ts 24 KB

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