页面简介
Get started with OpenRouter
正文摘录
OpenRouter gives you access to hundreds of AI models through a single API endpoint. It handles fallbacks automatically and picks the most cost-effective option for each request. There are three ways to integrate with OpenRouter, depending on how much control you want: ApproachBest forAPIFull control, any language, no dependenciesClient SDKsType-safe model calls with minimal overheadAgent SDKBuilding agents with tool use, loops, and state Read github.com/OpenRouterTeam/skills/tree/main/skills/create-agent-tui and follow the instructions to build an agent using OpenRouter. Looking for information about free models and rate limits? Please see the FAQ In the examples below, the OpenRouter-specific headers are optional. Setting them allows your app to appear on the OpenRouter leaderboards. For detailed information about app attribution, see our App Attribution guide. Using the OpenRouter API The most direct way to use OpenRouter. Send standard HTTP requests to the /api/v1/responses endpoint. It works with any language or framework. You can use the interactive Request Builder to generate OpenRouter API requests in the language of your choice. The examples below use ~openai/gpt-sol-latest, a latest alias that always resolves to the newest model in the OpenAI GPT Sol family, so your code keeps using the freshest version without redeploying. You can substitute any model slug here. Browse the full catalog at openrouter.ai/models, or list every available slug programmatically via the GET /api/v1/models endpoint. PythonTypeScript (fetch)ShellGoimport requests import json response = requests.post( url="https://openrouter.ai/api/v1/responses", headers={ "Authorization": "Bearer <OPENROUTER_API_KEY>", "HTTP-Referer": "<YOUR_SITE_URL>", # Optional. Site URL for rankings on openrouter.ai. "X-OpenRouter-Title": "<YOUR_SITE_NAME>", # Optional. Site title for rankings on openrouter.ai. }, json={ "model": "~openai/gpt-sol-latest", "input": "What is the meaning of life?" } ) print(json.dumps(response.json(), indent=2)) Output{ "id": "gen-1794950777-ohGluKGXVfe7XRUEApST", "object": "response", "created_at": 1794950777, "model": "openai/gpt-6.2-sol", "status": "completed", "completed_at": 1794950779, "output": [ { "id": "msg_tmp_jygk8q70hz", "type": "message", "role": "assistant", "status": "completed", "content": [ { "type": "output_text", "text": "There may be no single meaning of life that everyone is meant to discover. But that doesn’t make the meanings we find any less real.\n\nA good working answer is: **find what’s worth caring about, and give it some of your life.** That might mean raising a child, understanding a small piece of the universe, making music with friends, or being someone another person can count on. Meaning isn’t the same as happiness: some of the things that make life most meaningful are hard, and we’d still choose them.\n\nIf the big question feels too abstract, try a smaller one: *When has my life felt worth the effort, and what was I giving myself to then?*", "annotations": [], "logprobs": [] } ], "phase": "final_answer" } ], "error": null, "incomplete_details": null, "access_programs": null, "tools": [], "tool_choice": "auto", "parallel_tool_calls": true, "max_output_tokens": null, "temperature": 1, "top_p": 1, "presence_penalty": 0, "frequency_penalty": 0, "top_logprobs": 0, "max_tool_calls": null, "metadata": {}, "background": false, "previous_response_id": null, The API also supports streaming. You can also use the OpenAI SDK pointed at OpenRouter as a drop-in replacement. For EU in-region routing on Business or Enterprise, send requests to https://eu.openrouter.ai/api/v1/responses, or set your SDK’s base URL to https://eu.openrouter.ai/api/v1, with an EU-eligible model. EU in-region routing on Business explains what is processed in Europe, what may be stored or processed in the US, and how BYOK requests are handled. Using the Client SDKs The Client SDKs wrap the OpenRouter API with full type safety, auto-generated types from the OpenAPI spec, and zero boilerplate. It’s intentionally lean, a thin layer over the REST API. First, install the SDK: npmpnpmyarnbundenopipnpm install @openrouter/sdk Then use it in your code: TypeScriptPythonGocURLimport { OpenRouter } from '@openrouter/sdk'; const client = new OpenRouter({ apiKey: '<OPENROUTER_API_KEY>', httpReferer: '<YOUR_SITE_URL>', // Optional. Site URL for rankings on openrouter.ai. appTitle: '<YOUR_SITE_NAME>', // Optional. Site title for rankings on openrouter.ai. }); const response = await client.responses.send({ responsesRequest: { model: '~openai/gpt-sol-latest', input: 'What is the meaning of life?', }, }); if (!('output' in response)) { throw new Error('Expected a non-streaming response'); } if (response.status !== 'completed') { throw new Error(response.error?.message ?? `Response ended as ${response.status}`); } const message = response.output.find((item) => item.type === 'message'); console.log(message?.content.find((part) => part.type === 'output_text')?.text); OutputThere’s no single answer everyone agrees on. Some people believe meaning comes from God or a purpose larger than themselves. Others believe we create it through our choices and commitments. And some find it in experiences they didn’t choose: loving someone, being moved by music, or receiving kindness when they needed it most. A practical answer is this: **life becomes meaningful when there are people, experiences, or commitments that matter to you—and you give them your attention.** If the big question feels too abstract, try a smaller one: *When has life felt most worth living to me, and what was I paying attention to then?* See the full Client SDKs documentation for streaming, embeddings, and the complete API reference. Using the Agent SDK The Agent SDK (@openrouter/agent) provides higher-level primitives for building AI agents. It handles multi-turn conversation loops, tool execution, and state management automatically via the callModel function. Install the package: npmpnpmyarnbundenonpm install @openrouter/agent Build an agent with tools: PythonGoimport { OpenRouter, tool } from '@openrouter/agent'; import { z } from 'zod'; const openrouter = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY, }); const weatherTool = tool({ name: 'get_weather', description: 'Get the current weather for a location', inputSchema: z.object({ location: z.string().describe('City name'), }), execute: async ({ location }) => { return { temperature: 72, condition: 'sunny', location }; }, }); const result = openrouter.callModel({ model: '~anthropic/claude-sonnet-latest', input: 'What is the weather in San Francisco?', tools: [weatherTool], }); const text = await result.getText(); console.log(text); See all 26 lines OutputSan Francisco is sunny right now, and the temperature is 72°. The tool didn't say whether that's °F or °C. San Francisco is usually mild, so it's probably °F. The SDK sends the prompt, receives a tool call from the model, executes get_weather, feeds the result back, and returns the final response, all in one callModel invocation. See the full Agent SDK documentation for stop conditions, streaming, dynamic parameters, and more. Using the OpenAI SDK You can also use the OpenAI SDK pointed at OpenRouter as a drop-in replacement. This is useful if you have existing code built on the OpenAI SDK and want to access OpenRouter’s model catalog without changing your code structure. TypescriptPythonGocURLimport OpenAI from 'openai'; const openai = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: '<OPENROUTER_API_KEY>', defaultHeaders: { 'HTTP-Referer': '<YOUR_SITE_URL>', // Optional. Site URL for rankings on openrouter.ai. 'X-OpenRouter-Title': '<YOUR_SITE_NAME>', // Optional. Site title for rankings on openrouter.ai. }, }); async function main() { const response = await openai.responses.create({ model: '~openai/gpt-sol-latest', input: 'What is the meaning of life?', }); console.log(response.output_text); } main(); See all 21 lines OutputThere may not be one meaning of life that everyone has to discover. But a life can still have meaning: in loving and being loved, in understanding a little more of the world, in making something worth sharing, or in easing someone else’s burden. Some people understand that meaning as something given by God; others see it as something we create through our commitments. Either way, you don’t have to settle the cosmic question before you can ask a more personal one: **What would I be glad to have given my time and care to?** Using third-party SDKs For information about using third-party SDKs, frameworks, and coding agents with OpenRouter, see our frameworks and integrations overview. Anthropic SDK & Claude Code: Anthropic-compatible clients automatically append /v1/messages, so set the base URL to https://openrouter.ai/api (without /v1). See the Claude Code integration guide for full setup instructions. Building with an AI assistant If you write code with an AI coding tool (Claude Code, Cursor, Codex, and others), connect the OpenRouter MCP server. It’s a remote server hosted by OpenRouter, so there’s nothing to install. Your assistant can pull live OpenRouter data (which models exist, what they cost, your credit balance, usage rankings) and search these docs while you build. That way its suggestions reflect current data instead of stale training knowledge. Add one URL to your MCP client and approve an OAuth login: https://mcp.openrouter.ai/mcp See the MCP server guide for per-client setup and the full tool list. To run models in your app, keep calling the OpenRouter API directly.Was this page helpful?YesNo