{"record":{"id":"8c981a10b523541c","repo":"mastra-ai/mastra","slug":"invalid-model-provided-model-must-be-a-mastralang","errorCode":null,"errorMessage":"Invalid model provided. Model must be a MastraLanguageModel instance (e.g., openai(\"gpt-4\"), anthropic(\"claude-3-5-sonnet\"), etc.)","messagePattern":"Invalid model provided\\. Model must be a MastraLanguageModel instance \\(e\\.g\\., openai\\(\"gpt-4\"\\), anthropic\\(\"claude-3-5-sonnet\"\\), etc\\.\\)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/agent-builder/src/utils.ts","lineNumber":683,"sourceCode":"// Helper function to resolve model from request context with AI SDK version detection\nexport const resolveModel = async ({\n  requestContext,\n  defaultModel = 'openai/gpt-4.1',\n  projectPath,\n}: {\n  requestContext: RequestContext;\n  defaultModel?: MastraLanguageModel | MastraLegacyLanguageModel | string;\n  projectPath?: string;\n}): Promise<MastraLanguageModel | MastraLegacyLanguageModel> => {\n  // First try to get model from request context\n  const modelFromContext = requestContext.get('model');\n  if (modelFromContext) {\n    console.info('Using model from request context');\n    // Type check to ensure it's a MastraLanguageModel\n    if (isValidMastraLanguageModel(modelFromContext)) {\n      return modelFromContext;\n    }\n    throw new Error(\n      'Invalid model provided. Model must be a MastraLanguageModel instance (e.g., openai(\"gpt-4\"), anthropic(\"claude-3-5-sonnet\"), etc.)',\n    );\n  }\n\n  // Check for selected model info in request context\n  const selectedModel = requestContext.get('selectedModel') as { provider: string; modelId: string } | undefined;\n  if (selectedModel?.provider && selectedModel?.modelId && projectPath) {\n    console.info(`Resolving selected model: ${selectedModel.provider}/${selectedModel.modelId}`);\n\n    // Detect AI SDK version from project\n    const version = await detectAISDKVersion(projectPath);\n\n    // Create model instance with detected version\n    const modelInstance = await createModelInstance(selectedModel.provider, selectedModel.modelId, version);\n    if (modelInstance) {\n      // Store resolved model back in context for other steps to use\n      requestContext.set('model', modelInstance);\n      return modelInstance;","sourceCodeStart":665,"sourceCodeEnd":701,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/agent-builder/src/utils.ts#L665-L701","documentation":"When resolving the model for an agent-builder request, if a model is present in the request context but fails isValidMastraLanguageModel, this error is thrown: 'Invalid model provided. Model must be a MastraLanguageModel instance...'. It guards against strings, plain objects, or other non-language-model values being smuggled in via request context instead of a real provider model instance.","triggerScenarios":"Setting requestContext 'model' (or the context key the builder reads) to a string like 'openai/gpt-4', a serializable model descriptor object, or any value that is not produced by a provider factory (openai('gpt-4'), anthropic('claude-3-5-sonnet'), etc.).","commonSituations":"Passing model names from API payloads/UI directly into context instead of instantiating them with the provider SDK; JSON-deserialized model objects losing their class identity; config files storing model ids as strings; version changes in AI SDK model types breaking the validator.","solutions":["Instantiate the model with a provider factory before putting it in context, e.g. openai('gpt-4') from @ai-sdk/openai","If the model arrives as a string/id, resolve it server-side: a registry map from {provider, modelId} to a constructed MastraLanguageModel","Do not serialize/deserialize model objects across boundaries (HTTP, JSON) — reconstruct them from identifiers on the server","Check that the AI SDK provider package versions are compatible so isValidMastraLanguageModel recognizes the instance"],"exampleFix":"// before\nrequestContext.set('model', 'openai/gpt-4');\n\n// after\nimport { openai } from '@ai-sdk/openai';\nrequestContext.set('model', openai('gpt-4'));","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"function isMastraLanguageModel(m: unknown): m is MastraLanguageModel {\n  return (\n    !!m &&\n    typeof m === 'object' &&\n    typeof (m as any).doGenerate === 'function' &&\n    typeof (m as any).doStream === 'function'\n  );\n}\n// usage\nif (!isMastraLanguageModel(candidate)) throw new Error('Provide openai(\"gpt-4\")-style instance, not a string');","tryCatchPattern":null,"preventionTips":["Never store model ids as strings in request context; construct with provider factories","Resolve string model identifiers server-side via a registry before use","Avoid serializing model instances across HTTP/JSON boundaries","Keep AI SDK provider versions aligned with the validator"],"tags":["typescript","type-guard","configuration"],"backgroundTag":"invalid-model-instance","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}