langchain-apimart 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- langchain_apimart-0.1.0/.gitignore +10 -0
- langchain_apimart-0.1.0/LICENSE +21 -0
- langchain_apimart-0.1.0/PKG-INFO +116 -0
- langchain_apimart-0.1.0/README.md +88 -0
- langchain_apimart-0.1.0/pyproject.toml +63 -0
- langchain_apimart-0.1.0/src/langchain_apimart/__init__.py +12 -0
- langchain_apimart-0.1.0/src/langchain_apimart/chat_models.py +174 -0
- langchain_apimart-0.1.0/src/langchain_apimart/py.typed +0 -0
- langchain_apimart-0.1.0/tests/__init__.py +0 -0
- langchain_apimart-0.1.0/tests/integration_tests/__init__.py +0 -0
- langchain_apimart-0.1.0/tests/integration_tests/test_standard.py +19 -0
- langchain_apimart-0.1.0/tests/unit_tests/__init__.py +0 -0
- langchain_apimart-0.1.0/tests/unit_tests/test_chat_models.py +226 -0
- langchain_apimart-0.1.0/tests/unit_tests/test_standard.py +29 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 APIMart
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: langchain-apimart
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: APIMart chat models for LangChain Python.
|
|
5
|
+
Project-URL: Homepage, https://apimart.ai
|
|
6
|
+
Project-URL: Documentation, https://docs.apimart.ai
|
|
7
|
+
Project-URL: Repository, https://github.com/ApiMartAI/langchain-apimart
|
|
8
|
+
Project-URL: Issues, https://github.com/ApiMartAI/langchain-apimart/issues
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: apimart,chat-completions,langchain,llm
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: langchain-core<2,>=1.7.7
|
|
20
|
+
Requires-Dist: langchain-openai<2,>=1.7.4
|
|
21
|
+
Requires-Dist: pydantic<3,>=2.7.4
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: httpx<1,>=0.28; extra == 'test'
|
|
24
|
+
Requires-Dist: langchain-tests<2,>=1.2; extra == 'test'
|
|
25
|
+
Requires-Dist: pytest-asyncio<2,>=1; extra == 'test'
|
|
26
|
+
Requires-Dist: pytest<10,>=8.4; extra == 'test'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# langchain-apimart
|
|
30
|
+
|
|
31
|
+
[APIMart](https://apimart.ai) chat models for [LangChain](https://docs.langchain.com/oss/python/langchain/overview) Python.
|
|
32
|
+
|
|
33
|
+
APIMart serves many hosted models (GPT, Claude, DeepSeek, Qwen, GLM, Grok and others) behind one OpenAI-compatible Chat Completions API. `ChatAPIMart` is a thin subclass of `ChatOpenAI` with APIMart defaults, so it supports streaming, tool calling, structured output and async like any LangChain chat model.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install -U langchain-apimart
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Create an API key at [apimart.ai](https://apimart.ai) and export it:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
export APIMART_API_KEY="your-api-key"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Usage
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from langchain_apimart import ChatAPIMart
|
|
51
|
+
|
|
52
|
+
llm = ChatAPIMart(model="deepseek-v4-flash", temperature=0)
|
|
53
|
+
print(llm.invoke("Name three prime numbers.").content)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Switch models by changing the `model` string, for example `gpt-5.5`, `claude-sonnet-5-5`, `qwen3.7-plus`, `glm-5.3` or `grok-4.7`. See [apimart.ai/model](https://apimart.ai/model) for the full list.
|
|
57
|
+
|
|
58
|
+
### Streaming
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
for chunk in llm.stream("Write a haiku about the sea."):
|
|
62
|
+
print(chunk.content, end="", flush=True)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Token usage is included in streamed responses and is counted once per response.
|
|
66
|
+
|
|
67
|
+
### Tool calling
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from pydantic import BaseModel, Field
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class GetWeather(BaseModel):
|
|
74
|
+
"""Get the current weather for a city."""
|
|
75
|
+
|
|
76
|
+
city: str = Field(description="City name")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
msg = llm.bind_tools([GetWeather]).invoke("What's the weather in Paris?")
|
|
80
|
+
print(msg.tool_calls)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Structured output
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
class Joke(BaseModel):
|
|
87
|
+
setup: str
|
|
88
|
+
punchline: str
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
joke = llm.with_structured_output(Joke).invoke("Tell me a joke about cats.")
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`with_structured_output` defaults to `method="function_calling"`, which works across APIMart models. `method="json_schema"` is honored only by some models; pass it explicitly when you know the model supports it.
|
|
95
|
+
|
|
96
|
+
## Configuration
|
|
97
|
+
|
|
98
|
+
| Argument | Environment variable | Default |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| `api_key` | `APIMART_API_KEY` | required |
|
|
101
|
+
| `base_url` | `APIMART_API_BASE` | `https://api.apimart.ai/api/v1` |
|
|
102
|
+
| `model` | | `deepseek-v4-flash` |
|
|
103
|
+
|
|
104
|
+
All other `ChatOpenAI` arguments (`temperature`, `max_tokens`, `timeout`, `max_retries`, ...) work as usual. The Responses API is not used.
|
|
105
|
+
|
|
106
|
+
## Development
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
pip install -e ".[test]"
|
|
110
|
+
pytest # offline unit tests
|
|
111
|
+
APIMART_API_KEY=... pytest tests/integration_tests # real API calls
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
MIT
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# langchain-apimart
|
|
2
|
+
|
|
3
|
+
[APIMart](https://apimart.ai) chat models for [LangChain](https://docs.langchain.com/oss/python/langchain/overview) Python.
|
|
4
|
+
|
|
5
|
+
APIMart serves many hosted models (GPT, Claude, DeepSeek, Qwen, GLM, Grok and others) behind one OpenAI-compatible Chat Completions API. `ChatAPIMart` is a thin subclass of `ChatOpenAI` with APIMart defaults, so it supports streaming, tool calling, structured output and async like any LangChain chat model.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install -U langchain-apimart
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Create an API key at [apimart.ai](https://apimart.ai) and export it:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
export APIMART_API_KEY="your-api-key"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from langchain_apimart import ChatAPIMart
|
|
23
|
+
|
|
24
|
+
llm = ChatAPIMart(model="deepseek-v4-flash", temperature=0)
|
|
25
|
+
print(llm.invoke("Name three prime numbers.").content)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Switch models by changing the `model` string, for example `gpt-5.5`, `claude-sonnet-5-5`, `qwen3.7-plus`, `glm-5.3` or `grok-4.7`. See [apimart.ai/model](https://apimart.ai/model) for the full list.
|
|
29
|
+
|
|
30
|
+
### Streaming
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
for chunk in llm.stream("Write a haiku about the sea."):
|
|
34
|
+
print(chunk.content, end="", flush=True)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Token usage is included in streamed responses and is counted once per response.
|
|
38
|
+
|
|
39
|
+
### Tool calling
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from pydantic import BaseModel, Field
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class GetWeather(BaseModel):
|
|
46
|
+
"""Get the current weather for a city."""
|
|
47
|
+
|
|
48
|
+
city: str = Field(description="City name")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
msg = llm.bind_tools([GetWeather]).invoke("What's the weather in Paris?")
|
|
52
|
+
print(msg.tool_calls)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Structured output
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
class Joke(BaseModel):
|
|
59
|
+
setup: str
|
|
60
|
+
punchline: str
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
joke = llm.with_structured_output(Joke).invoke("Tell me a joke about cats.")
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`with_structured_output` defaults to `method="function_calling"`, which works across APIMart models. `method="json_schema"` is honored only by some models; pass it explicitly when you know the model supports it.
|
|
67
|
+
|
|
68
|
+
## Configuration
|
|
69
|
+
|
|
70
|
+
| Argument | Environment variable | Default |
|
|
71
|
+
|---|---|---|
|
|
72
|
+
| `api_key` | `APIMART_API_KEY` | required |
|
|
73
|
+
| `base_url` | `APIMART_API_BASE` | `https://api.apimart.ai/api/v1` |
|
|
74
|
+
| `model` | | `deepseek-v4-flash` |
|
|
75
|
+
|
|
76
|
+
All other `ChatOpenAI` arguments (`temperature`, `max_tokens`, `timeout`, `max_retries`, ...) work as usual. The Responses API is not used.
|
|
77
|
+
|
|
78
|
+
## Development
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
pip install -e ".[test]"
|
|
82
|
+
pytest # offline unit tests
|
|
83
|
+
APIMART_API_KEY=... pytest tests/integration_tests # real API calls
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
MIT
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27,<2"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-apimart"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "APIMart chat models for LangChain Python."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
keywords = ["langchain", "apimart", "llm", "chat-completions"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.10",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"langchain-core>=1.7.7,<2",
|
|
24
|
+
"langchain-openai>=1.7.4,<2",
|
|
25
|
+
"pydantic>=2.7.4,<3",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://apimart.ai"
|
|
30
|
+
Documentation = "https://docs.apimart.ai"
|
|
31
|
+
Repository = "https://github.com/ApiMartAI/langchain-apimart"
|
|
32
|
+
Issues = "https://github.com/ApiMartAI/langchain-apimart/issues"
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
test = [
|
|
36
|
+
"httpx>=0.28,<1",
|
|
37
|
+
"langchain-tests>=1.2,<2",
|
|
38
|
+
"pytest>=8.4,<10",
|
|
39
|
+
"pytest-asyncio>=1,<2",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.wheel]
|
|
43
|
+
packages = ["src/langchain_apimart"]
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.sdist]
|
|
46
|
+
include = ["/src", "/tests", "/LICENSE", "/README.md", "/pyproject.toml"]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
testpaths = ["tests/unit_tests"]
|
|
50
|
+
asyncio_mode = "auto"
|
|
51
|
+
addopts = "-ra --strict-markers"
|
|
52
|
+
|
|
53
|
+
[tool.ruff]
|
|
54
|
+
target-version = "py310"
|
|
55
|
+
line-length = 88
|
|
56
|
+
|
|
57
|
+
[tool.ruff.lint]
|
|
58
|
+
select = ["E", "F", "I", "B", "UP"]
|
|
59
|
+
|
|
60
|
+
[tool.mypy]
|
|
61
|
+
python_version = "3.10"
|
|
62
|
+
strict = true
|
|
63
|
+
plugins = ["pydantic.mypy"]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""APIMart integration for LangChain."""
|
|
2
|
+
|
|
3
|
+
from importlib import metadata
|
|
4
|
+
|
|
5
|
+
from langchain_apimart.chat_models import ChatAPIMart
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = metadata.version(__package__ or "langchain-apimart")
|
|
9
|
+
except metadata.PackageNotFoundError:
|
|
10
|
+
__version__ = ""
|
|
11
|
+
|
|
12
|
+
__all__ = ["ChatAPIMart", "__version__"]
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""LangChain chat model for the APIMart Chat Completions API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator, Iterator
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
from langchain_core.callbacks import (
|
|
9
|
+
AsyncCallbackManagerForLLMRun,
|
|
10
|
+
CallbackManagerForLLMRun,
|
|
11
|
+
)
|
|
12
|
+
from langchain_core.language_models import LanguageModelInput
|
|
13
|
+
from langchain_core.messages import AIMessageChunk, BaseMessage
|
|
14
|
+
from langchain_core.messages.ai import UsageMetadata
|
|
15
|
+
from langchain_core.outputs import ChatGenerationChunk
|
|
16
|
+
from langchain_core.runnables import Runnable
|
|
17
|
+
from langchain_core.utils import from_env, secret_from_env
|
|
18
|
+
from langchain_openai import ChatOpenAI
|
|
19
|
+
from pydantic import ConfigDict, Field, SecretStr, field_validator
|
|
20
|
+
|
|
21
|
+
DEFAULT_BASE_URL = "https://api.apimart.ai/api/v1"
|
|
22
|
+
DEFAULT_MODEL = "deepseek-v4-flash"
|
|
23
|
+
_API_KEY_ENV = "APIMART_API_KEY"
|
|
24
|
+
_API_KEY_ERROR = "Set APIMART_API_KEY or pass a nonempty api_key."
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ChatAPIMart(ChatOpenAI):
|
|
28
|
+
"""APIMart chat model.
|
|
29
|
+
|
|
30
|
+
APIMart serves many hosted models (GPT, Claude, DeepSeek, Qwen, GLM, Grok and
|
|
31
|
+
others) behind one OpenAI-compatible Chat Completions endpoint. Pick a model
|
|
32
|
+
with the ``model`` argument; any model id listed at https://apimart.ai/model
|
|
33
|
+
works.
|
|
34
|
+
|
|
35
|
+
Setup:
|
|
36
|
+
.. code-block:: bash
|
|
37
|
+
|
|
38
|
+
pip install -U langchain-apimart
|
|
39
|
+
export APIMART_API_KEY="your-api-key"
|
|
40
|
+
|
|
41
|
+
Instantiate:
|
|
42
|
+
.. code-block:: python
|
|
43
|
+
|
|
44
|
+
from langchain_apimart import ChatAPIMart
|
|
45
|
+
|
|
46
|
+
llm = ChatAPIMart(model="deepseek-v4-flash", temperature=0)
|
|
47
|
+
|
|
48
|
+
Invoke:
|
|
49
|
+
.. code-block:: python
|
|
50
|
+
|
|
51
|
+
llm.invoke("Name three prime numbers.")
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
model_config = ConfigDict(hide_input_in_errors=True)
|
|
55
|
+
|
|
56
|
+
model_name: str = Field(default=DEFAULT_MODEL, alias="model")
|
|
57
|
+
"""Model id, for example ``gpt-5.5`` or ``claude-sonnet-5-5``."""
|
|
58
|
+
|
|
59
|
+
openai_api_base: str = Field(
|
|
60
|
+
alias="base_url",
|
|
61
|
+
default_factory=from_env("APIMART_API_BASE", default=DEFAULT_BASE_URL),
|
|
62
|
+
validate_default=True,
|
|
63
|
+
)
|
|
64
|
+
"""Base URL. Defaults to ``APIMART_API_BASE`` or the public endpoint."""
|
|
65
|
+
|
|
66
|
+
openai_api_key: SecretStr = Field(
|
|
67
|
+
alias="api_key",
|
|
68
|
+
default_factory=secret_from_env(_API_KEY_ENV, error_message=_API_KEY_ERROR),
|
|
69
|
+
repr=False,
|
|
70
|
+
exclude=True,
|
|
71
|
+
validate_default=True,
|
|
72
|
+
)
|
|
73
|
+
"""API key. Defaults to ``APIMART_API_KEY``."""
|
|
74
|
+
|
|
75
|
+
use_responses_api: Literal[False] = False
|
|
76
|
+
"""APIMart serves Chat Completions; the Responses API is not used."""
|
|
77
|
+
|
|
78
|
+
stream_usage: bool = True
|
|
79
|
+
"""Request token usage in streamed responses (supported by APIMart)."""
|
|
80
|
+
|
|
81
|
+
@field_validator("openai_api_key")
|
|
82
|
+
@classmethod
|
|
83
|
+
def _check_key(cls, value: SecretStr) -> SecretStr:
|
|
84
|
+
if not value.get_secret_value().strip():
|
|
85
|
+
raise ValueError(_API_KEY_ERROR)
|
|
86
|
+
return value
|
|
87
|
+
|
|
88
|
+
@field_validator("openai_api_base")
|
|
89
|
+
@classmethod
|
|
90
|
+
def _check_base_url(cls, value: str) -> str:
|
|
91
|
+
if not value.strip():
|
|
92
|
+
raise ValueError("Set APIMART_API_BASE or pass a nonempty base_url.")
|
|
93
|
+
return value.rstrip("/")
|
|
94
|
+
|
|
95
|
+
# Some upstream models behind APIMart attach a cumulative ``usage`` object to
|
|
96
|
+
# every streamed chunk instead of only the final one. Summing those chunks
|
|
97
|
+
# would multiply the token counts, so usage is held back while streaming and
|
|
98
|
+
# emitted once, from the last chunk that carried it.
|
|
99
|
+
|
|
100
|
+
def _stream(
|
|
101
|
+
self,
|
|
102
|
+
messages: list[BaseMessage],
|
|
103
|
+
stop: list[str] | None = None,
|
|
104
|
+
run_manager: CallbackManagerForLLMRun | None = None,
|
|
105
|
+
**kwargs: Any,
|
|
106
|
+
) -> Iterator[ChatGenerationChunk]:
|
|
107
|
+
usage: UsageMetadata | None = None
|
|
108
|
+
for chunk in super()._stream(messages, stop, run_manager, **kwargs):
|
|
109
|
+
usage = _take_usage(chunk, usage)
|
|
110
|
+
yield chunk
|
|
111
|
+
if usage is not None:
|
|
112
|
+
yield _usage_chunk(usage)
|
|
113
|
+
|
|
114
|
+
async def _astream(
|
|
115
|
+
self,
|
|
116
|
+
messages: list[BaseMessage],
|
|
117
|
+
stop: list[str] | None = None,
|
|
118
|
+
run_manager: AsyncCallbackManagerForLLMRun | None = None,
|
|
119
|
+
**kwargs: Any,
|
|
120
|
+
) -> AsyncIterator[ChatGenerationChunk]:
|
|
121
|
+
usage: UsageMetadata | None = None
|
|
122
|
+
async for chunk in super()._astream(messages, stop, run_manager, **kwargs):
|
|
123
|
+
usage = _take_usage(chunk, usage)
|
|
124
|
+
yield chunk
|
|
125
|
+
if usage is not None:
|
|
126
|
+
yield _usage_chunk(usage)
|
|
127
|
+
|
|
128
|
+
def with_structured_output(
|
|
129
|
+
self,
|
|
130
|
+
schema: Any = None,
|
|
131
|
+
*,
|
|
132
|
+
method: Literal[
|
|
133
|
+
"function_calling", "json_mode", "json_schema"
|
|
134
|
+
] = "function_calling",
|
|
135
|
+
include_raw: bool = False,
|
|
136
|
+
strict: bool | None = None,
|
|
137
|
+
**kwargs: Any,
|
|
138
|
+
) -> Runnable[LanguageModelInput, Any]:
|
|
139
|
+
"""Return a model that outputs data matching ``schema``.
|
|
140
|
+
|
|
141
|
+
Defaults to ``method="function_calling"``, which works across APIMart
|
|
142
|
+
models. ``json_schema`` response formats are honored only by some models,
|
|
143
|
+
so pass ``method="json_schema"`` explicitly when you know the model
|
|
144
|
+
supports it.
|
|
145
|
+
"""
|
|
146
|
+
return super().with_structured_output(
|
|
147
|
+
schema, method=method, include_raw=include_raw, strict=strict, **kwargs
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def _llm_type(self) -> str:
|
|
152
|
+
return "apimart-chat"
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def lc_secrets(self) -> dict[str, str]:
|
|
156
|
+
return {"openai_api_key": _API_KEY_ENV}
|
|
157
|
+
|
|
158
|
+
@classmethod
|
|
159
|
+
def is_lc_serializable(cls) -> bool:
|
|
160
|
+
return False
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _take_usage(
|
|
164
|
+
chunk: ChatGenerationChunk, last: UsageMetadata | None
|
|
165
|
+
) -> UsageMetadata | None:
|
|
166
|
+
message = chunk.message
|
|
167
|
+
if isinstance(message, AIMessageChunk) and message.usage_metadata:
|
|
168
|
+
last = message.usage_metadata
|
|
169
|
+
message.usage_metadata = None
|
|
170
|
+
return last
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _usage_chunk(usage: UsageMetadata) -> ChatGenerationChunk:
|
|
174
|
+
return ChatGenerationChunk(message=AIMessageChunk(content="", usage_metadata=usage))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""LangChain standard integration tests. Needs APIMART_API_KEY; makes real calls."""
|
|
2
|
+
|
|
3
|
+
from langchain_tests.integration_tests import ChatModelIntegrationTests
|
|
4
|
+
|
|
5
|
+
from langchain_apimart import ChatAPIMart
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TestChatAPIMartIntegration(ChatModelIntegrationTests):
|
|
9
|
+
@property
|
|
10
|
+
def chat_model_class(self) -> type[ChatAPIMart]:
|
|
11
|
+
return ChatAPIMart
|
|
12
|
+
|
|
13
|
+
@property
|
|
14
|
+
def chat_model_params(self) -> dict:
|
|
15
|
+
return {"model": "deepseek-v4-flash", "temperature": 0, "max_tokens": 1000}
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def supports_json_mode(self) -> bool:
|
|
19
|
+
return True
|
|
File without changes
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Offline tests: requests go to an httpx mock transport, never the network."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
import pytest
|
|
11
|
+
from pydantic import BaseModel, ValidationError
|
|
12
|
+
|
|
13
|
+
from langchain_apimart import ChatAPIMart
|
|
14
|
+
from langchain_apimart.chat_models import DEFAULT_BASE_URL, DEFAULT_MODEL
|
|
15
|
+
|
|
16
|
+
KEY = "local-mock-credential"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@pytest.fixture(autouse=True)
|
|
20
|
+
def _env(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
21
|
+
for var in (
|
|
22
|
+
"OPENAI_API_KEY",
|
|
23
|
+
"OPENAI_API_BASE",
|
|
24
|
+
"OPENAI_BASE_URL",
|
|
25
|
+
"APIMART_API_BASE",
|
|
26
|
+
"LANGSMITH_TRACING",
|
|
27
|
+
):
|
|
28
|
+
monkeypatch.delenv(var, raising=False)
|
|
29
|
+
monkeypatch.setenv("APIMART_API_KEY", KEY)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _completion(message: dict[str, Any], finish: str = "stop") -> httpx.Response:
|
|
33
|
+
return httpx.Response(
|
|
34
|
+
200,
|
|
35
|
+
json={
|
|
36
|
+
"id": "chatcmpl-test",
|
|
37
|
+
"object": "chat.completion",
|
|
38
|
+
"created": 1_800_000_000,
|
|
39
|
+
"model": DEFAULT_MODEL,
|
|
40
|
+
"choices": [{"index": 0, "message": message, "finish_reason": finish}],
|
|
41
|
+
"usage": {"prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8},
|
|
42
|
+
},
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.fixture
|
|
47
|
+
def mock_chat() -> Iterator[Any]:
|
|
48
|
+
clients: list[httpx.Client] = []
|
|
49
|
+
|
|
50
|
+
def make(responses: list[httpx.Response], **kw: Any) -> tuple[ChatAPIMart, list]:
|
|
51
|
+
seen: list[httpx.Request] = []
|
|
52
|
+
it = iter(responses)
|
|
53
|
+
|
|
54
|
+
def send(req: httpx.Request) -> httpx.Response:
|
|
55
|
+
seen.append(req)
|
|
56
|
+
return next(it)
|
|
57
|
+
|
|
58
|
+
client = httpx.Client(transport=httpx.MockTransport(send))
|
|
59
|
+
clients.append(client)
|
|
60
|
+
return ChatAPIMart(http_client=client, **kw), seen
|
|
61
|
+
|
|
62
|
+
yield make
|
|
63
|
+
for c in clients:
|
|
64
|
+
c.close()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_defaults() -> None:
|
|
68
|
+
llm = ChatAPIMart()
|
|
69
|
+
assert llm.model_name == DEFAULT_MODEL
|
|
70
|
+
assert llm.openai_api_base == DEFAULT_BASE_URL
|
|
71
|
+
assert llm.use_responses_api is False
|
|
72
|
+
assert llm._llm_type == "apimart-chat"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_env_base_url_and_trailing_slash(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
76
|
+
monkeypatch.setenv("APIMART_API_BASE", "https://proxy.example/api/v1/")
|
|
77
|
+
assert ChatAPIMart().openai_api_base == "https://proxy.example/api/v1"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_missing_key(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
81
|
+
monkeypatch.delenv("APIMART_API_KEY")
|
|
82
|
+
with pytest.raises(ValueError, match="APIMART_API_KEY"):
|
|
83
|
+
ChatAPIMart()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_blank_key_rejected() -> None:
|
|
87
|
+
with pytest.raises(ValidationError):
|
|
88
|
+
ChatAPIMart(api_key=" ")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_key_not_leaked() -> None:
|
|
92
|
+
llm = ChatAPIMart(api_key="sk-very-secret")
|
|
93
|
+
assert "sk-very-secret" not in repr(llm)
|
|
94
|
+
assert "sk-very-secret" not in str(llm.model_dump())
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_responses_api_cannot_be_enabled() -> None:
|
|
98
|
+
with pytest.raises(ValidationError):
|
|
99
|
+
ChatAPIMart(use_responses_api=True)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_invoke_hits_chat_completions(mock_chat: Any) -> None:
|
|
103
|
+
llm, seen = mock_chat([_completion({"role": "assistant", "content": "hi"})])
|
|
104
|
+
msg = llm.invoke("hello")
|
|
105
|
+
assert msg.content == "hi"
|
|
106
|
+
assert msg.usage_metadata["total_tokens"] == 8
|
|
107
|
+
req = seen[0]
|
|
108
|
+
assert str(req.url) == f"{DEFAULT_BASE_URL}/chat/completions"
|
|
109
|
+
assert req.headers["authorization"] == f"Bearer {KEY}"
|
|
110
|
+
body = json.loads(req.content)
|
|
111
|
+
assert body["model"] == DEFAULT_MODEL
|
|
112
|
+
assert body["messages"] == [{"role": "user", "content": "hello"}]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_tool_call_parsed(mock_chat: Any) -> None:
|
|
116
|
+
class Convert(BaseModel):
|
|
117
|
+
"""Convert currency."""
|
|
118
|
+
|
|
119
|
+
amount: float
|
|
120
|
+
to: str
|
|
121
|
+
|
|
122
|
+
tool_msg = {
|
|
123
|
+
"role": "assistant",
|
|
124
|
+
"content": None,
|
|
125
|
+
"tool_calls": [
|
|
126
|
+
{
|
|
127
|
+
"id": "call_1",
|
|
128
|
+
"type": "function",
|
|
129
|
+
"function": {
|
|
130
|
+
"name": "Convert",
|
|
131
|
+
"arguments": '{"amount": 250, "to": "JPY"}',
|
|
132
|
+
},
|
|
133
|
+
}
|
|
134
|
+
],
|
|
135
|
+
}
|
|
136
|
+
llm, seen = mock_chat([_completion(tool_msg, "tool_calls")])
|
|
137
|
+
out = llm.bind_tools([Convert]).invoke("250 CHF in yen?")
|
|
138
|
+
assert out.tool_calls[0]["name"] == "Convert"
|
|
139
|
+
assert out.tool_calls[0]["args"] == {"amount": 250, "to": "JPY"}
|
|
140
|
+
assert json.loads(seen[0].content)["tools"][0]["function"]["name"] == "Convert"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_stream_usage_on_by_default() -> None:
|
|
144
|
+
assert ChatAPIMart().stream_usage is True
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def test_structured_output_defaults_to_function_calling(mock_chat: Any) -> None:
|
|
148
|
+
class Joke(BaseModel):
|
|
149
|
+
"""A joke."""
|
|
150
|
+
|
|
151
|
+
setup: str
|
|
152
|
+
punchline: str
|
|
153
|
+
|
|
154
|
+
tool_msg = {
|
|
155
|
+
"role": "assistant",
|
|
156
|
+
"content": None,
|
|
157
|
+
"tool_calls": [
|
|
158
|
+
{
|
|
159
|
+
"id": "call_1",
|
|
160
|
+
"type": "function",
|
|
161
|
+
"function": {
|
|
162
|
+
"name": "Joke",
|
|
163
|
+
"arguments": '{"setup": "a", "punchline": "b"}',
|
|
164
|
+
},
|
|
165
|
+
}
|
|
166
|
+
],
|
|
167
|
+
}
|
|
168
|
+
llm, seen = mock_chat([_completion(tool_msg, "tool_calls")])
|
|
169
|
+
out = llm.with_structured_output(Joke).invoke("joke")
|
|
170
|
+
assert out == Joke(setup="a", punchline="b")
|
|
171
|
+
body = json.loads(seen[0].content)
|
|
172
|
+
assert "response_format" not in body
|
|
173
|
+
assert body["tools"][0]["function"]["name"] == "Joke"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _sse(chunks: list[dict[str, Any]]) -> httpx.Response:
|
|
177
|
+
body = "".join(f"data: {json.dumps(c)}\n\n" for c in chunks) + "data: [DONE]\n\n"
|
|
178
|
+
return httpx.Response(
|
|
179
|
+
200, content=body.encode(), headers={"content-type": "text/event-stream"}
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _delta(text: str, usage: dict[str, int] | None, finish: str | None = None) -> dict:
|
|
184
|
+
chunk: dict[str, Any] = {
|
|
185
|
+
"id": "c",
|
|
186
|
+
"object": "chat.completion.chunk",
|
|
187
|
+
"created": 1,
|
|
188
|
+
"model": DEFAULT_MODEL,
|
|
189
|
+
"choices": [{"index": 0, "delta": {"content": text}, "finish_reason": finish}],
|
|
190
|
+
}
|
|
191
|
+
if usage:
|
|
192
|
+
chunk["usage"] = usage
|
|
193
|
+
return chunk
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _u(p: int, c: int) -> dict[str, int]:
|
|
197
|
+
return {"prompt_tokens": p, "completion_tokens": c, "total_tokens": p + c}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@pytest.mark.parametrize(
|
|
201
|
+
"chunks",
|
|
202
|
+
[
|
|
203
|
+
# cumulative usage on every chunk, plus a usage-only final chunk
|
|
204
|
+
[
|
|
205
|
+
_delta("Hel", _u(10, 1)),
|
|
206
|
+
_delta("lo", _u(10, 2), "stop"),
|
|
207
|
+
{**_delta("", _u(10, 2)), "choices": []},
|
|
208
|
+
],
|
|
209
|
+
# OpenAI style: usage only on the final usage-only chunk
|
|
210
|
+
[
|
|
211
|
+
_delta("Hel", None),
|
|
212
|
+
_delta("lo", None, "stop"),
|
|
213
|
+
{**_delta("", _u(10, 2)), "choices": []},
|
|
214
|
+
],
|
|
215
|
+
],
|
|
216
|
+
)
|
|
217
|
+
def test_stream_usage_counted_once(mock_chat: Any, chunks: list[dict]) -> None:
|
|
218
|
+
llm, _ = mock_chat([_sse(chunks)])
|
|
219
|
+
full = None
|
|
220
|
+
for piece in llm.stream("hi"):
|
|
221
|
+
full = piece if full is None else full + piece
|
|
222
|
+
assert full is not None
|
|
223
|
+
assert full.content == "Hello"
|
|
224
|
+
assert full.usage_metadata["input_tokens"] == 10
|
|
225
|
+
assert full.usage_metadata["output_tokens"] == 2
|
|
226
|
+
assert full.usage_metadata["total_tokens"] == 12
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""LangChain standard unit tests."""
|
|
2
|
+
|
|
3
|
+
from langchain_tests.unit_tests import ChatModelUnitTests
|
|
4
|
+
|
|
5
|
+
from langchain_apimart import ChatAPIMart
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TestChatAPIMartStandard(ChatModelUnitTests):
|
|
9
|
+
@property
|
|
10
|
+
def chat_model_class(self) -> type[ChatAPIMart]:
|
|
11
|
+
return ChatAPIMart
|
|
12
|
+
|
|
13
|
+
@property
|
|
14
|
+
def chat_model_params(self) -> dict:
|
|
15
|
+
return {"model": "deepseek-v4-flash", "api_key": "test-key"}
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def init_from_env_params(self) -> tuple[dict, dict, dict]:
|
|
19
|
+
return (
|
|
20
|
+
{
|
|
21
|
+
"APIMART_API_KEY": "env-key",
|
|
22
|
+
"APIMART_API_BASE": "https://example.invalid/api/v1",
|
|
23
|
+
},
|
|
24
|
+
{"model": "deepseek-v4-flash"},
|
|
25
|
+
{
|
|
26
|
+
"openai_api_key": "env-key",
|
|
27
|
+
"openai_api_base": "https://example.invalid/api/v1",
|
|
28
|
+
},
|
|
29
|
+
)
|