Connect LangChain to an AI API from Iran
LangChain is the most widely used Python framework for building on language models: chains, agents, tools and RAG. The ChatOpenAI class of the langchain-openai package takes a base_url; point it at 1xAi and the models of 10 vendors are available in your code with one key and a Toman bill.
Setting up LangChain
- [01]
Create an account and a 1xAi key. Register at 1xai.ir (the app is in Persian) and confirm your email or mobile number. You spin the sign-up gift wheel (from 100,000 to 1,000,000 Toman of gift credit) once, which is enough to test the connection. Then create a 1xai-* key in the dashboard and copy it at once: a key is shown only once.
- [02]
Install the packages. Install with pip install -U langchain langchain-openai; for Claude prompt caching add the langchain-anthropic package too.
- [03]
Put the key in an environment variable. Export ONEXAI_API_KEY with your 1xai-* key, so that the key is not written into the code.
- [04]
Create the model with base_url. Create ChatOpenAI with model set to the model name, base_url set to https://1xai.ir/v1 and api_key from the environment variable. The model name decides which vendor a request goes to; for Claude, change the name and nothing else.
- [05]
Run the example. Run python app.py. Each reply's usage_metadata holds its input, output and cached token counts, and the Toman cost of each call is recorded in the 1xAi dashboard.
Ready to copy
# pip install -U langchain langchain-openai
# https://docs.langchain.com/oss/python/integrations/chat/openai
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="gpt-5-mini",
base_url="https://1xai.ir/v1",
api_key=os.environ["ONEXAI_API_KEY"],
)
reply = llm.invoke("Explain prompt caching in two sentences.")
print(reply.content)
print(reply.usage_metadata)
# Claude, Gemini or DeepSeek: the same key and base URL, another model name
claude = ChatOpenAI(model="claude-sonnet-5", base_url="https://1xai.ir/v1", api_key=os.environ["ONEXAI_API_KEY"])
for chunk in claude.stream("Write a haiku about Tehran."):
print(chunk.content, end="", flush=True)# https://docs.langchain.com/oss/python/langchain/agents
import os
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_openai import ChatOpenAI
@tool
def word_count(text: str) -> int:
"""Count the words in a text."""
return len(text.split())
llm = ChatOpenAI(model="claude-sonnet-5", base_url="https://1xai.ir/v1", api_key=os.environ["ONEXAI_API_KEY"])
agent = create_agent(model=llm, tools=[word_count])
result = agent.invoke({"messages": [{"role": "user", "content": "How many words are in 'one key for every model'?"}]})
print(result["messages"][-1].content)# pip install -U langchain-anthropic
# https://docs.langchain.com/oss/python/integrations/chat/anthropic
import os
from langchain_anthropic import ChatAnthropic
claude = ChatAnthropic(
model="claude-sonnet-5",
base_url="https://1xai.ir/anthropic",
api_key=os.environ["ONEXAI_API_KEY"],
)
guide = open("guide.md", encoding="utf-8").read() # a long text sent with every call
messages = [
{"role": "system", "content": [{"type": "text", "text": guide, "cache_control": {"type": "ephemeral"}}]},
{"role": "user", "content": "Summarise the guide in five bullet points."},
]
reply = claude.invoke(messages)
print(reply.usage_metadata) # input_token_details: cache_creation, cache_readRecommended model
Recommended: claude-sonnet-5. A cheaper alternative: gpt-5-mini. For agents and tool calls the recommended model is dependable; for simple chains, summaries and classification the alternative is far cheaper. For prompt caching on Claude, use ChatAnthropic and the /anthropic route. Every model and its Toman price is on the models page.
What it costs
Each call is billed at the model's Toman price: the vendor's list price plus a markup of 15–30% depending on the model, at the day's dollar rate (refreshed every day at 9 in the morning, Tehran time). On /v1, OpenAI and Gemini models cache the repeated part of a prompt automatically, but Claude has no cache there. If you repeat a long system prompt in every call, call Claude with ChatAnthropic on the native route, so that the repeated part is billed at the cheaper cache rate. The native Anthropic route.
Common errors
- A 404 or model-not-found error
- base_url has to end in /v1, and the model name has to match the models page exactly. base_url in the code takes precedence over the OPENAI_BASE_URL and OPENAI_API_BASE variables, so you do not need them.
- Claude fails with reasoning or OpenAI's built-in tools
- With the reasoning parameter, OpenAI's built-in tools or previous_response_id, ChatOpenAI switches to the Responses API, which on 1xAi takes OpenAI models only and keeps no responses. For Claude leave those parameters out, or use ChatAnthropic on the native route.
- 401: invalid key
- The key is wrong, has expired, or you revoked it. Copy it again from the dashboard or create a new one, with no space before or after it.
- 402: insufficient balance
- The account's Toman credit is used up. A wallet top-up by the Zarinpal gateway or the Digipay gateway or card-to-card transfer with a receipt; calls work again as soon as a payment succeeds.
- Model name or routing error
- 1xAi routes by model name: claude-* to Anthropic, gemini-* to Google, deepseek-* to DeepSeek; grok-*, kimi-*, glm-*, qwen*, MiniMax-* and hy* reach the Grok, Kimi, GLM, Qwen, MiniMax and Hunyuan models; every other name goes to OpenAI. Write a model id exactly as the model list shows it.
Every error code is in the error reference.
Do embeddings and RAG work with the same key?
Yes. OpenAIEmbeddings from the same langchain-openai package works with model set to text-embedding-3-small and the same base_url and api_key, with any vector store LangChain supports.
How is the cost of a LangChain program billed?
Each model call is a call of its own, and an agent makes several calls per question. Each model costs its vendor's list price plus a markup of 15–30% depending on the model, and each reply's usage_metadata states its tokens. The sign-up gift wheel (from 100,000 to 1,000,000 Toman of gift credit) is enough to try it.
Other guides: Cursor, Claude Code, Codex CLI, n8n, Dify, Cline, Open WebUI, LibreChat, Continue, LlamaIndex, Vercel AI SDK, LiteLLM.
1xAi is an independent gateway. It is not affiliated with, endorsed by, or a reseller for OpenAI, Anthropic, Google, DeepSeek, xAI, Moonshot AI, Z.ai, Alibaba Qwen, MiniMax or Tencent Hunyuan. Requests are relayed upstream rather than answered by models of our own, so each provider's own usage policies apply to what their models will and will not do, and their model availability is theirs to change. Current reachability is published on the status page.