Connect LangGraph (Python & TypeScript) to byesu API
Key Takeaways
- Python (
langchain-openai&langchain-anthropic): UseChatOpenAI(base_url="https://byesu.com/v1", api_key=...)for unified cross-vendor routing andChatAnthropic(anthropic_api_url="https://byesu.com", api_key=...)(without/v1) for native/v1/messages+0.1xprompt caching.- TypeScript (
@langchain/langgraph+@langchain/openai): Passconfiguration: { baseURL: "https://byesu.com/v1" }andapiKey: process.env.BYESU_API_KEY.- Multi-model graph node pattern: Run your Supervisor/Router on
gpt-6-lunaordeepseek-v4-pro, Planner onclaude-opus-5-5orgpt-6.2-sol, and Tool Worker onclaude-sonnet-5-5— all drawing from oneautogroup key at a fraction of list rates.- Streaming & checkpoints: Stream per-node tokens via
astream_events(..., version="v2")and keep staticSystemMessageprefixes immutable across graph checkpoints to preserve0.1xcached reads.
LangGraph models stateful, cyclic, human-in-the-loop agent architectures as explicit state machines in Python and TypeScript. Pairing LangGraph with byesu lets each node in your StateGraph bind the exact model tier that fits its latency and reasoning budget without juggling multiple upstream SDK credentials. (Looking for basic linear LangChain chains? See LangChain & LangGraph Basics.)
Step 0: Run the 5-Second Terminal Smoke Test
Create an sk-... token in the byesu Console under the default auto group (Quickstart). Verify your key against both /v1/chat/completions and /v1/messages before debugging graph state:
curl -fsSL https://docs.byesu.com/setup/test.sh | sh(Non-interactive shells: BYESU_KEY="sk-your-byesu-token" curl -fsSL https://docs.byesu.com/setup/test.sh | bash.) Interactive snippets are also available in the Client & SDK Config Generator.
Python: Multi-Model StateGraph (Supervisor + Planner + ReAct Worker)
Install the LangGraph ecosystem packages:
pip install langgraph langchain-openai langchain-anthropic langchain-core
export BYESU_API_KEY="sk-your-byesu-token"The production blueprint below assigns three distinct models across one StateGraph using a single BYESU_API_KEY:
- Supervisor / Router (
gpt-6-lunaordeepseek-v4-pro): Classifies intent in milliseconds via/v1/chat/completions. - Planner (
claude-opus-5-5orgpt-6.2-sol): Synthesizes architectural root-cause plans for complex requests. - Tool Worker (
claude-sonnet-5-5viacreate_react_agent): Executes@toolcalls over native/v1/messageswith0.1xprompt caching.
import asyncio
import os
from typing import Literal
from pydantic import BaseModel
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import create_react_agent
BYESU_KEY = os.environ["BYESU_API_KEY"]
# 1. Fast Supervisor / Router node (/v1 OpenAI-compatible)
router_llm = ChatOpenAI(
model="gpt-6-luna", # or "deepseek-v4-pro" / "deepseek-v4.1-flash"
api_key=BYESU_KEY,
base_url="https://byesu.com/v1",
timeout=60,
)
# 2. Deep Reasoning Planner node (/v1 OpenAI-compatible or native Anthropic)
planner_llm = ChatOpenAI(
model="gpt-6.2-sol", # or "claude-opus-5-5"
api_key=BYESU_KEY,
base_url="https://byesu.com/v1",
timeout=180,
)
# 3. Fast Tool-Execution Worker (native Anthropic /v1/messages, NO /v1 suffix!)
worker_llm = ChatAnthropic(
model="claude-sonnet-5-5",
api_key=BYESU_KEY,
anthropic_api_url="https://byesu.com",
timeout=120,
)
@tool
def query_service_slo(service: str) -> dict:
"""Fetch p95 latency and error-budget burn rate for a microservice."""
return {"service": service, "p95_ms": 412, "burn_rate_1h": 3.4}
worker_agent = create_react_agent(worker_llm, tools=[query_service_slo])
class RouteDecision(BaseModel):
next_node: Literal["planner", "worker"]
async def supervisor_node(state: MessagesState):
structured = router_llm.with_structured_output(RouteDecision)
decision = await structured.ainvoke(
[
SystemMessage(content="Route deep architecture design to 'planner'; live ops checks to 'worker'."),
*state["messages"],
]
)
return {"messages": [SystemMessage(content=f"[route={decision.next_node}]")]}
def route_edge(state: MessagesState) -> Literal["planner", "worker"]:
last = state["messages"][-1].content
return "planner" if "[route=planner]" in str(last) else "worker"
async def planner_node(state: MessagesState):
reply = await planner_llm.ainvoke(
[
SystemMessage(content="Produce a concise step-by-step remediation plan before tool execution."),
*state["messages"],
]
)
return {"messages": [reply]}
builder = StateGraph(MessagesState)
builder.add_node("supervisor", supervisor_node)
builder.add_node("planner", planner_node)
builder.add_node("worker", worker_agent)
builder.add_edge(START, "supervisor")
builder.add_conditional_edges("supervisor", route_edge)
builder.add_edge("planner", "worker")
builder.add_edge("worker", END)
graph = builder.compile(checkpointer=InMemorySaver())Streaming Node Tokens with astream_events(..., version="v2")
Use astream_events(..., version="v2") and inspect event["metadata"]["langgraph_node"] so your UI streams live tokens from "planner" and "worker" while suppressing internal "supervisor" routing steps:
async def run_stream():
config = {"configurable": {"thread_id": "incident-42"}}
inputs = {"messages": [HumanMessage(content="Check checkout-api SLO burn rate and propose mitigation.")]}
async for event in graph.astream_events(inputs, config=config, version="v2"):
node = event.get("metadata", {}).get("langgraph_node")
if event["event"] == "on_chat_model_stream" and node in ("planner", "worker"):
chunk = event["data"]["chunk"]
if chunk.content:
print(chunk.content, end="", flush=True)
asyncio.run(run_stream())TypeScript: @langchain/langgraph + @langchain/openai
Install the official TypeScript packages:
npm install @langchain/langgraph @langchain/openai @langchain/anthropic @langchain/core zodConfigure configuration: { baseURL: "https://byesu.com/v1" } on ChatOpenAI (and anthropicApiUrl: "https://byesu.com" without /v1 if using ChatAnthropic):
import { ChatOpenAI } from "@langchain/openai";
import { ChatAnthropic } from "@langchain/anthropic";
import { StateGraph, MessagesAnnotation, MemorySaver } from "@langchain/langgraph";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
const apiKey = process.env.BYESU_API_KEY!;
// OpenAI-compatible node (GPT-6.2, DeepSeek V4, Gemini 4)
const plannerModel = new ChatOpenAI({
model: "gpt-6.2-sol",
apiKey,
configuration: { baseURL: "https://byesu.com/v1" },
timeout: 150_000,
});
// Native Anthropic node (0.1x prompt caching over /v1/messages — NO /v1 suffix!)
const workerModel = new ChatAnthropic({
model: "claude-sonnet-5-5",
anthropicApiKey: apiKey,
anthropicApiUrl: "https://byesu.com",
});
const fetchDeployDiff = tool(
async ({ service }) => JSON.stringify({ service, commit: "a91f3c2", changedFiles: 6 }),
{
name: "fetch_deploy_diff",
description: "Inspect the latest production deployment metadata for a service.",
schema: z.object({ service: z.string() }),
}
);
const workerNode = createReactAgent({ llm: workerModel, tools: [fetchDeployDiff] });
const workflow = new StateGraph(MessagesAnnotation)
.addNode("planner", async (state) => ({
messages: [await plannerModel.invoke(state.messages)],
}))
.addNode("worker", workerNode)
.addEdge("__start__", "planner")
.addEdge("planner", "worker")
.addEdge("worker", "__end__")
.compile({ checkpointer: new MemorySaver() });
const stream = await workflow.streamEvents(
{ messages: [{ role: "user", content: "Audit the latest billing-api deploy diff and summarize risks." }] },
{ configurable: { thread_id: "ts-thread-1" }, version: "v2" }
);
for await (const ev of stream) {
if (ev.event === "on_chat_model_stream" && ev.data.chunk?.content) {
process.stdout.write(String(ev.data.chunk.content));
}
}Preserving 0.1x Prompt-Cache Prefixes Across Graph Checkpoints
Stateful graphs (PostgresSaver, RedisSaver, MemorySaver) replay growing message histories across super-steps and human-in-the-loop (interrupt()) pauses. Three rules keep cached input billing down to 0.1x:
- Never mutate the leading
SystemMessage: Injectingdatetime.now(), request UUIDs, or mutable scratchpad JSON into the top system string invalidates the entire prefix cache on every checkpoint turn. Keep the system instructions and tool definitions static, and append mutable state updates as trailing messages. - Attach
cache_controlon Claude nodes: When usingChatAnthropic(anthropic_api_url="https://byesu.com"), pass"cache_control": {"type": "ephemeral"}on static system blocks (>= 1,024tokens) — see Prompt Caching, Explained and Claude 5m vs GPT 30m Cache TTL. - Omit fixed
temperatureon reasoning tiers: Do not passtemperature=0onclaude-opus-5-5,claude-sonnet-5-5, orgpt-6.2-sol, which triggers HTTP400(Claude 400 temperature fix). Fund your unified gateway balance via USDT or Alipay and estimate multi-node token budgets in the Token Cost Calculator.
Troubleshooting
404onChatAnthropic: Remove/v1fromanthropic_api_url/anthropicApiUrlso it reads"https://byesu.com"(Claude 404 fix).401 authentication_error/invalid_api_key: EnsureBYESU_API_KEYis passed explicitly or exported cleanly without quotes (Claude 401 fix, OpenAI 401 fix).no available channel: Confirm your key is in the defaultautogroup (no available channel).
FAQ
How do I route different LangGraph nodes to different vendor models using one byesu API key?
Create separate ChatOpenAI(base_url="https://byesu.com/v1") and ChatAnthropic(anthropic_api_url="https://byesu.com") instances sharing BYESU_API_KEY — e.g. gpt-6-luna for routing, claude-opus-5-5 or gpt-6.2-sol for planning, and claude-sonnet-5-5 for tool execution.
What is the URL difference between ChatOpenAI and ChatAnthropic in LangGraph?
ChatOpenAI requires https://byesu.com/v1 (with /v1), whereas ChatAnthropic requires https://byesu.com (without /v1).
How do I keep 0.1x prompt caching stable across LangGraph checkpoints?
Keep your leading SystemMessage and tool array byte-identical across turns (no dynamic timestamps in the system prompt) and append state updates to the end of messages.
How do I stream token-by-token output from multi-node LangGraph workflows?
Iterate over graph.astream_events(inputs, config=config, version="v2") (Python) or workflow.streamEvents(..., { version: "v2" }) (TypeScript) and filter on_chat_model_stream by metadata.langgraph_node.