---
url: 'https://docs.byesu.com/en/clients/langgraph.md'
description: >-
  Connect LangGraph (Python & TypeScript) to byesu API: route Supervisor,
  Planner, and Worker nodes across Claude 5.5, GPT-6.2, and DeepSeek V4 on one
  key.
---

# Connect LangGraph (Python & TypeScript) to byesu API

> **Key Takeaways**
>
> * **Python (`langchain-openai` & `langchain-anthropic`)**: Use `ChatOpenAI(base_url="https://byesu.com/v1", api_key=...)` for unified cross-vendor routing and `ChatAnthropic(anthropic_api_url="https://byesu.com", api_key=...)` (**without `/v1`**) for native `/v1/messages` + `0.1x` prompt caching.
> * **TypeScript (`@langchain/langgraph` + `@langchain/openai`)**: Pass `configuration: { baseURL: "https://byesu.com/v1" }` and `apiKey: process.env.BYESU_API_KEY`.
> * **Multi-model graph node pattern**: Run your **Supervisor/Router** on [`gpt-6-luna`](/en/models/gpt-6) or [`deepseek-v4-pro`](/en/models/deepseek-v4), **Planner** on [`claude-opus-5-5`](/en/models/claude-opus-5-5) or [`gpt-6.2-sol`](/en/models/gpt-6-2), and **Tool Worker** on [`claude-sonnet-5-5`](/en/models/claude-sonnet-5-5) — all drawing from one **`auto`** group key at a fraction of list rates.
> * **Streaming & checkpoints**: Stream per-node tokens via `astream_events(..., version="v2")` and keep static `SystemMessage` prefixes immutable across graph checkpoints to preserve `0.1x` cached reads.

**LangGraph** models stateful, cyclic, human-in-the-loop agent architectures as explicit state machines in **Python** and **TypeScript**. Pairing LangGraph with **[byesu](https://byesu.com)** 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](/en/clients/langchain)**.)*

## Step 0: Run the 5-Second Terminal Smoke Test

Create an `sk-...` token in the [byesu Console](https://byesu.com/register) under the default **`auto`** group ([Quickstart](/en/guide/quickstart)). Verify your key against both `/v1/chat/completions` and `/v1/messages` before debugging graph state:

```bash
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](/en/tools/config-generator)**.

## Python: Multi-Model `StateGraph` (Supervisor + Planner + ReAct Worker)

Install the LangGraph ecosystem packages:

```bash
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`:

1. **Supervisor / Router (`gpt-6-luna` or `deepseek-v4-pro`)**: Classifies intent in milliseconds via `/v1/chat/completions`.
2. **Planner (`claude-opus-5-5` or `gpt-6.2-sol`)**: Synthesizes architectural root-cause plans for complex requests.
3. **Tool Worker (`claude-sonnet-5-5` via `create_react_agent`)**: Executes `@tool` calls over native `/v1/messages` with `0.1x` prompt caching.

```python
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:

```python
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:

```bash
npm install @langchain/langgraph @langchain/openai @langchain/anthropic @langchain/core zod
```

Configure `configuration: { baseURL: "https://byesu.com/v1" }` on `ChatOpenAI` (and `anthropicApiUrl: "https://byesu.com"` without `/v1` if using `ChatAnthropic`):

```typescript
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`**:

1. **Never mutate the leading `SystemMessage`**: Injecting `datetime.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.
2. **Attach `cache_control` on Claude nodes**: When using `ChatAnthropic(anthropic_api_url="https://byesu.com")`, pass `"cache_control": {"type": "ephemeral"}` on static system blocks (`>= 1,024` tokens) — see **[Prompt Caching, Explained](/en/guide/prompt-caching)** and **[Claude 5m vs GPT 30m Cache TTL](/en/articles/claude-5m-vs-gpt-30m-prompt-cache-ttl)**.
3. **Omit fixed `temperature` on reasoning tiers**: Do not pass `temperature=0` on `claude-opus-5-5`, `claude-sonnet-5-5`, or `gpt-6.2-sol`, which triggers HTTP `400` ([Claude 400 temperature fix](/en/errors/claude-api-400-temperature-top-p-not-supported)). Fund your unified gateway balance via **[USDT](/en/guide/pay-with-usdt)** or **Alipay** and estimate multi-node token budgets in the **[Token Cost Calculator](/en/tools/token-cost-calculator)**.

## Troubleshooting

* **`404` on `ChatAnthropic`**: Remove `/v1` from `anthropic_api_url` / `anthropicApiUrl` so it reads `"https://byesu.com"` ([Claude 404 fix](/en/errors/claude-api-model-not-found-404)).
* **`401 authentication_error` / `invalid_api_key`**: Ensure `BYESU_API_KEY` is passed explicitly or exported cleanly without quotes ([Claude 401 fix](/en/errors/claude-api-401-authentication-error), [OpenAI 401 fix](/en/errors/openai-api-401-invalid-api-key)).
* **`no available channel`**: Confirm your key is in the default **`auto`** group ([no available channel](/en/errors/no-available-channel-error)).

## 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`.

## Related Guides & Tools

* [Connect LangChain & LangGraph Basics to byesu API](/en/clients/langchain)
* [Connect CrewAI Multi-Agent Workflows to byesu API](/en/clients/crewai)
* [Connect OpenHands Autonomous SWE Agent to byesu API](/en/clients/openhands)
* [Prompt Caching, Explained (`0.1x` Cache Reads)](/en/guide/prompt-caching)
* [LLM API Token Cost Calculator](/en/tools/token-cost-calculator)
* [AI Client & SDK Config Generator](/en/tools/config-generator)
