LangChain and LlamaIndex with a Custom Endpoint: Claude, GPT and Chinese Models on One Key
As of 2026-11-25, pointing LangChain or LlamaIndex at QCode takes one setting per model family. Claude goes through the Anthropic integrations with base_url="https://api.qcode.cc/api" (LangChain ChatAnthropic, LlamaIndex Anthropic). GPT and the Chinese models (GLM, Kimi, DeepSeek, Qwen) go through the OpenAI integrations with https://api.qcode.cc/openai/v1 (LangChain ChatOpenAI, LlamaIndex OpenAILike). The same cr_ key works for both. This guide was checked against langchain 1.5.2, langchain-anthropic 1.7.12, langchain-openai 1.8.5, llama-index-core 0.14.26, llama-index-llms-anthropic 0.13.0 and llama-index-llms-openai-like 0.9.0.
QCode is an independent third-party API service. It is not operated by, endorsed by or partnered with Anthropic, OpenAI, LangChain, LlamaIndex or any model vendor. Parameter names below come from each package's own source code and documentation.
Updated 2026-11-26
Key facts
- Two base URLs, one key. Anthropic protocol:
https://api.qcode.cc/api(the SDK appends/v1/messages). OpenAI protocol:https://api.qcode.cc/openai/v1(the SDK appends/chat/completionsor/responses). Alternate hosts:asia.qcode.ccandus.qcode.cc. - Protocol rule. Claude models run only on the Anthropic endpoint. GPT models run only on the OpenAI endpoint. GLM, Kimi, DeepSeek and Qwen run on both, but on the OpenAI side only via Chat Completions, not Responses.
- LangChain names.
ChatAnthropic(base_url=...)is an alias ofanthropic_api_url, andapi_keyis an alias ofanthropic_api_key.ChatOpenAI(base_url=...)is an alias ofopenai_api_base. - LlamaIndex names.
Anthropic(base_url=..., api_key=...)andOpenAILike(api_base=..., api_key=..., is_chat_model=True). Leavingis_chat_modelat its defaultFalseis the most common LlamaIndex mistake. - Billing. Official API price × service multiplier, currently ×1.0 for Anthropic and OpenAI models. Example list prices per million tokens on /models:
claude-sonnet-5-5$2 / $10,claude-opus-5-5$4 / $20,gpt-6.2-sol$2 / $10.
Which class talks to which endpoint
| Model family | LangChain class | LlamaIndex class | Base URL on QCode |
|---|---|---|---|
Claude (claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5, claude-fable-5-2) |
langchain_anthropic.ChatAnthropic |
llama_index.llms.anthropic.Anthropic |
https://api.qcode.cc/api |
GPT (gpt-6.2-sol, gpt-6.2-astra, gpt-6.1-sol) |
langchain_openai.ChatOpenAI |
llama_index.llms.openai_like.OpenAILike |
https://api.qcode.cc/openai/v1 |
GLM, Kimi, DeepSeek, Qwen (glm-5.3, kimi-k3.1-pro, deepseek-v4-pro, deepseek-v4.1-flash, qwen3.8-max) |
ChatOpenAI (or ChatAnthropic) |
OpenAILike (or Anthropic) |
/openai/v1 or /api |
The Chinese models also accept the Anthropic protocol on QCode, so you can run them through ChatAnthropic if your code base is built around Claude message blocks. For background on why the two protocols differ, see Anthropic Messages vs OpenAI Chat vs Responses.
Install and set environment variables
# LangChain 1.x
pip install -U langchain langchain-anthropic langchain-openai
# LlamaIndex 0.14.x
pip install -U llama-index-core llama-index-llms-anthropic \
llama-index-llms-openai-like llama-index-embeddings-huggingface
Keep the key out of source code. One variable for the key and two for the URLs is enough:
export QCODE_API_KEY="cr_your_key"
export QCODE_ANTHROPIC_BASE="https://api.qcode.cc/api"
export QCODE_OPENAI_BASE="https://api.qcode.cc/openai/v1"
If you prefer the frameworks' own variables, these are what they read when you pass nothing (from the package source):
| Variable | Read by | Value for QCode |
|---|---|---|
ANTHROPIC_API_URL, then ANTHROPIC_BASE_URL |
ChatAnthropic |
https://api.qcode.cc/api |
ANTHROPIC_API_KEY |
ChatAnthropic, the Anthropic SDK under LlamaIndex |
your cr_ key |
OPENAI_API_BASE (LangChain), then OPENAI_BASE_URL (OpenAI SDK) |
ChatOpenAI |
https://api.qcode.cc/openai/v1 |
OPENAI_API_KEY |
ChatOpenAI |
your cr_ key |
A warning for Claude Code users: Claude Code reads ANTHROPIC_AUTH_TOKEN, but ChatAnthropic looks for ANTHROPIC_API_KEY. If neither the argument nor ANTHROPIC_API_KEY is set, LangChain raises "Anthropic authentication failed: no API key or authorization credentials were provided." Pass api_key= explicitly and the problem goes away.
LangChain: Claude with ChatAnthropic
import os
from langchain_anthropic import ChatAnthropic
claude = ChatAnthropic(
model="claude-sonnet-5-5",
base_url=os.environ["QCODE_ANTHROPIC_BASE"], # https://api.qcode.cc/api, no /v1
api_key=os.environ["QCODE_API_KEY"],
max_tokens=4096,
timeout=120, # alias of default_request_timeout
max_retries=2,
)
reply = claude.invoke("Explain idempotency in one sentence.")
print(reply.text)
print(reply.usage_metadata) # input/output tokens, including cache reads
For Opus 5.5 and Fable 5.2, depth is controlled by effort, not by turning thinking off. ChatAnthropic exposes it as effort (an alias of reasoning_effort, which it sends as output_config.effort):
opus = ChatAnthropic(
model="claude-opus-5-5",
base_url=os.environ["QCODE_ANTHROPIC_BASE"],
api_key=os.environ["QCODE_API_KEY"],
max_tokens=16000,
effort="high", # low | medium | high | xhigh | max
)
LangChain: GPT and Chinese models with ChatOpenAI
from langchain_openai import ChatOpenAI
def qcode_openai(model: str, **kw) -> ChatOpenAI:
return ChatOpenAI(
model=model,
base_url=os.environ["QCODE_OPENAI_BASE"], # https://api.qcode.cc/openai/v1
api_key=os.environ["QCODE_API_KEY"],
stream_usage=True, # off by default when base_url is custom
**kw,
)
gpt = qcode_openai("gpt-6.2-sol")
glm = qcode_openai("glm-5.3")
kimi = qcode_openai("kimi-k3.1-pro")
ds = qcode_openai("deepseek-v4.1-flash")
for llm in (gpt, glm, kimi, ds):
print(llm.model_name, "->", llm.invoke("Reply with one word: ping").text)
Two behaviors in langchain-openai 1.8.5 are worth knowing:
- Automatic Responses API. When the model name starts with
gpt-6and the request carries tools,ChatOpenAIswitches to the Responses API (/openai/v1/responses). Setuse_responses_api=Falseto force Chat Completions, orTrueto always use Responses. Never set it toTruefor Chinese models: they are not served on Responses. If you rely on the Responses path, test tool calling with a small request first. - Non-standard fields are dropped. The package docstring says fields such as
reasoning_contentthat third-party providers add are not extracted. If you need DeepSeek's or Kimi's reasoning text in LangChain, use a provider-specific package or read the raw response; for plain answersChatOpenAIis fine. If you depend on tool calling with a Chinese model, test it with a small request first.
Streaming
The same loop works for every chat model, because streaming is part of LangChain's common interface:
for chunk in claude.stream("Write a haiku about CI pipelines."):
print(chunk.text, end="", flush=True)
# async version, e.g. inside FastAPI
async def stream_answer(question: str):
async for chunk in gpt.astream(question):
yield chunk.text
With stream_usage=True, the last ChatOpenAI chunk carries usage_metadata. ChatAnthropic streams usage by default (stream_usage=True). Log those numbers per request so you can reconcile against the QCode usage page.
Tool calling and a small agent
Define a tool once and bind it to any model:
from langchain_core.tools import tool
@tool
def get_file_size(path: str) -> int:
"""Return the size in bytes of a file in the current repository."""
return os.path.getsize(path)
msg = claude.bind_tools([get_file_size]).invoke("How big is README.md?")
print(msg.tool_calls) # [{'name': 'get_file_size', 'args': {'path': 'README.md'}, ...}]
For a loop that runs the tool and answers, LangChain 1.x provides create_agent:
from langchain.agents import create_agent
agent = create_agent(
model=claude, # swap in gpt or glm without other changes
tools=[get_file_size],
system_prompt="You answer questions about this repository. Use tools for facts.",
)
result = agent.invoke({"messages": [
{"role": "user", "content": "Which is larger, README.md or LICENSE?"}
]})
print(result["messages"][-1].text)
Two rules for new Claude models. First, Opus 5.5, Sonnet 5.5 and Fable 5.x reject a forced tool_choice (any or a named tool) with HTTP 400, so leave tool_choice unset and name the tool in the prompt. Second, for JSON output prefer claude.with_structured_output(MySchema, method="json_schema"). On those models the default function_calling method cannot force the tool and LangChain warns that it may raise OutputParserException. If your pipeline depends on the output_config.format field reaching the model, test it with a small request first.
LlamaIndex: Claude, GPT and Chinese models
import os
from llama_index.llms.anthropic import Anthropic
from llama_index.llms.openai_like import OpenAILike
claude = Anthropic(
model="claude-sonnet-5-5",
base_url=os.environ["QCODE_ANTHROPIC_BASE"], # https://api.qcode.cc/api
api_key=os.environ["QCODE_API_KEY"],
max_tokens=4096, # default is only 512
max_retries=3, # default is 10
timeout=120,
)
def qcode_like(model: str) -> OpenAILike:
return OpenAILike(
model=model,
api_base=os.environ["QCODE_OPENAI_BASE"], # https://api.qcode.cc/openai/v1
api_key=os.environ["QCODE_API_KEY"],
is_chat_model=True, # required, default False calls /completions
is_function_calling_model=True, # required for FunctionAgent
context_window=128000, # conservative; check /models
max_tokens=4096,
)
gpt = qcode_like("gpt-6.2-sol")
kimi = qcode_like("kimi-k3.1-pro")
for r in claude.stream_complete("List three uses of a message queue."):
print(r.delta, end="", flush=True)
Why OpenAILike for GPT too? llama_index.llms.openai.OpenAI checks the model name against a built-in table, and a model missing from the installed package's table raises an "unknown model" error. OpenAILike skips that check and takes the context window you give it. The Anthropic class has a similar table: if your model is not listed in the installed version, llm.metadata can raise ValueError: Unknown model; upgrade the package or use OpenAILike.
A small RAG pipeline and an agent in LlamaIndex
The example indexes a folder of Markdown files and answers with Claude. The vector step uses a local embedding model, so it does not depend on a hosted embeddings endpoint:
from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
Settings.llm = claude
Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
docs = SimpleDirectoryReader("./docs", required_exts=[".md"]).load_data()
index = VectorStoreIndex.from_documents(docs)
engine = index.as_query_engine(similarity_top_k=4, streaming=True)
engine.query("How do we rotate API keys in staging?").print_response_stream()
To switch the answering model, change only Settings.llm, for example to kimi for Chinese-language docs.
An agent with one tool, using LlamaIndex's workflow agents:
import asyncio
from llama_index.core.agent.workflow import FunctionAgent
def estimate_cost(input_tokens: int, output_tokens: int) -> float:
"""Estimate USD cost for claude-sonnet-5-5 at $2 / $10 per million tokens."""
return input_tokens * 2 / 1e6 + output_tokens * 10 / 1e6
agent = FunctionAgent(
tools=[estimate_cost],
llm=claude,
system_prompt="You estimate API costs. Always call the tool for arithmetic.",
)
async def main():
resp = await agent.run(user_msg="Cost of 1.2M input and 300K output tokens?")
print(str(resp))
asyncio.run(main())
FunctionAgent refuses an LLM whose metadata says it cannot call functions, which is another reason to set is_function_calling_model=True on OpenAILike.
Common errors and fixes
| Symptom | Usual cause | Fix |
|---|---|---|
404 from ChatAnthropic or LlamaIndex Anthropic |
base_url ends in /api/v1, so the request becomes /api/v1/v1/messages |
Stop at https://api.qcode.cc/api, no trailing slash |
404 from ChatOpenAI / OpenAILike |
Base URL missing /v1, or OpenAILike left at is_chat_model=False and calling /completions |
Use https://api.qcode.cc/openai/v1 and set is_chat_model=True |
model_not_available_on_endpoint |
A Claude model sent through ChatOpenAI or OpenAILike |
Use ChatAnthropic / Anthropic on /api for Claude |
| "Anthropic authentication failed: no API key..." | Only ANTHROPIC_AUTH_TOKEN set (Claude Code style) |
Pass api_key= or set ANTHROPIC_API_KEY |
ValueError: Unknown model in LlamaIndex |
Model missing from the installed package's model table | Use OpenAILike, a listed model ID, or upgrade the package |
| Answers cut off at about 512 tokens | LlamaIndex Anthropic default max_tokens=512 |
Set max_tokens explicitly |
| HTTP 400 on Opus 5.5 / Sonnet 5.5 | Forced tool_choice, or thinking disabled / budget_tokens |
Leave tool_choice unset; use effort |
| Streaming shows no token usage | ChatOpenAI disables stream_usage for custom base URLs |
stream_usage=True |
402 daily_cost_limit_exceeded |
Plan's daily quota used up | Resets at 00:00 Beijing time, or top up |
| 429 under load | More parallel calls in flight than your plan or key allows | Lower max_concurrency in batch(), or queue requests |
When you run chain.batch(inputs, config={"max_concurrency": 4}), keep the number under your key's concurrency limit. That is cheaper than retrying 429s.
LangChain or LlamaIndex, and production tips
Both frameworks connect to QCode the same way, so pick by application shape:
- Conversation, tools and multi-step flows (support assistants, code-review bots, internal ops agents): LangChain 1.x with
create_agentand middleware is the more natural fit, and the model object swaps between Claude, GPT and GLM without other changes. - Retrieval and Q&A (knowledge bases, document assistants): LlamaIndex has the fuller set of readers, indexes and query engines, and
Settings.llmswitches the answering model in one line. - Mixing them is fine. One
cr_key can serve both frameworks, with one quota and one bill.
Before going live:
- Pick the model per task. Use low-cost models such as
claude-haiku-5-5ordeepseek-v4.1-flashfor summarizing retrieved chunks, classification and rewriting; keepclaude-opus-5-5orgpt-6.2-solfor planning and code changes. Note that Haiku 5.5 bills the whole request at a higher tier once one prompt exceeds 100K tokens. - Put long, stable content first. Keep the system prompt, tool definitions and project rules unchanged so Claude's prompt cache can hit. Do not put timestamps in the system prompt.
- Keep history append-only. On Opus 5.5 and other new models, thinking blocks are tied to the conversation; rewriting earlier messages breaks both cache and thinking blocks.
- Set timeouts and retries deliberately. LangChain defaults to
max_retries=2; LlamaIndexAnthropicdefaults to 10, which can stretch one failing call for a long time. - Pick a host by region and measure. Try
asia.qcode.ccin Asia andus.qcode.ccin North America or Europe, keeping the/apior/openai/v1path. - Log usage per request. Send
usage_metadatato your logs or tracing tool so month-end reconciliation with the QCode dashboard is quick.
FAQ
What base_url do I use for ChatAnthropic?
Use https://api.qcode.cc/api. The underlying Anthropic SDK appends /v1/messages, so adding /v1 yourself produces a 404. base_url is an alias of anthropic_api_url, so either name works.
Can I call Claude through ChatOpenAI or OpenAILike?
No. On QCode, Claude models are served only on the Anthropic Messages endpoint, and the OpenAI path returns model_not_available_on_endpoint. Use ChatAnthropic or LlamaIndex Anthropic for Claude, and the OpenAI classes for GPT and Chinese models.
Do DeepSeek, Kimi, GLM and Qwen work in LangChain?
Yes, through ChatOpenAI with base_url="https://api.qcode.cc/openai/v1" and the exact model ID from /models, such as glm-5.3 or kimi-k3.1-pro. They also accept the Anthropic protocol, so ChatAnthropic on /api works too. Do not force the Responses API for them.
Why does LlamaIndex OpenAILike return 404 or empty answers?
OpenAILike defaults to is_chat_model=False, which sends requests to the legacy /completions route. Set is_chat_model=True, and for agents also is_function_calling_model=True.
How does the RAG example handle embeddings?
The example uses a local Hugging Face embedding model for retrieval, with Claude or another chat model for the answer step, so it does not depend on a hosted embeddings endpoint. If you plan to call one, test it with a small request first.
Does prompt caching work through LangChain?
Caching is a feature of the Claude models on the Anthropic endpoint, and ChatAnthropic passes cache_control content blocks through. Check usage_metadata on later calls to confirm cache reads; stable content must come first for the prefix to match.
How is usage billed?
QCode bills official API price × service multiplier, currently ×1.0 for Anthropic and OpenAI models. LangChain and LlamaIndex add no cost of their own; the tokens they send are what you pay for.
Which plan fits framework work
Prototyping a chain, running an evaluation set or indexing a document folder is bursty work, so pay-as-you-go packs are the simplest choice: no subscription, 7-day validity, stackable, from $4 for $30 of usage per /pay-as-you-go as of 2026-11-25. If the agent runs every day in production, compare the daily-quota plans on /pricing.