Skip to content
IQ

LangChain · Python

LangChain's ChatOpenAI and ChatAnthropic wrappers accept the same base_url argument as the underlying SDK. Swap the base URL on the model constructor and every chain that uses the LLM routes through the gateway.

Drop-in switch

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="auto",
    base_url="https://gateway.iq-routing.com/v1",
    api_key="gw_live_xxxxxxxx",
)

See Authentication for how to generate a gw_live_... key and where to store it.

langchain-anthropic follows the same pattern with base_url pointing at the gateway origin (no /v1 suffix; LangChain's wrapper appends the path itself).

Verify it routes

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

llm = ChatOpenAI(
    model="auto",
    base_url="https://gateway.iq-routing.com/v1",
    api_key=os.environ["IQ_API_KEY"],
    timeout=60,
    max_retries=0,
)

result = llm.invoke([HumanMessage(content="Summarise: routing-aware gateway.")])
print("Content:", result.content)
print("Model picked:", result.response_metadata.get("model_name"))
print("Token usage:", result.response_metadata.get("token_usage"))

Drop into a fresh venv with pip install langchain langchain-openai. Set IQ_API_KEY in your environment, run. The response_metadata["model_name"] field carries the chosen upstream model; the token_usage dict matches the standard OpenAI completion tokens shape.

The Anthropic equivalent:

import os
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage

llm = ChatAnthropic(
    model="claude-haiku-5-5",
    base_url="https://gateway.iq-routing.com",
    api_key=os.environ["IQ_API_KEY"],
    timeout=60,
    max_retries=0,
)

result = llm.invoke([HumanMessage(content="Say hello.")])

See LangChain's Anthropic chat docs for the ChatAnthropic constructor arguments.

Using capability aliases

Pass cap:<name> in the model field to request a capability; find the request in Requests to see the model IQ recorded and manage your organization's overrides at /settings/capabilities.

import os
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage

chat = ChatAnthropic(
    model="cap:reason-heavy",
    base_url="https://gateway.iq-routing.com",
    api_key=os.environ["IQ_API_KEY"],
)

result = chat.invoke([HumanMessage(content="Plan the migration in three phases.")])

When present, the x-iq-model response header identifies the model IQ dispatched, or the model recorded for a cache hit, but LangChain does not expose raw response headers by default (see the gotchas below). See the capability aliases docs for the full list of default mappings and how to override them. A workspace owner or admin can override the default capability mapping in the editor at /settings/capabilities.

Common gotchas

A missing or invalid API key returns 401 before the request reaches routing -- no provider call is made and nothing is billed. LangChain surfaces this as the underlying SDK's auth exception; see the API reference for the full set of status codes and error body shapes.

LangChain wraps the underlying SDK but does not expose the raw response headers by default, so the X-Request-Id header itself is not reachable through response_metadata or a callback. The gateway does embed its request id inside the completion, though: the chat-completion id field comes back as chatcmpl-<request-id>, one chatcmpl- prefix away from the value /requests/<request-id> expects. Whether that raw id survives into response_metadata or llm_output depends on your langchain-openai version, so treat it as a best-effort capture rather than a guaranteed one:

def request_id_from_response(result) -> str | None:
    raw_id = (
        (getattr(result, "llm_output", None) or {}).get("id")
        or (getattr(result, "response_metadata", None) or {}).get("id")
        or getattr(result, "id", None)
    )
    if raw_id and raw_id.startswith("chatcmpl-"):
        return raw_id.removeprefix("chatcmpl-")
    return None

If correlation matters for every call, call the underlying SDK directly instead of going through LangChain -- see the OpenAI Python recipe for the with_raw_response pattern that reads X-Request-Id off the real HTTP response.

Current ChatOpenAI and ChatAnthropic default to two retries; set max_retries=0 if your own queue handles backoff, and consult the OpenAI SDK retry docs for its Retry-After handling.

LangSmith tracing (LANGCHAIN_TRACING_V2=true) captures full prompt content. If you route through the gateway, every prompt traces to LangSmith's servers in addition to the gateway's own routing records. Pin your tracing scope; the gateway alone has the routing decision, the costs, and the cache hits.

The gateway forwards anthropic-beta identifiers to Anthropic and Claude Bedrock, may normalize the comma-separated values or add required beta identifiers, and omits them for other providers.

Try this in the playground

Run this snippet against your gateway key →