# LangChain & LangGraph

[LangChain](https://docs.langchain.com) is the largest LLM framework ecosystem
in Python. [LangGraph](https://docs.langchain.com/oss/python/langgraph/overview)
is its graph-based agent runtime. Both reach Hyphen through `ChatOpenAI` with
two changed kwargs.

```bash
pip install langchain langchain-openai langgraph
export HYPHEN_API_KEY="sk-..."
```

*Setup guide: this config comes from LangChain's official documentation and
has not been run end to end against the gateway. Corrections to [support@hyphen-solution.com](mailto:support@hyphen-solution.com).*

## The model

```python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="minimax-m3",
    base_url="https://api.hyphen-solution.com/v1",
    api_key=os.environ["HYPHEN_API_KEY"],
    max_tokens=2000,
    temperature=0,
)

print(llm.invoke("Explain a Bloom filter in three sentences.").content)
```

`base_url`, `api_key` and `model` are the canonical kwarg names.
`openai_api_base`, `openai_api_key` and `model_name` still work as aliases from
older tutorials, but use the short ones.

## Streaming

```python
for chunk in llm.stream("Count to ten slowly."):
    print(chunk.content, end="", flush=True)
```

## Tools

```python
from langchain_core.tools import tool


@tool
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"It is 31C and storming in {city}."


bound = llm.bind_tools([get_weather])
resp = bound.invoke("What is the weather in Kuala Lumpur?")
print(resp.tool_calls)
```

## A LangGraph agent

:::warning[`create_react_agent` is deprecated]
In LangGraph v1 the prebuilt `create_react_agent` from `langgraph.prebuilt` is
deprecated in favour of `create_agent` from `langchain.agents`. The old import
still runs but warns. The snippet below uses the current one.
:::

```python
import os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain.agents import create_agent

llm = ChatOpenAI(
    model="minimax-m3",
    base_url="https://api.hyphen-solution.com/v1",
    api_key=os.environ["HYPHEN_API_KEY"],
    max_tokens=4000,
    temperature=0,
)


@tool
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"It is 31C and storming in {city}."


agent = create_agent(
    model=llm,
    tools=[get_weather],
    system_prompt="You are a helpful assistant. Use the tools you have.",
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "What is the weather in Kuala Lumpur?"}]}
)
print(result["messages"][-1].content)
```

:::note[Pass the model object, not a string]
`create_agent` accepts either a `BaseChatModel` or a provider string like
`"openai:gpt-4o"`. **You must pass the object.** A string identifier has
nowhere to carry your `base_url`, so LangChain would send the request to
OpenAI instead of Hyphen.
:::

## Structured output

`with_structured_output` defaults to a function-calling strategy, which is what
you want here. MiniMax supports tool calling but not `response_format`, so do
not pass `method="json_mode"` or `method="json_schema"`.

```python
from pydantic import BaseModel, Field


class Issue(BaseModel):
    """A structured bug report."""

    title: str = Field(description="One-line summary")
    severity: str = Field(description="low, medium, high or critical")
    component: str


structured = llm.with_structured_output(Issue)  # method="function_calling" is the default
print(structured.invoke("The CSV exporter drops the last row on 2.4.1."))
```

## Gotchas

- **`max_tokens` of 2000 or more.** 4000 for agents. The M-series reason before
  answering and a tight cap returns an empty `AIMessage`. See
  [Choosing a model](/choosing-a-model#the-max_tokens-gotcha).
- **No `OpenAIEmbeddings` against Hyphen.** The catalog has no embedding
  models. Point your vector store somewhere else.
- **Doc links moved.** The API reference now lives at `reference.langchain.com`.
- **`429`** means your monthly budget is spent. See
  [Handling the 429 cap](/recipes/handling-429).

## Related

- [LangChain agents docs](https://docs.langchain.com/oss/python/langchain/agents)
- [ChatOpenAI reference](https://reference.langchain.com/python/langchain-openai/chat_models/base/ChatOpenAI/)
- [Structured JSON output](/recipes/structured-output): why tool calling and not JSON mode.
- [Choosing a model](/choosing-a-model): which model for which job.
