transform.ts 24 KB

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