transform.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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. return "copilot"
  21. case "@ai-sdk/openai":
  22. case "@ai-sdk/azure":
  23. return "openai"
  24. case "@ai-sdk/amazon-bedrock":
  25. return "bedrock"
  26. case "@ai-sdk/anthropic":
  27. case "@ai-sdk/google-vertex/anthropic":
  28. return "anthropic"
  29. case "@ai-sdk/google-vertex":
  30. case "@ai-sdk/google":
  31. return "google"
  32. case "@ai-sdk/gateway":
  33. return "gateway"
  34. case "@openrouter/ai-sdk-provider":
  35. return "openrouter"
  36. }
  37. return undefined
  38. }
  39. function normalizeMessages(
  40. msgs: ModelMessage[],
  41. model: Provider.Model,
  42. options: Record<string, unknown>,
  43. ): ModelMessage[] {
  44. // Anthropic rejects messages with empty content - filter out empty string messages
  45. // and remove empty text/reasoning parts from array content
  46. if (model.api.npm === "@ai-sdk/anthropic") {
  47. msgs = msgs
  48. .map((msg) => {
  49. if (typeof msg.content === "string") {
  50. if (msg.content === "") return undefined
  51. return msg
  52. }
  53. if (!Array.isArray(msg.content)) return msg
  54. const filtered = msg.content.filter((part) => {
  55. if (part.type === "text" || part.type === "reasoning") {
  56. return part.text !== ""
  57. }
  58. return true
  59. })
  60. if (filtered.length === 0) return undefined
  61. return { ...msg, content: filtered }
  62. })
  63. .filter((msg): msg is ModelMessage => msg !== undefined && msg.content !== "")
  64. }
  65. if (model.api.id.includes("claude")) {
  66. return msgs.map((msg) => {
  67. if ((msg.role === "assistant" || msg.role === "tool") && Array.isArray(msg.content)) {
  68. msg.content = msg.content.map((part) => {
  69. if ((part.type === "tool-call" || part.type === "tool-result") && "toolCallId" in part) {
  70. return {
  71. ...part,
  72. toolCallId: part.toolCallId.replace(/[^a-zA-Z0-9_-]/g, "_"),
  73. }
  74. }
  75. return part
  76. })
  77. }
  78. return msg
  79. })
  80. }
  81. if (
  82. model.providerID === "mistral" ||
  83. model.api.id.toLowerCase().includes("mistral") ||
  84. model.api.id.toLocaleLowerCase().includes("devstral")
  85. ) {
  86. const result: ModelMessage[] = []
  87. for (let i = 0; i < msgs.length; i++) {
  88. const msg = msgs[i]
  89. const nextMsg = msgs[i + 1]
  90. if ((msg.role === "assistant" || msg.role === "tool") && Array.isArray(msg.content)) {
  91. msg.content = msg.content.map((part) => {
  92. if ((part.type === "tool-call" || part.type === "tool-result") && "toolCallId" in part) {
  93. // Mistral requires alphanumeric tool call IDs with exactly 9 characters
  94. const normalizedId = part.toolCallId
  95. .replace(/[^a-zA-Z0-9]/g, "") // Remove non-alphanumeric characters
  96. .substring(0, 9) // Take first 9 characters
  97. .padEnd(9, "0") // Pad with zeros if less than 9 characters
  98. return {
  99. ...part,
  100. toolCallId: normalizedId,
  101. }
  102. }
  103. return part
  104. })
  105. }
  106. result.push(msg)
  107. // Fix message sequence: tool messages cannot be followed by user messages
  108. if (msg.role === "tool" && nextMsg?.role === "user") {
  109. result.push({
  110. role: "assistant",
  111. content: [
  112. {
  113. type: "text",
  114. text: "Done.",
  115. },
  116. ],
  117. })
  118. }
  119. }
  120. return result
  121. }
  122. if (typeof model.capabilities.interleaved === "object" && model.capabilities.interleaved.field) {
  123. const field = model.capabilities.interleaved.field
  124. return msgs.map((msg) => {
  125. if (msg.role === "assistant" && Array.isArray(msg.content)) {
  126. const reasoningParts = msg.content.filter((part: any) => part.type === "reasoning")
  127. const reasoningText = reasoningParts.map((part: any) => part.text).join("")
  128. // Filter out reasoning parts from content
  129. const filteredContent = msg.content.filter((part: any) => part.type !== "reasoning")
  130. // Include reasoning_content | reasoning_details directly on the message for all assistant messages
  131. if (reasoningText) {
  132. return {
  133. ...msg,
  134. content: filteredContent,
  135. providerOptions: {
  136. ...msg.providerOptions,
  137. openaiCompatible: {
  138. ...(msg.providerOptions as any)?.openaiCompatible,
  139. [field]: reasoningText,
  140. },
  141. },
  142. }
  143. }
  144. return {
  145. ...msg,
  146. content: filteredContent,
  147. }
  148. }
  149. return msg
  150. })
  151. }
  152. return msgs
  153. }
  154. function applyCaching(msgs: ModelMessage[], providerID: string): ModelMessage[] {
  155. const system = msgs.filter((msg) => msg.role === "system").slice(0, 2)
  156. const final = msgs.filter((msg) => msg.role !== "system").slice(-2)
  157. const providerOptions = {
  158. anthropic: {
  159. cacheControl: { type: "ephemeral" },
  160. },
  161. openrouter: {
  162. cacheControl: { type: "ephemeral" },
  163. },
  164. bedrock: {
  165. cachePoint: { type: "ephemeral" },
  166. },
  167. openaiCompatible: {
  168. cache_control: { type: "ephemeral" },
  169. },
  170. copilot: {
  171. copilot_cache_control: { type: "ephemeral" },
  172. },
  173. }
  174. for (const msg of unique([...system, ...final])) {
  175. const shouldUseContentOptions = providerID !== "anthropic" && Array.isArray(msg.content) && msg.content.length > 0
  176. if (shouldUseContentOptions) {
  177. const lastContent = msg.content[msg.content.length - 1]
  178. if (lastContent && typeof lastContent === "object") {
  179. lastContent.providerOptions = mergeDeep(lastContent.providerOptions ?? {}, providerOptions)
  180. continue
  181. }
  182. }
  183. msg.providerOptions = mergeDeep(msg.providerOptions ?? {}, providerOptions)
  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.id.includes("anthropic") ||
  227. model.id.includes("claude") ||
  228. model.api.npm === "@ai-sdk/anthropic"
  229. ) {
  230. msgs = applyCaching(msgs, model.providerID)
  231. }
  232. // Remap providerOptions keys from stored providerID to expected SDK key
  233. const key = sdkKey(model.api.npm)
  234. if (key && key !== model.providerID && model.api.npm !== "@ai-sdk/azure") {
  235. const remap = (opts: Record<string, any> | undefined) => {
  236. if (!opts) return opts
  237. if (!(model.providerID in opts)) return opts
  238. const result = { ...opts }
  239. result[key] = result[model.providerID]
  240. delete result[model.providerID]
  241. return result
  242. }
  243. msgs = msgs.map((msg) => {
  244. if (!Array.isArray(msg.content)) return { ...msg, providerOptions: remap(msg.providerOptions) }
  245. return {
  246. ...msg,
  247. providerOptions: remap(msg.providerOptions),
  248. content: msg.content.map((part) => ({ ...part, providerOptions: remap(part.providerOptions) })),
  249. } as typeof msg
  250. })
  251. }
  252. return msgs
  253. }
  254. export function temperature(model: Provider.Model) {
  255. const id = model.id.toLowerCase()
  256. if (id.includes("qwen")) return 0.55
  257. if (id.includes("claude")) return undefined
  258. if (id.includes("gemini")) return 1.0
  259. if (id.includes("glm-4.6")) return 1.0
  260. if (id.includes("glm-4.7")) return 1.0
  261. if (id.includes("minimax-m2")) return 1.0
  262. if (id.includes("kimi-k2")) {
  263. // kimi-k2-thinking & kimi-k2.5 && kimi-k2p5
  264. if (id.includes("thinking") || id.includes("k2.") || id.includes("k2p")) {
  265. return 1.0
  266. }
  267. return 0.6
  268. }
  269. return undefined
  270. }
  271. export function topP(model: Provider.Model) {
  272. const id = model.id.toLowerCase()
  273. if (id.includes("qwen")) return 1
  274. if (id.includes("minimax-m2") || id.includes("kimi-k2.5") || id.includes("kimi-k2p5") || id.includes("gemini")) {
  275. return 0.95
  276. }
  277. return undefined
  278. }
  279. export function topK(model: Provider.Model) {
  280. const id = model.id.toLowerCase()
  281. if (id.includes("minimax-m2")) {
  282. if (id.includes("m2.1")) return 40
  283. return 20
  284. }
  285. if (id.includes("gemini")) return 64
  286. return undefined
  287. }
  288. const WIDELY_SUPPORTED_EFFORTS = ["low", "medium", "high"]
  289. const OPENAI_EFFORTS = ["none", "minimal", ...WIDELY_SUPPORTED_EFFORTS, "xhigh"]
  290. export function variants(model: Provider.Model): Record<string, Record<string, any>> {
  291. if (!model.capabilities.reasoning) return {}
  292. const id = model.id.toLowerCase()
  293. if (
  294. id.includes("deepseek") ||
  295. id.includes("minimax") ||
  296. id.includes("glm") ||
  297. id.includes("mistral") ||
  298. id.includes("kimi")
  299. )
  300. return {}
  301. // see: https://docs.x.ai/docs/guides/reasoning#control-how-hard-the-model-thinks
  302. if (id.includes("grok") && id.includes("grok-3-mini")) {
  303. if (model.api.npm === "@openrouter/ai-sdk-provider") {
  304. return {
  305. low: { reasoning: { effort: "low" } },
  306. high: { reasoning: { effort: "high" } },
  307. }
  308. }
  309. return {
  310. low: { reasoningEffort: "low" },
  311. high: { reasoningEffort: "high" },
  312. }
  313. }
  314. if (id.includes("grok")) return {}
  315. switch (model.api.npm) {
  316. case "@openrouter/ai-sdk-provider":
  317. if (!model.id.includes("gpt") && !model.id.includes("gemini-3")) return {}
  318. return Object.fromEntries(OPENAI_EFFORTS.map((effort) => [effort, { reasoning: { effort } }]))
  319. // TODO: YOU CANNOT SET max_tokens if this is set!!!
  320. case "@ai-sdk/gateway":
  321. return Object.fromEntries(OPENAI_EFFORTS.map((effort) => [effort, { reasoningEffort: effort }]))
  322. case "@ai-sdk/github-copilot":
  323. if (model.id.includes("gemini")) {
  324. // currently github copilot only returns thinking
  325. return {}
  326. }
  327. if (model.id.includes("claude")) {
  328. return {
  329. thinking: { thinking_budget: 4000 },
  330. }
  331. }
  332. const copilotEfforts = iife(() => {
  333. if (id.includes("5.1-codex-max") || id.includes("5.2")) return [...WIDELY_SUPPORTED_EFFORTS, "xhigh"]
  334. return WIDELY_SUPPORTED_EFFORTS
  335. })
  336. return Object.fromEntries(
  337. copilotEfforts.map((effort) => [
  338. effort,
  339. {
  340. reasoningEffort: effort,
  341. reasoningSummary: "auto",
  342. include: ["reasoning.encrypted_content"],
  343. },
  344. ]),
  345. )
  346. case "@ai-sdk/cerebras":
  347. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/cerebras
  348. case "@ai-sdk/togetherai":
  349. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/togetherai
  350. case "@ai-sdk/xai":
  351. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/xai
  352. case "@ai-sdk/deepinfra":
  353. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/deepinfra
  354. case "@ai-sdk/openai-compatible":
  355. // When using openai-compatible SDK with Claude/Anthropic models,
  356. // we must use snake_case (budget_tokens) as the SDK doesn't convert parameter names
  357. // and the OpenAI-compatible API spec uses snake_case
  358. if (
  359. model.providerID === "anthropic" ||
  360. model.api.id.includes("anthropic") ||
  361. model.api.id.includes("claude") ||
  362. model.id.includes("anthropic") ||
  363. model.id.includes("claude")
  364. ) {
  365. return {
  366. high: {
  367. thinking: {
  368. type: "enabled",
  369. budget_tokens: 16000,
  370. },
  371. },
  372. max: {
  373. thinking: {
  374. type: "enabled",
  375. budget_tokens: 31999,
  376. },
  377. },
  378. }
  379. }
  380. return Object.fromEntries(WIDELY_SUPPORTED_EFFORTS.map((effort) => [effort, { reasoningEffort: effort }]))
  381. case "@ai-sdk/azure":
  382. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/azure
  383. if (id === "o1-mini") return {}
  384. const azureEfforts = ["low", "medium", "high"]
  385. if (id.includes("gpt-5-") || id === "gpt-5") {
  386. azureEfforts.unshift("minimal")
  387. }
  388. return Object.fromEntries(
  389. azureEfforts.map((effort) => [
  390. effort,
  391. {
  392. reasoningEffort: effort,
  393. reasoningSummary: "auto",
  394. include: ["reasoning.encrypted_content"],
  395. },
  396. ]),
  397. )
  398. case "@ai-sdk/openai":
  399. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/openai
  400. if (id === "gpt-5-pro") return {}
  401. const openaiEfforts = iife(() => {
  402. if (id.includes("codex")) {
  403. if (id.includes("5.2")) return [...WIDELY_SUPPORTED_EFFORTS, "xhigh"]
  404. return WIDELY_SUPPORTED_EFFORTS
  405. }
  406. const arr = [...WIDELY_SUPPORTED_EFFORTS]
  407. if (id.includes("gpt-5-") || id === "gpt-5") {
  408. arr.unshift("minimal")
  409. }
  410. if (model.release_date >= "2025-11-13") {
  411. arr.unshift("none")
  412. }
  413. if (model.release_date >= "2025-12-04") {
  414. arr.push("xhigh")
  415. }
  416. return arr
  417. })
  418. return Object.fromEntries(
  419. openaiEfforts.map((effort) => [
  420. effort,
  421. {
  422. reasoningEffort: effort,
  423. reasoningSummary: "auto",
  424. include: ["reasoning.encrypted_content"],
  425. },
  426. ]),
  427. )
  428. case "@ai-sdk/anthropic":
  429. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/anthropic
  430. case "@ai-sdk/google-vertex/anthropic":
  431. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/google-vertex#anthropic-provider
  432. return {
  433. high: {
  434. thinking: {
  435. type: "enabled",
  436. budgetTokens: Math.min(16_000, Math.floor(model.limit.output / 2 - 1)),
  437. },
  438. },
  439. max: {
  440. thinking: {
  441. type: "enabled",
  442. budgetTokens: Math.min(31_999, model.limit.output - 1),
  443. },
  444. },
  445. }
  446. case "@ai-sdk/amazon-bedrock":
  447. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/amazon-bedrock
  448. // For Anthropic models on Bedrock, use reasoningConfig with budgetTokens
  449. if (model.api.id.includes("anthropic")) {
  450. return {
  451. high: {
  452. reasoningConfig: {
  453. type: "enabled",
  454. budgetTokens: 16000,
  455. },
  456. },
  457. max: {
  458. reasoningConfig: {
  459. type: "enabled",
  460. budgetTokens: 31999,
  461. },
  462. },
  463. }
  464. }
  465. // For Amazon Nova models, use reasoningConfig with maxReasoningEffort
  466. return Object.fromEntries(
  467. WIDELY_SUPPORTED_EFFORTS.map((effort) => [
  468. effort,
  469. {
  470. reasoningConfig: {
  471. type: "enabled",
  472. maxReasoningEffort: effort,
  473. },
  474. },
  475. ]),
  476. )
  477. case "@ai-sdk/google-vertex":
  478. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/google-vertex
  479. case "@ai-sdk/google":
  480. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai
  481. if (id.includes("2.5")) {
  482. return {
  483. high: {
  484. thinkingConfig: {
  485. includeThoughts: true,
  486. thinkingBudget: 16000,
  487. },
  488. },
  489. max: {
  490. thinkingConfig: {
  491. includeThoughts: true,
  492. thinkingBudget: 24576,
  493. },
  494. },
  495. }
  496. }
  497. return Object.fromEntries(
  498. ["low", "high"].map((effort) => [
  499. effort,
  500. {
  501. includeThoughts: true,
  502. thinkingLevel: effort,
  503. },
  504. ]),
  505. )
  506. case "@ai-sdk/mistral":
  507. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/mistral
  508. return {}
  509. case "@ai-sdk/cohere":
  510. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/cohere
  511. return {}
  512. case "@ai-sdk/groq":
  513. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/groq
  514. const groqEffort = ["none", ...WIDELY_SUPPORTED_EFFORTS]
  515. return Object.fromEntries(
  516. groqEffort.map((effort) => [
  517. effort,
  518. {
  519. includeThoughts: true,
  520. thinkingLevel: effort,
  521. },
  522. ]),
  523. )
  524. case "@ai-sdk/perplexity":
  525. // https://v5.ai-sdk.dev/providers/ai-sdk-providers/perplexity
  526. return {}
  527. }
  528. return {}
  529. }
  530. export function options(input: {
  531. model: Provider.Model
  532. sessionID: string
  533. providerOptions?: Record<string, any>
  534. }): Record<string, any> {
  535. const result: Record<string, any> = {}
  536. // openai and providers using openai package should set store to false by default.
  537. if (
  538. input.model.providerID === "openai" ||
  539. input.model.api.npm === "@ai-sdk/openai" ||
  540. input.model.api.npm === "@ai-sdk/github-copilot"
  541. ) {
  542. result["store"] = false
  543. }
  544. if (input.model.api.npm === "@openrouter/ai-sdk-provider") {
  545. result["usage"] = {
  546. include: true,
  547. }
  548. if (input.model.api.id.includes("gemini-3")) {
  549. result["reasoning"] = { effort: "high" }
  550. }
  551. }
  552. if (
  553. input.model.providerID === "baseten" ||
  554. (input.model.providerID === "opencode" && ["kimi-k2-thinking", "glm-4.6"].includes(input.model.api.id))
  555. ) {
  556. result["chat_template_args"] = { enable_thinking: true }
  557. }
  558. if (["zai", "zhipuai"].includes(input.model.providerID) && input.model.api.npm === "@ai-sdk/openai-compatible") {
  559. result["thinking"] = {
  560. type: "enabled",
  561. clear_thinking: false,
  562. }
  563. }
  564. if (input.model.providerID === "openai" || input.providerOptions?.setCacheKey) {
  565. result["promptCacheKey"] = input.sessionID
  566. }
  567. if (input.model.api.npm === "@ai-sdk/google" || input.model.api.npm === "@ai-sdk/google-vertex") {
  568. result["thinkingConfig"] = {
  569. includeThoughts: true,
  570. }
  571. if (input.model.api.id.includes("gemini-3")) {
  572. result["thinkingConfig"]["thinkingLevel"] = "high"
  573. }
  574. }
  575. if (input.model.api.id.includes("gpt-5") && !input.model.api.id.includes("gpt-5-chat")) {
  576. if (!input.model.api.id.includes("gpt-5-pro")) {
  577. result["reasoningEffort"] = "medium"
  578. }
  579. // Only set textVerbosity for non-chat gpt-5.x models
  580. // Chat models (e.g. gpt-5.2-chat-latest) only support "medium" verbosity
  581. if (
  582. input.model.api.id.includes("gpt-5.") &&
  583. !input.model.api.id.includes("codex") &&
  584. !input.model.api.id.includes("-chat") &&
  585. input.model.providerID !== "azure"
  586. ) {
  587. result["textVerbosity"] = "low"
  588. }
  589. if (input.model.providerID.startsWith("opencode")) {
  590. result["promptCacheKey"] = input.sessionID
  591. result["include"] = ["reasoning.encrypted_content"]
  592. result["reasoningSummary"] = "auto"
  593. }
  594. }
  595. if (input.model.providerID === "venice") {
  596. result["promptCacheKey"] = input.sessionID
  597. }
  598. return result
  599. }
  600. export function smallOptions(model: Provider.Model) {
  601. if (model.providerID === "openai" || model.api.id.includes("gpt-5")) {
  602. if (model.api.id.includes("5.")) {
  603. return { reasoningEffort: "low" }
  604. }
  605. return { reasoningEffort: "minimal" }
  606. }
  607. if (model.providerID === "google") {
  608. // gemini-3 uses thinkingLevel, gemini-2.5 uses thinkingBudget
  609. if (model.api.id.includes("gemini-3")) {
  610. return { thinkingConfig: { thinkingLevel: "minimal" } }
  611. }
  612. return { thinkingConfig: { thinkingBudget: 0 } }
  613. }
  614. if (model.providerID === "openrouter") {
  615. if (model.api.id.includes("google")) {
  616. return { reasoning: { enabled: false } }
  617. }
  618. return { reasoningEffort: "minimal" }
  619. }
  620. return {}
  621. }
  622. export function providerOptions(model: Provider.Model, options: { [x: string]: any }) {
  623. const key = sdkKey(model.api.npm) ?? model.providerID
  624. return { [key]: options }
  625. }
  626. export function maxOutputTokens(
  627. npm: string,
  628. options: Record<string, any>,
  629. modelLimit: number,
  630. globalLimit: number,
  631. ): number {
  632. const modelCap = modelLimit || globalLimit
  633. const standardLimit = Math.min(modelCap, globalLimit)
  634. // Handle thinking mode for @ai-sdk/anthropic, @ai-sdk/google-vertex/anthropic (budgetTokens)
  635. // and @ai-sdk/openai-compatible with Claude (budget_tokens)
  636. if (
  637. npm === "@ai-sdk/anthropic" ||
  638. npm === "@ai-sdk/google-vertex/anthropic" ||
  639. npm === "@ai-sdk/openai-compatible"
  640. ) {
  641. const thinking = options?.["thinking"]
  642. // Support both camelCase (for @ai-sdk/anthropic) and snake_case (for openai-compatible)
  643. const budgetTokens =
  644. typeof thinking?.["budgetTokens"] === "number"
  645. ? thinking["budgetTokens"]
  646. : typeof thinking?.["budget_tokens"] === "number"
  647. ? thinking["budget_tokens"]
  648. : 0
  649. const enabled = thinking?.["type"] === "enabled"
  650. if (enabled && budgetTokens > 0) {
  651. // Return text tokens so that text + thinking <= model cap, preferring 32k text when possible.
  652. if (budgetTokens + standardLimit <= modelCap) {
  653. return standardLimit
  654. }
  655. return modelCap - budgetTokens
  656. }
  657. }
  658. return standardLimit
  659. }
  660. export function schema(model: Provider.Model, schema: JSONSchema.BaseSchema) {
  661. /*
  662. if (["openai", "azure"].includes(providerID)) {
  663. if (schema.type === "object" && schema.properties) {
  664. for (const [key, value] of Object.entries(schema.properties)) {
  665. if (schema.required?.includes(key)) continue
  666. schema.properties[key] = {
  667. anyOf: [
  668. value as JSONSchema.JSONSchema,
  669. {
  670. type: "null",
  671. },
  672. ],
  673. }
  674. }
  675. }
  676. }
  677. */
  678. // Convert integer enums to string enums for Google/Gemini
  679. if (model.providerID === "google" || model.api.id.includes("gemini")) {
  680. const sanitizeGemini = (obj: any): any => {
  681. if (obj === null || typeof obj !== "object") {
  682. return obj
  683. }
  684. if (Array.isArray(obj)) {
  685. return obj.map(sanitizeGemini)
  686. }
  687. const result: any = {}
  688. for (const [key, value] of Object.entries(obj)) {
  689. if (key === "enum" && Array.isArray(value)) {
  690. // Convert all enum values to strings
  691. result[key] = value.map((v) => String(v))
  692. // If we have integer type with enum, change type to string
  693. if (result.type === "integer" || result.type === "number") {
  694. result.type = "string"
  695. }
  696. } else if (typeof value === "object" && value !== null) {
  697. result[key] = sanitizeGemini(value)
  698. } else {
  699. result[key] = value
  700. }
  701. }
  702. // Filter required array to only include fields that exist in properties
  703. if (result.type === "object" && result.properties && Array.isArray(result.required)) {
  704. result.required = result.required.filter((field: any) => field in result.properties)
  705. }
  706. if (result.type === "array" && result.items == null) {
  707. result.items = {}
  708. }
  709. return result
  710. }
  711. schema = sanitizeGemini(schema)
  712. }
  713. return schema
  714. }
  715. export function error(providerID: string, error: APICallError) {
  716. let message = error.message
  717. if (providerID.includes("github-copilot") && error.statusCode === 403) {
  718. return "Please reauthenticate with the copilot provider to ensure your credentials work properly with OpenCode."
  719. }
  720. if (providerID.includes("github-copilot") && message.includes("The requested model is not supported")) {
  721. return (
  722. message +
  723. "\n\nMake sure the model is enabled in your copilot settings: https://github.com/settings/copilot/features"
  724. )
  725. }
  726. return message
  727. }
  728. }