> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apimart.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Using APIMart with LangChain

> Use APIMart chat models in LangChain Python with the langchain-apimart package: setup, streaming, tool calling, structured output, and agents.

## Introduction

[LangChain](https://docs.langchain.com/oss/python/langchain/overview) is an open-source framework for building applications and agents on top of large language models.
The `langchain-apimart` package provides `ChatAPIMart`, a LangChain chat model that connects to APIMart's OpenAI-compatible API, so you can use GPT, Claude, DeepSeek, Qwen, GLM, Grok and other models through one API key and switch between them by changing the model name.

`ChatAPIMart` supports the standard LangChain chat model interface: `invoke`, `stream`, `batch`, async methods, tool calling and structured output.

## Prerequisites

Before you begin, make sure you have:

1. **Python 3.10 or newer**

2. **An APIMart API key**
   Log in to the [APIMart Console](https://apimart.ai/keys) to get your API key (starts with `sk-`)

> [!NOTE]
>
> **Tip:** If you don't have an APIMart account yet, please register at [APIMart](https://apimart.ai) first and obtain your API key.

## Step 1: Install the package

```bash theme={null}
pip install -U langchain-apimart
```

This installs `langchain-apimart` together with `langchain-core` and `langchain-openai`.

> [!NOTE]
>
> If your terminal reports `command not found: pip` (common on macOS), use `pip3 install -U langchain-apimart` or `python3 -m pip install -U langchain-apimart` instead.

## Step 2: Set your API key

`ChatAPIMart` reads the key from the `APIMART_API_KEY` environment variable.

> [tab] macOS / Linux
>
> ```bash theme={null}
> export APIMART_API_KEY="sk-your-api-key"
> ```

> [tab] Windows (PowerShell)
>
> ```powershell theme={null}
> $env:APIMART_API_KEY="sk-your-api-key"
> ```

You can also pass the key directly with `ChatAPIMart(api_key="sk-...")`, but keep keys out of source code you share.

## Step 3: Send your first request

```python theme={null}
from langchain_apimart import ChatAPIMart

llm = ChatAPIMart(model="deepseek-v4-flash", temperature=0)

response = llm.invoke("Name three prime numbers.")
print(response.content)
```

To use another model, change the `model` value, for example `gpt-5.5`, `claude-sonnet-5-5`, `qwen3.7-plus`, `glm-5.3` or `grok-4.7`. See the [model list](https://apimart.ai/model) for all available model IDs.

## Streaming

```python theme={null}
from langchain_apimart import ChatAPIMart

llm = ChatAPIMart(model="deepseek-v4-flash", temperature=0)

for chunk in llm.stream("Write a haiku about the sea."):
    print(chunk.content, end="", flush=True)
```

Token usage is returned with streamed responses and is counted once per response, so `usage_metadata` on the combined message matches the token counts reported by the API.

## Tool calling

Describe a tool with a Pydantic model (or a function decorated with `@tool`) and bind it to the model:

```python theme={null}
from pydantic import BaseModel, Field

from langchain_apimart import ChatAPIMart

llm = ChatAPIMart(model="deepseek-v4-flash", temperature=0)


class GetWeather(BaseModel):
    """Get the current weather for a city."""

    city: str = Field(description="City name, for example Paris")


llm_with_tools = llm.bind_tools([GetWeather])
message = llm_with_tools.invoke("What's the weather in Paris right now?")
print(message.tool_calls)
```

The model returns a tool call such as `[{'name': 'GetWeather', 'args': {'city': 'Paris'}, ...}]`. Your code runs the tool and sends the result back as a `ToolMessage`.

## Structured output

Ask the model to return data that matches a schema:

```python theme={null}
from pydantic import BaseModel

from langchain_apimart import ChatAPIMart

llm = ChatAPIMart(model="deepseek-v4-flash", temperature=0)


class Joke(BaseModel):
    setup: str
    punchline: str


joke = llm.with_structured_output(Joke).invoke("Tell me a joke about cats.")
print(joke.setup)
print(joke.punchline)
```

> [!NOTE]
>
> `with_structured_output` uses tool calling by default, which works with all APIMart chat models that support tools. Some models also support OpenAI's `json_schema` response format; pass `method="json_schema"` only when you know the model supports it.

## Build an agent

`ChatAPIMart` works with LangChain agents. This example gives the model one tool and lets the agent decide when to call it:

```python theme={null}
from langchain.agents import create_agent
from langchain_core.tools import tool

from langchain_apimart import ChatAPIMart

llm = ChatAPIMart(model="deepseek-v4-flash", temperature=0)


@tool
def get_word_length(word: str) -> int:
    """Return the number of letters in a word."""
    return len(word)


agent = create_agent(llm, tools=[get_word_length])
result = agent.invoke(
    {"messages": [{"role": "user", "content": "How many letters are in 'interoperability'?"}]}
)
print(result["messages"][-1].content)
```

Install the agent package first with `pip install -U langchain`.

## Configuration reference

| Argument | Environment variable | Default |
| - | - | - |
| `api_key` | `APIMART_API_KEY` | Required |
| `base_url` | `APIMART_API_BASE` | `https://api.apimart.ai/api/v1` |
| `model` | | `deepseek-v4-flash` |

All other `ChatOpenAI` arguments, such as `temperature`, `max_tokens`, `timeout` and `max_retries`, work as usual.

## Using ChatOpenAI directly

If you already use `langchain-openai`, you can point `ChatOpenAI` at APIMart instead of installing a new package:

```python theme={null}
import os

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="deepseek-v4-flash",
    base_url="https://api.apimart.ai/api/v1",
    api_key=os.environ["APIMART_API_KEY"],
)
```

`ChatAPIMart` adds a few APIMart-specific defaults on top of this: it requests token usage when streaming and counts it once, uses tool calling for structured output, and always uses the Chat Completions API.

## FAQ

> [accordion] Which base URL should I use?
>
> Use `https://api.apimart.ai/api/v1`, which is the default in `ChatAPIMart`. It follows the standard OpenAI behavior and returns a single JSON response unless you ask for streaming.

> [accordion] I get an error about a missing API key
>
> Make sure `APIMART_API_KEY` is set in the same terminal session that runs your code, or pass `api_key` when creating `ChatAPIMart`.

> [accordion] Structured output returns plain text
>
> Remove `method="json_schema"` so that the default tool-calling method is used. Not every model supports the `json_schema` response format.

> [accordion] Where is the source code?
>
> The package is open source: [GitHub](https://github.com/ApiMartAI/langchain-apimart) · [PyPI](https://pypi.org/project/langchain-apimart/).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.