transform.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import type { ModelMessage } from "ai"
  2. import { unique } from "remeda"
  3. import type { JSONSchema } from "zod/v4/core"
  4. export namespace ProviderTransform {
  5. function normalizeMessages(msgs: ModelMessage[], providerID: string, modelID: string): ModelMessage[] {
  6. if (modelID.includes("claude")) {
  7. return msgs.map((msg) => {
  8. if ((msg.role === "assistant" || msg.role === "tool") && Array.isArray(msg.content)) {
  9. msg.content = msg.content.map((part) => {
  10. if ((part.type === "tool-call" || part.type === "tool-result") && "toolCallId" in part) {
  11. return {
  12. ...part,
  13. toolCallId: part.toolCallId.replace(/[^a-zA-Z0-9_-]/g, "_"),
  14. }
  15. }
  16. return part
  17. })
  18. }
  19. return msg
  20. })
  21. }
  22. if (providerID === "mistral" || modelID.toLowerCase().includes("mistral")) {
  23. const result: ModelMessage[] = []
  24. for (let i = 0; i < msgs.length; i++) {
  25. const msg = msgs[i]
  26. const nextMsg = msgs[i + 1]
  27. if ((msg.role === "assistant" || msg.role === "tool") && Array.isArray(msg.content)) {
  28. msg.content = msg.content.map((part) => {
  29. if ((part.type === "tool-call" || part.type === "tool-result") && "toolCallId" in part) {
  30. // Mistral requires alphanumeric tool call IDs with exactly 9 characters
  31. const normalizedId = part.toolCallId
  32. .replace(/[^a-zA-Z0-9]/g, "") // Remove non-alphanumeric characters
  33. .substring(0, 9) // Take first 9 characters
  34. .padEnd(9, "0") // Pad with zeros if less than 9 characters
  35. return {
  36. ...part,
  37. toolCallId: normalizedId,
  38. }
  39. }
  40. return part
  41. })
  42. }
  43. result.push(msg)
  44. // Fix message sequence: tool messages cannot be followed by user messages
  45. if (msg.role === "tool" && nextMsg?.role === "user") {
  46. result.push({
  47. role: "assistant",
  48. content: [
  49. {
  50. type: "text",
  51. text: "Done.",
  52. },
  53. ],
  54. })
  55. }
  56. }
  57. return result
  58. }
  59. return msgs
  60. }
  61. function applyCaching(msgs: ModelMessage[], providerID: string): ModelMessage[] {
  62. const system = msgs.filter((msg) => msg.role === "system").slice(0, 2)
  63. const final = msgs.filter((msg) => msg.role !== "system").slice(-2)
  64. const providerOptions = {
  65. anthropic: {
  66. cacheControl: { type: "ephemeral" },
  67. },
  68. openrouter: {
  69. cache_control: { type: "ephemeral" },
  70. },
  71. bedrock: {
  72. cachePoint: { type: "ephemeral" },
  73. },
  74. openaiCompatible: {
  75. cache_control: { type: "ephemeral" },
  76. },
  77. }
  78. for (const msg of unique([...system, ...final])) {
  79. const shouldUseContentOptions = providerID !== "anthropic" && Array.isArray(msg.content) && msg.content.length > 0
  80. if (shouldUseContentOptions) {
  81. const lastContent = msg.content[msg.content.length - 1]
  82. if (lastContent && typeof lastContent === "object") {
  83. lastContent.providerOptions = {
  84. ...lastContent.providerOptions,
  85. ...providerOptions,
  86. }
  87. continue
  88. }
  89. }
  90. msg.providerOptions = {
  91. ...msg.providerOptions,
  92. ...providerOptions,
  93. }
  94. }
  95. return msgs
  96. }
  97. export function message(msgs: ModelMessage[], providerID: string, modelID: string) {
  98. msgs = normalizeMessages(msgs, providerID, modelID)
  99. if (providerID === "anthropic" || modelID.includes("anthropic") || modelID.includes("claude")) {
  100. msgs = applyCaching(msgs, providerID)
  101. }
  102. return msgs
  103. }
  104. export function temperature(_providerID: string, modelID: string) {
  105. if (modelID.toLowerCase().includes("qwen")) return 0.55
  106. if (modelID.toLowerCase().includes("claude")) return undefined
  107. if (modelID.toLowerCase().includes("gemini-3-pro")) return 1.0
  108. return 0
  109. }
  110. export function topP(_providerID: string, modelID: string) {
  111. if (modelID.toLowerCase().includes("qwen")) return 1
  112. return undefined
  113. }
  114. export function options(
  115. providerID: string,
  116. modelID: string,
  117. npm: string,
  118. sessionID: string,
  119. ): Record<string, any> | undefined {
  120. const result: Record<string, any> = {}
  121. // switch to providerID later, for now use this
  122. if (npm === "@openrouter/ai-sdk-provider") {
  123. result["usage"] = {
  124. include: true,
  125. }
  126. }
  127. if (providerID === "openai") {
  128. result["promptCacheKey"] = sessionID
  129. }
  130. if (providerID === "google") {
  131. result["thinkingConfig"] = {
  132. includeThoughts: true,
  133. }
  134. }
  135. if (modelID.includes("gpt-5") && !modelID.includes("gpt-5-chat")) {
  136. if (modelID.includes("codex")) {
  137. result["store"] = false
  138. }
  139. if (!modelID.includes("codex") && !modelID.includes("gpt-5-pro")) {
  140. result["reasoningEffort"] = "medium"
  141. }
  142. if (modelID.endsWith("gpt-5.1") && providerID !== "azure") {
  143. result["textVerbosity"] = "low"
  144. }
  145. if (providerID === "opencode") {
  146. result["promptCacheKey"] = sessionID
  147. result["include"] = ["reasoning.encrypted_content"]
  148. result["reasoningSummary"] = "auto"
  149. }
  150. }
  151. return result
  152. }
  153. export function providerOptions(npm: string | undefined, providerID: string, options: { [x: string]: any }) {
  154. switch (npm) {
  155. case "@ai-sdk/openai":
  156. case "@ai-sdk/azure":
  157. return {
  158. ["openai" as string]: options,
  159. }
  160. case "@ai-sdk/amazon-bedrock":
  161. return {
  162. ["bedrock" as string]: options,
  163. }
  164. case "@ai-sdk/anthropic":
  165. return {
  166. ["anthropic" as string]: options,
  167. }
  168. case "@ai-sdk/google":
  169. return {
  170. ["google" as string]: options,
  171. }
  172. case "@ai-sdk/gateway":
  173. return {
  174. ["gateway" as string]: options,
  175. }
  176. case "@openrouter/ai-sdk-provider":
  177. return {
  178. ["openrouter" as string]: options,
  179. }
  180. default:
  181. return {
  182. [providerID]: options,
  183. }
  184. }
  185. }
  186. export function maxOutputTokens(
  187. npm: string,
  188. options: Record<string, any>,
  189. modelLimit: number,
  190. globalLimit: number,
  191. ): number {
  192. const modelCap = modelLimit || globalLimit
  193. const standardLimit = Math.min(modelCap, globalLimit)
  194. if (npm === "@ai-sdk/anthropic") {
  195. const thinking = options?.["thinking"]
  196. const budgetTokens = typeof thinking?.["budgetTokens"] === "number" ? thinking["budgetTokens"] : 0
  197. const enabled = thinking?.["type"] === "enabled"
  198. if (enabled && budgetTokens > 0) {
  199. // Return text tokens so that text + thinking <= model cap, preferring 32k text when possible.
  200. if (budgetTokens + standardLimit <= modelCap) {
  201. return standardLimit
  202. }
  203. return modelCap - budgetTokens
  204. }
  205. }
  206. return standardLimit
  207. }
  208. export function schema(_providerID: string, _modelID: string, schema: JSONSchema.BaseSchema) {
  209. /*
  210. if (["openai", "azure"].includes(providerID)) {
  211. if (schema.type === "object" && schema.properties) {
  212. for (const [key, value] of Object.entries(schema.properties)) {
  213. if (schema.required?.includes(key)) continue
  214. schema.properties[key] = {
  215. anyOf: [
  216. value as JSONSchema.JSONSchema,
  217. {
  218. type: "null",
  219. },
  220. ],
  221. }
  222. }
  223. }
  224. }
  225. if (providerID === "google") {
  226. }
  227. */
  228. return schema
  229. }
  230. }