Skip to main content
LangChain is a framework for building LLM-powered applications using composable chains and agents. Because the Portkey AI Gateway is OpenAI-compatible, you can use it as the LLM backend in any LangChain application by setting the base_url. This gives your LangChain app automatic retries, fallbacks, load balancing, caching, and guardrails — without changing your chain logic.

Installation

1

Start the gateway

The gateway listens at http://localhost:8787/v1.
2

Install dependencies

Basic setup

Set base_url on ChatOpenAI to point at the gateway.

Adding routing configs via headers

Pass gateway configs and Portkey metadata through default_headers (when constructing the client) or extra_headers (per-request).
createHeaders from portkey-ai is a convenience function that produces the correct x-portkey-* header dict. You can also construct headers manually.

Using in a chain

Drop the configured llm into any LangChain chain or pipeline as usual.

Real-world use case: RAG pipeline with fallback

A retrieval-augmented generation pipeline that falls back to a secondary model if the primary is unavailable.
All requests made through LangChain are logged and traceable in the Portkey dashboard when using the hosted gateway. Use trace_id in your headers to group related requests.