Skip to content
freellm.site

OpenRouter Agent Migration: SDK to @openrouter/agent

How to migrate from @openrouter/sdk to @openrouter/agent, plus moving an existing OpenAI, Vercel AI SDK or Claude agent onto OpenRouter.

By
openrouteragent-sdkmigrationtypescriptai-agentsllm-api

“OpenRouter agent migration” can mean two things, and each has a different fix. If your code imports callModel, tool(), or stop conditions from @openrouter/sdk, those agent pieces moved to a standalone package: install @openrouter/agent and change the import source. If you mean moving an existing agent (OpenAI SDK, Vercel AI SDK, Mastra, Claude Agent SDK) onto OpenRouter, you swap the base URL and model slugs, and adopting the Agent SDK is an optional second step.

OpenRouter Agent Migration: SDK to @openrouter/agent

This guide covers both, with the exact import mapping from OpenRouter’s own migration skill and docs, plus the env-var route for agent frameworks you don’t want to rewrite.

Which migration are you doing?

Your situationWhat changesEffort
You use @openrouter/sdk for callModel / tool() / stop conditionsInstall @openrouter/agent, change import pathsMinutes; the API is identical
You use @openrouter/sdk for models, credits, API keysNothing. Keep itNone
You use the OpenAI SDK against another providerRetarget baseURL to https://openrouter.ai/api/v1, swap model IDsSmall
You use Vercel AI SDKSwap the provider for @openrouter/ai-sdk-providerSmall
You use the Claude Agent SDK / Anthropic Agent SDKSet ANTHROPIC_BASE_URL + ANTHROPIC_AUTH_TOKEN, no code changeConfig only
You hand-rolled a tool loop and want it managedMove the execution boundary to @openrouter/agentMedium

Find your row and skip the rest. Most readers are in row one.

Case 1: @openrouter/sdk → @openrouter/agent

Per the agent migration skill, the agent functionality (callModel, tool(), stop conditions, format converters, streaming helpers) has moved out of @openrouter/sdk into the standalone @openrouter/agent package. The new package ships its own OpenRouter client class, so agent-only projects don’t need @openrouter/sdk as a direct dependency.

Step 1: install

npm install @openrouter/agent

If you only used the SDK for agent features, you can drop it:

npm uninstall @openrouter/sdk
npm install @openrouter/agent

The Agent SDK overview notes that @openrouter/agent depends on @openrouter/sdk and installs it for you. If you also call REST endpoints directly, keep @openrouter/sdk in your own package.json so you control which version resolves.

Step 2: change the imports

The client class and the client.callModel() pattern haven’t changed. Only the import source moves:

- import OpenRouter from '@openrouter/sdk';
+ import { OpenRouter } from '@openrouter/agent';

The export shape changed too. The old package exported the client as a default export and the new one uses a named export. This is the most common compile error in the migration.

Helpers now live on subpaths:

Old importNew import
import OpenRouter from '@openrouter/sdk'import { OpenRouter } from '@openrouter/agent'
import { tool } from '@openrouter/sdk'import { tool } from '@openrouter/agent/tool'
import { stepCountIs } from '@openrouter/sdk'import { stepCountIs } from '@openrouter/agent/stop-conditions'
import { hasToolCall } from '@openrouter/sdk'import { hasToolCall } from '@openrouter/agent/stop-conditions'

The barrel import @openrouter/agent re-exports everything, so import { OpenRouter, tool, stepCountIs } from '@openrouter/agent' also works if you’d rather have one line than separate subpaths.

Step 3: verify a runnable example

Here’s a complete agent after migration. Only the import block differs from the old version:

import { OpenRouter } from '@openrouter/agent';
import { tool } from '@openrouter/agent/tool';
import { stepCountIs, hasToolCall } from '@openrouter/agent/stop-conditions';
import { z } from 'zod';

const client = new OpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY,
});

const searchTool = tool({
  name: 'web_search',
  description: 'Search the web',
  inputSchema: z.object({ query: z.string() }),
  outputSchema: z.object({ results: z.array(z.string()) }),
  execute: async ({ query }) => {
    return { results: ['Result 1', 'Result 2'] };
  },
});

const finishTool = tool({
  name: 'finish',
  description: 'Complete the task',
  inputSchema: z.object({ answer: z.string() }),
  execute: async ({ answer }) => ({ answer }),
});

const result = client.callModel({
  model: 'openai/gpt-5-nano',
  instructions: 'You are a research assistant.',
  input: 'What are the latest AI developments?',
  tools: [searchTool, finishTool],
  stopWhen: [stepCountIs(10), hasToolCall('finish')],
});

console.log(await result.getText());

If this runs and your tool fires, the migration is done.

Subpaths you’ll use most

@openrouter/agent exposes separate subpaths. These are the ones you’re most likely to touch during a migration:

SubpathWhat it exports
@openrouter/agent/clientthe OpenRouter class
@openrouter/agent/toolthe tool() factory
@openrouter/agent/stop-conditionsstepCountIs, hasToolCall, maxCost, maxTokensUsed, finishReasonIs
@openrouter/agent/anthropic-compatfromClaudeMessages, toClaudeMessage
@openrouter/agent/chat-compatfromChatMessages, toChatMessage
@openrouter/agent/conversation-statecreateInitialState, updateState, appendToMessages

If your agent stores messages in Claude Messages or OpenAI Chat Completions format, the compat converters let you keep those shapes and convert at the boundary, so you don’t have to rewrite your history store.

Case 2: mixed projects, keep both packages

If you call platform endpoints (model list, credits, API keys, analytics) and run agent loops, the docs recommend installing both packages side by side and aliasing one:

import OpenRouter from '@openrouter/sdk';               // platform APIs
import { OpenRouter as Agent } from '@openrouter/agent'; // agent loops
import { tool } from '@openrouter/agent/tool';
import { stepCountIs } from '@openrouter/agent/stop-conditions';

const sdkClient = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY });
const models = await sdkClient.models.list();
const credits = await sdkClient.credits.getCredits();

const agent = new Agent({ apiKey: process.env.OPENROUTER_API_KEY });
const result = agent.callModel({
  model: 'openai/gpt-5-nano',
  input: 'Hello!',
  tools: [searchTool],
  stopWhen: stepCountIs(5),
});

The docs’ rule of thumb: platform APIs go through @openrouter/sdk; callModel, tool(), stop conditions, format converters and model-runner abstractions go through @openrouter/agent.

Case 3: migrating an agent onto OpenRouter

Here you have a working agent on another provider and want OpenRouter’s routing in front of it. OpenRouter publishes a one-prompt migration cookbook that you paste into your coding agent; it lists your integration points before editing anything. The paths it uses:

  • OpenAI SDK (TS or Python): retarget baseURL / base_url to https://openrouter.ai/api/v1 and swap model IDs. This is ordinary OpenAI-compatible API work, the same as for any gateway.
  • Vercel AI SDK: swap the provider for @openrouter/ai-sdk-provider and keep generateText, streamText, tools, and your UI stream protocol as they are.
  • Claude Agent SDK / Anthropic Agent SDK: leave the agent loop alone and change the configuration:
export ANTHROPIC_BASE_URL=https://openrouter.ai/api
export ANTHROPIC_AUTH_TOKEN=$OPENROUTER_API_KEY
export ANTHROPIC_API_KEY=

The docs say to set ANTHROPIC_API_KEY explicitly empty, as in the third line, because otherwise a stale key can take precedence. Keep your allowed tools, permission prompts, working directory, and model-override env vars, and replace Claude model values with OpenRouter model slugs where the runtime supports them. It’s the same trick behind running a free LLM API in Cursor or Claude Code.

  • Stack not listed? Do a provider-agnostic migration: find where your code calls the model, keep your framework and protocol, and change only the HTTP client, model IDs, auth env vars, and response parsing.

The cookbook treats the Agent SDK step as opt-in. It recommends moving server-side execution to @openrouter/agent only when it finds tool loops or multi-turn orchestration, and it asks before changing code. If you decline, it takes the least disruptive provider path and records the decision.

Don’t migrate more than you need to

Two traps catch people here.

Migrating the UI protocol along with the model call. If your frontend reads the Vercel AI SDK stream protocol, moving server execution to @openrouter/agent won’t preserve that wire format on its own. The docs are explicit: keep ai / @ai-sdk/react as documented UI-protocol dependencies, or put a verified adapter in between. Plain text streaming only works if your clients already read plain text.

Assuming the /api/chat route is your only call site. The cookbook tells the agent to also check command palettes, title and summary generators, autocomplete, classification, extraction, moderation and background workers. Those calls tend to stay on the old provider unnoticed and keep your old key in use for months.

If you’re building an agent from scratch, read about how the loop works first. How to create a headless agent and how to create an agent TUI build the same primitives by hand.

Cost and limits after you migrate

An agent loop can keep spending indefinitely, which is why the Agent SDK has maxCost and maxTokensUsed stop conditions. Set them from day one. For current OpenRouter pricing, free-model availability and rate limits, check the official docs and our OpenRouter free API page; these change constantly, so don’t trust a number in a blog post.

If cost matters to you, compare a gateway with going direct to one provider. Cheapest LLM API after the free tier works through the arithmetic, and the best free LLM APIs in 2026 roundup lists which providers still give out keys without a card.

Migration checklist

  1. Grep for @openrouter/sdk imports of callModel, tool, stepCountIs, hasToolCall, maxCost, maxTokensUsed, finishReasonIs.
  2. npm install @openrouter/agent.
  3. Change the default import to a named import of OpenRouter.
  4. Move tool() to @openrouter/agent/tool and stop conditions to @openrouter/agent/stop-conditions.
  5. Decide whether you still need @openrouter/sdk for platform endpoints. If you do, pin it in your own dependencies.
  6. Run one agent end to end and confirm a tool executes.
  7. Confirm your stop conditions fire (temporarily drop stepCountIs to 2 to prove it).
  8. Check the less obvious call sites: summarizers, classifiers, background jobs.

FAQ

Is the @openrouter/agent API different from the old SDK?

No. According to the migration skill, the OpenRouter client class and the client.callModel() pattern work the same way. Only the import source changes, along with the switch from a default to a named export. Tool definitions, stopWhen, and result.getText() stay the same.

Do I have to uninstall @openrouter/sdk?

Only if you no longer use it. Agent-only projects can remove it. If you call platform endpoints like model listing or credits, keep it as a direct dependency so you control which version resolves, since @openrouter/agent also pulls it in transitively.

Is the Agent SDK TypeScript-only?

No. The overview lists @openrouter/agent for TypeScript, openrouter-agent-sdk on PyPI for Python, and go-agent for Go, with the Python and Go ports kept in sync automatically. The docs use TypeScript examples throughout.

Do I need to rewrite my Claude Agent SDK loop to use OpenRouter?

No. Set ANTHROPIC_BASE_URL=https://openrouter.ai/api, ANTHROPIC_AUTH_TOKEN=$OPENROUTER_API_KEY, and ANTHROPIC_API_KEY explicitly empty, then swap model values for OpenRouter slugs. The agent loop, tools and permission prompts stay as they are.

What are the new features I get for migrating?

The skill documents a tool approval flow (requireApproval: true or a predicate function on a tool) and turn lifecycle callbacks (onTurnStart, onTurnEnd) that receive turn context. The Agent SDK is changing quickly, so check the official docs for the current feature list.