Skip to main content

Agent frameworks

An agent framework is a library that turns a model into a program that plans, calls tools and keeps state, such as a support bot that looks up orders or a research agent that reads documents. Every framework on this page talks to a model through an OpenAI or Anthropic style client, so pointing that client at the gateway is a two line change. Once it is done, every model call the agent makes uses a Spanway virtual key, so it counts against that key's budget and rate limit, shows on the Logs page, can fall back to another provider when one fails, and passes through the guardrails your admin set, without the agent's code ever holding a provider key.

A real-world scenario​

A product team builds an order support agent with LangGraph and a document summariser with CrewAI. Both ran against a provider key that sat in a shared .env file, and one runaway tool loop cost a weekend of spend. The admin creates one key per agent, each limited to the two models it needs, with a 100 USD monthly budget and 60 requests per minute. The developers change the base URL and the key in two lines each. The next loop stops at the budget with a clear 422 error, the Logs page shows which agent made every call, and the team can switch the summariser from one provider to another by changing the model behind its public name, with no code change.

Before you start​

  • A running gateway and its address, for example https://gateway.example.com. A local test gateway is http://localhost:4000.
  • A virtual key for the agent, made in the next section. Never put the master key in agent code.
  • The public model names the key may call. GET /v1/models with the key lists them.
  • Python 3.10 or later for the Python frameworks, or Node 20 or later for the Vercel AI SDK and LangChain.js.

Make a key for the agent​

Give every agent its own key, so its spend, errors and limits stay separate and one leaked key exposes one agent. Make a key for a tool has the full recipe. In short:

  1. In the Admin UI open Virtual Keys (/ui/api-keys) and click + Create New Key.
  2. Set Key Name to the agent, such as orders-agent-prod, and leave Key Type on AI APIs so the key cannot call management routes.
  3. In Models, pick the chat model the agent uses and every helper model it calls in the background. A RAG agent also needs its embedding model, CrewAI needs the model you give function_calling_llm or manager_llm, and an agent that writes short summaries on a cheaper model needs that one too. A missing helper model fails with 403 while the main chat works.
  4. Open Optional Settings. Set Max Budget (USD) and Reset Budget, and set Requests per minute Limit (RPM) and Tokens per minute Limit (TPM), because an agent loop can send hundreds of calls a minute. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage.
  5. Click Create Key and copy the key. It is shown once.

The same key from the API, with the master key or a proxy admin's key:

curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "orders-agent-prod", "key_type": "llm_api", "models": ["claude-sonnet-5-5", "claude-haiku-5-5", "text-embedding-3-large"], "max_budget": 100, "budget_duration": "30d", "rpm_limit": 60, "tpm_limit": 200000}'

The answer carries the new key in key. Store it where the agent reads its secrets, for example as SPANWAY_API_KEY in the environment.

Steps​

These steps hold for every framework, and the sections below give the exact setting names and code for each one.

  1. Check the key and the model names from a terminal.

    curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY"
  2. Set the base URL. Every framework on this page uses an OpenAI style client, which needs the address with /v1, such as https://gateway.example.com/v1. The one exception is LangChain's ChatAnthropic, which takes the bare root https://gateway.example.com because the Anthropic SDK adds /v1/messages itself. The Vercel AI SDK's Anthropic provider is not an exception. It takes the address with /v1 because it adds only /messages. The /v1 rule explains why.

  3. Pass the virtual key as the API key. The OpenAI style clients send it as Authorization: Bearer <key>, and the Anthropic style clients send it as x-api-key: <key>. The gateway accepts both.

  4. Use a public model name from step 1 as the model, typed exactly. It is the name the admin gave the model in Models + Endpoints, not the provider's own id.

  5. Run the agent once and open Logs (/ui/logs). Click Filters, pick the key in Key Alias and click Apply Filters. Every model call the agent made is a row.

LangChain and LangGraph​

LangChain's ChatOpenAI in the langchain-openai package is the client to use. It takes the base URL in base_url and the key in api_key, and reads OPENAI_API_KEY and then OPENAI_API_BASE or OPENAI_BASE_URL from the environment when they are not passed. LangGraph agents use the same chat model object, so connecting LangChain connects LangGraph.

  1. Install the packages.

    pip install -U langchain langchain-openai
  2. Create the chat model and call it.

    import os
    from langchain_openai import ChatOpenAI

    llm = ChatOpenAI(
    model="claude-sonnet-5-5",
    base_url="https://gateway.example.com/v1",
    api_key=os.environ["SPANWAY_API_KEY"],
    stream_usage=True,
    )
    print(llm.invoke("Say hello in five words.").content)
  3. Build an agent with tools. create_agent runs on LangGraph, so this is also the LangGraph setup.

    from langchain.agents import create_agent

    def order_status(order_id: str) -> str:
    """Look up the status of an order."""
    return f"Order {order_id} shipped yesterday."

    agent = create_agent(model=llm, tools=[order_status], system_prompt="You answer order questions.")
    result = agent.invoke({"messages": [{"role": "user", "content": "Where is order 4417?"}]})
    print(result["messages"][-1].content)

A node in your own LangGraph StateGraph calls llm.invoke(...) the same way. For embeddings use OpenAIEmbeddings(model="text-embedding-3-large", base_url="https://gateway.example.com/v1", api_key=...), and add check_embedding_ctx_length=False when the name routes to a provider other than OpenAI, because the client otherwise sends token ids that only OpenAI understands.

To use the gateway's Responses API route, pass use_responses_api=True to ChatOpenAI. To reach Claude models in the Anthropic format, for example to use Anthropic prompt caching blocks, use ChatAnthropic from langchain-anthropic with base_url="https://gateway.example.com" and api_key set to the virtual key, with no /v1.

LangChain.js takes the same values in a different shape.

import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
model: "claude-sonnet-5-5",
apiKey: process.env.SPANWAY_API_KEY,
configuration: { baseURL: "https://gateway.example.com/v1" },
});
console.log((await llm.invoke("Say hello in five words.")).content);

LlamaIndex​

LlamaIndex's OpenAILike class in the llama-index-llms-openai-like package is made for OpenAI compatible servers. It takes api_base, api_key, model, is_chat_model, is_function_calling_model and context_window. is_chat_model defaults to False, which makes LlamaIndex send prompts to the older text completion route, /v1/completions, where chat formatting and tool calling are lost, so always set it to True. LlamaIndex cannot look up the limits of a gateway name, so set context_window to the real window of the model behind the name.

  1. Install the packages.

    pip install llama-index-core llama-index-llms-openai-like llama-index-embeddings-openai
  2. Create the model and the embedding model, and make them the defaults.

    import os
    from llama_index.core import Settings, VectorStoreIndex, SimpleDirectoryReader
    from llama_index.llms.openai_like import OpenAILike
    from llama_index.embeddings.openai import OpenAIEmbedding

    Settings.llm = OpenAILike(
    model="claude-sonnet-5-5",
    api_base="https://gateway.example.com/v1",
    api_key=os.environ["SPANWAY_API_KEY"],
    is_chat_model=True,
    is_function_calling_model=True,
    context_window=1000000,
    )
    Settings.embed_model = OpenAIEmbedding(
    model="text-embedding-3-large",
    api_base="https://gateway.example.com/v1",
    api_key=os.environ["SPANWAY_API_KEY"],
    )

    index = VectorStoreIndex.from_documents(SimpleDirectoryReader("./docs").load_data())
    print(index.as_query_engine().query("What is our refund window?"))

Settings replaces the ServiceContext object that older LlamaIndex releases used, and the imports above replace the old llama_index.llms and llama_index.embeddings paths. Indexing sends one embedding call per batch of chunks, and each one shows on Logs with its own cost.

Vercel AI SDK​

The AI SDK for TypeScript reaches the gateway through @ai-sdk/openai-compatible. createOpenAICompatible takes name, baseURL, apiKey, headers, includeUsage and fetch, and sends apiKey as Authorization: Bearer <key>. includeUsage is off by default, which leaves token counts out of streamed results on the client side. The gateway still records tokens and cost either way.

  1. Install the packages.

    npm install ai @ai-sdk/openai-compatible
  2. Create the provider and call a model.

    import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
    import { generateText, streamText } from "ai";

    const spanway = createOpenAICompatible({
    name: "spanway",
    baseURL: "https://gateway.example.com/v1",
    apiKey: process.env.SPANWAY_API_KEY,
    includeUsage: true,
    headers: { "x-spanway-tags": "app:storefront" },
    });

    const { text, response } = await generateText({ model: spanway("claude-sonnet-5-5"), prompt: "Say hello in five words." });
    console.log(text, response.headers?.["x-spanway-call-id"]);

    const stream = streamText({ model: spanway("claude-sonnet-5-5"), prompt: "Count to five." });
    for await (const part of stream.textStream) process.stdout.write(part);

Options that only some providers take go under providerOptions.spanway, keyed by the name you chose. apiKey can also be a function that returns the current key, which lets you rotate it without restarting the app.

The other AI SDK providers work too. createOpenAI from @ai-sdk/openai with baseURL: "https://gateway.example.com/v1" calls the Responses API by default, which the gateway serves for every model, and provider.chat("<name>") uses chat completions instead. createAnthropic from @ai-sdk/anthropic takes baseURL: "https://gateway.example.com/v1" with /v1 because it adds only /messages, and sends apiKey as x-api-key.

OpenAI Agents SDK​

The OpenAI Agents SDK for Python uses the Responses API by default. The gateway serves /v1/responses for every model, OpenAI or not, so the default works. The SDK also uploads traces to OpenAI's own servers by default, which fails with a gateway key, so turn tracing off or give it a separate OpenAI key.

  1. Install the package.

    pip install openai-agents
  2. Point the SDK at the gateway and run an agent.

    import os
    from openai import AsyncOpenAI
    from agents import Agent, Runner, function_tool, set_default_openai_client, set_tracing_disabled

    set_default_openai_client(AsyncOpenAI(base_url="https://gateway.example.com/v1", api_key=os.environ["SPANWAY_API_KEY"]))
    set_tracing_disabled(True)

    @function_tool
    def order_status(order_id: str) -> str:
    """Look up the status of an order."""
    return f"Order {order_id} shipped yesterday."

    agent = Agent(name="Orders", instructions="You answer order questions.", model="claude-sonnet-5-5", tools=[order_status])
    print(Runner.run_sync(agent, "Where is order 4417?").final_output)

To use chat completions instead, call set_default_openai_api("chat_completions") or give the agent model=OpenAIChatCompletionsModel(model="claude-sonnet-5-5", openai_client=client). Setting OPENAI_BASE_URL and OPENAI_API_KEY in the environment works as well as set_default_openai_client. Reasoning effort goes in ModelSettings, passed as the agent's model_settings.

CrewAI​

CrewAI takes the gateway in its LLM class with model, base_url and api_key. Give the model the openai/ prefix, such as openai/claude-sonnet-5-5, so CrewAI uses its OpenAI compatible client for every name, including Claude and Gemini names, instead of trying to call that provider directly. Without the prefix, CrewAI may pick a provider from the name and call it directly, outside the gateway, or stop because it cannot choose one.

  1. Install the package.

    pip install crewai
  2. Create the model and a crew.

    import os
    from crewai import LLM, Agent, Task, Crew

    llm = LLM(
    model="openai/claude-sonnet-5-5",
    base_url="https://gateway.example.com/v1",
    api_key=os.environ["SPANWAY_API_KEY"],
    )

    writer = Agent(role="Summariser", goal="Summarise support tickets", backstory="You write short, plain summaries.", llm=llm, verbose=True)
    task = Task(description="Summarise: the customer cannot reset a password after the update.", expected_output="One sentence.", agent=writer)
    print(Crew(agents=[writer], tasks=[task], verbose=True).kickoff())

Every agent step is a model call, so one kickoff() makes several rows on Logs. Set llm= on every agent, and on function_calling_llm and manager_llm when you use them, or that part of the crew falls back to the default model from the environment. CrewAI also reads OPENAI_API_KEY, OPENAI_BASE_URL and MODEL from the environment, which is a way to cover every agent at once. Leave crew memory off unless its embedder is pointed at the gateway too, or its embedding calls go to a provider directly. stream=True on LLM streams the answer.

Pydantic AI​

Pydantic AI takes the gateway through OpenAIProvider with base_url and api_key, passed to OpenAIChatModel for chat completions or OpenAIResponsesModel for the Responses API. Pass the provider object every time, so the gateway address is set in code. A model string such as openai:claude-sonnet-5-5 without a provider uses the default OpenAI address unless something else in the environment overrides it.

  1. Install the package.

    pip install "pydantic-ai-slim[openai]"
  2. Create the model and an agent.

    import os
    from pydantic_ai import Agent
    from pydantic_ai.models.openai import OpenAIChatModel
    from pydantic_ai.providers.openai import OpenAIProvider

    provider = OpenAIProvider(base_url="https://gateway.example.com/v1", api_key=os.environ["SPANWAY_API_KEY"])
    agent = Agent(OpenAIChatModel("claude-sonnet-5-5", provider=provider), instructions="You answer order questions.")

    @agent.tool_plain
    def order_status(order_id: str) -> str:
    """Look up the status of an order."""
    return f"Order {order_id} shipped yesterday."

    print(agent.run_sync("Where is order 4417?").output)

OpenAIResponsesModel from the same module takes the same provider. api_key can also be an async function that returns the current key. To serve a Pydantic AI agent to other teams through the gateway instead, register it as an A2A agent, see framework agents.

Expected result​

Each example prints the model's answer, for example Hello there, nice to meet you. for the first LangChain call or Order 4417 shipped yesterday. for the agent examples. On the gateway side:

  • Logs (/ui/logs) has one row per model call, filtered by Key Alias. The row shows the public model name, the tokens, the cost and the route, /v1/chat/completions, /v1/responses, /v1/messages or /v1/embeddings. An agent that calls a tool shows two rows for one question, the call that asked for the tool and the call that read its result.
  • Virtual Keys, the key's Overview tab, shows the spend growing against the budget, and Usage groups it by the tag you set.
  • Every answer carries x-spanway-call-id, the id to search for on Logs, and x-spanway-response-cost with the cost of the call. x-spanway-model-group, x-spanway-model-id, x-spanway-routing-reason and x-spanway-attempts say which deployment served it and how many tries it took, see routing headers.

What works through the gateway​

FeatureHow it behavesKnown limits
StreamingEvery framework streams through the gateway, .stream() in LangChain, stream_chat in LlamaIndex, streamText in the AI SDK, Runner.run_streamed in the Agents SDK, stream=True in CrewAI and run_stream in Pydantic AI.Token counts in streamed results need stream_usage=True in LangChain and includeUsage: true in the AI SDK. The gateway counts them either way.
Tool callingTools work on every model behind the name that supports tool calling, whatever its provider, because the gateway translates the tool format.A model without tool support answers with a provider 400. The Agents SDK's hosted tools, such as web search and file search, run on the provider's side, so use function tools when the name may route to another provider.
Structured outputwith_structured_output in LangChain, output_type in the Agents SDK and Pydantic AI, generateObject in the AI SDK all work.Strict JSON schema mode depends on the provider. The gateway can repair an answer that does not match the schema.
ImagesImage parts in a message reach vision models from every provider.A model without vision answers with a provider 400.
Prompt cachingAnthropic cache_control blocks pass through on chat completions and /v1/messages, see prompt caching. OpenAI models cache automatically.Cache hits show as cached tokens on Logs. A name that falls back to another provider loses the cache for that call.
Reasoningreasoning_effort and the frameworks' own reasoning settings pass through, openai_reasoning_effort in Pydantic AI settings, ModelSettings(reasoning=...) in the Agents SDK, providerOptions in the AI SDK.LangChain's ChatOpenAI reads only OpenAI's own answer fields, so reasoning text from other providers is not kept. Use ChatAnthropic for Claude thinking blocks.
Parameters a provider does not takeThe gateway answers 400 naming the parameter.Remove it, or ask the admin to set drop params.

Errors​

Python frameworks built on the OpenAI SDK, which are LangChain, LlamaIndex, the Agents SDK and CrewAI, raise the OpenAI SDK's exception and print it as openai.<Class>: Error code: <status> - {'error': {'message': '<gateway text>', ...}}. Pydantic AI wraps the same answer as pydantic_ai.exceptions.ModelHTTPError: status_code: <status>, model_name: <name>, body: {...}. The Vercel AI SDK throws AI_APICallError with statusCode and the gateway text, and after its two retries on 429 and 5xx it throws AI_RetryError: Failed after 3 attempts. Last error: <gateway text>. The client error reference lists every gateway error with the SDK classes.

CaseWhat the framework showsCauseFix
401AuthenticationError: Error code: 401 with Authentication Error, Invalid proxy server token passed, or No api key passed in.The key is wrong, deleted or blocked, or the framework read another key from OPENAI_API_KEY.Pass the virtual key explicitly as shown above and check it with the curl in step 1.
403 model not allowedPermissionDeniedError: Error code: 403 with The requested model '<model>' is not available for this API key, or the model name is invalid.The key may not use that model. Agents often fail here on a helper model, such as the embedding model or the CrewAI function calling model.Add the model to the key in Virtual Keys, or use a name from GET /v1/models.
400 unknown modelBadRequestError: Error code: 400 with Invalid model name passed in model=<name>No deployment carries that name. A CrewAI openai/ prefix inside the name, or a provider id instead of the public name, causes it too.Use the public name exactly, including case, with the openai/ prefix only in CrewAI's model setting.
422 budgetUnprocessableEntityError: Error code: 422 with Budget has been exceeded! and the current cost and maximumThe key's budget is spent.Wait for the reset or ask the admin to raise Max Budget (USD). With budget_exceeded_status_code: 429 the framework sees RateLimitError instead.
429 rate limitRateLimitError: Error code: 429 with Rate limit exceeded for <scope>: <value>.The agent is over the key's RPM or TPM limit. The OpenAI SDK retries twice before raising it.Slow the loop, or ask for a higher Requests per minute Limit (RPM) or Tokens per minute Limit (TPM).
404 wrong path or doubled /v1NotFoundError: Error code: 404 with Not Found, or AI_APICallError with status 404The base URL carries /v1 twice or a path the gateway does not serve, such as a pasted /v1/chat/completions, or ChatAnthropic got a URL ending in /v1, which sends /v1/v1/messages.Apply the /v1 rule.
Connection refusedAPIConnectionError: Connection error. in Python, AI_APICallError: Cannot connect to API: fetch failed with ECONNREFUSED in the AI SDKNothing listens at that address, or the agent runs in Docker and localhost is the container.Check curl https://gateway.example.com/health/liveliness, and use host.docker.internal or the service name from a container.
TLS or CA errorAPIConnectionError: Connection error. caused by CERTIFICATE_VERIFY_FAILED, or UNABLE_TO_GET_ISSUER_CERT_LOCALLY and SELF_SIGNED_CERT_IN_CHAIN in NodeThe gateway's certificate is signed by a company authority the runtime does not trust.Point SSL_CERT_FILE at the company root certificate for Python, or NODE_EXTRA_CA_CERTS for Node. Never turn verification off outside a test machine.
Agents SDK tracing error in the log[non-fatal] Tracing client error 401 while the agent itself worksThe SDK uploads traces to OpenAI with the gateway key.Call set_tracing_disabled(True), or set_tracing_export_api_key(...) with an OpenAI key used only for traces.

Troubleshooting​

  1. Find the call on Logs. Filter by Key Alias, or paste the x-spanway-call-id into the search box. No row means the request never reached the gateway, so check the base URL, the network and TLS as in connect any client.
  2. Open the row. The drawer shows the status, the error text, the deployment the router picked and the provider's own answer. The response headers x-spanway-model-group, x-spanway-model-id, x-spanway-routing-reason and x-spanway-attempts repeat that on the client side. curl -i with the same key, model and prompt shows them.
  3. Turn on the framework's own debug output and compare the URL and headers it sends with the steps above.
FrameworkDebug switch
LangChain and LangGraphfrom langchain_core.globals import set_debug; set_debug(True), plus OPENAI_LOG=debug for every HTTP request.
LlamaIndeximport llama_index.core; llama_index.core.set_global_handler("simple"), plus OPENAI_LOG=debug.
Vercel AI SDKA fetch option on createOpenAICompatible that logs url and the status before returning the response.
OpenAI Agents SDKfrom agents import enable_verbose_stdout_logging; enable_verbose_stdout_logging().
CrewAIverbose=True on each Agent and on the Crew, plus OPENAI_LOG=debug.
Pydantic AIlogging.basicConfig(level=logging.DEBUG) for the httpx request lines, or Pydantic AI's OpenTelemetry instrumentation.
  1. When the request reaches the gateway but the reason is unclear, run a test gateway with --detailed_debug, which logs each request's route, key check and routing decision, see troubleshooting.
  2. Agents retry on their own, and so does the gateway, so one failing step can become several provider attempts. Set max_retries=0 on the OpenAI client, or maxRetries: 0 on AI SDK calls, when the gateway's retries and fallbacks should be the only ones.

Rotate or remove the key​

Rotate the key on a schedule and at once if it may have leaked. Open the key in Virtual Keys, click Regenerate Key, set a Grace Period such as 24h so the old key keeps working while you deploy, put the new key where the agent reads SPANWAY_API_KEY, and restart or redeploy the agent. Regenerating needs an Enterprise license. Without one, create a new key, move the agent to it and delete the old one. The AI SDK and Pydantic AI also take a function as the key, which picks up a new key without a restart.

To stop an agent at once, open the key's actions menu and click Block Key, which Unblock Key undoes. To remove it for good, click Delete Key and type the alias. From the API these are POST /key/block, POST /key/unblock and POST /key/delete.