langchain-levanto 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_levanto-0.1.0/.gitignore +7 -0
- langchain_levanto-0.1.0/CHANGELOG.md +5 -0
- langchain_levanto-0.1.0/LICENSE +21 -0
- langchain_levanto-0.1.0/PKG-INFO +97 -0
- langchain_levanto-0.1.0/README.md +77 -0
- langchain_levanto-0.1.0/langchain_levanto/__init__.py +7 -0
- langchain_levanto-0.1.0/langchain_levanto/_version.py +9 -0
- langchain_levanto-0.1.0/langchain_levanto/chat_models.py +110 -0
- langchain_levanto-0.1.0/langchain_levanto/decision_models.py +305 -0
- langchain_levanto-0.1.0/langchain_levanto/py.typed +0 -0
- langchain_levanto-0.1.0/pyproject.toml +43 -0
- langchain_levanto-0.1.0/tests/__init__.py +0 -0
- langchain_levanto-0.1.0/tests/integration_tests/__init__.py +0 -0
- langchain_levanto-0.1.0/tests/integration_tests/test_live.py +121 -0
- langchain_levanto-0.1.0/tests/unit_tests/__init__.py +0 -0
- langchain_levanto-0.1.0/tests/unit_tests/test_chat_models.py +86 -0
- langchain_levanto-0.1.0/tests/unit_tests/test_decision_models.py +163 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Levanto
|
|
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,97 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: langchain-levanto
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Levanto for LangChain: Sage decisions and Levanto's LLMs.
|
|
5
|
+
Project-URL: Homepage, https://docs.levanto.ai/integrations/langchain
|
|
6
|
+
Project-URL: Repository, https://github.com/levantolabs/langchain-levanto
|
|
7
|
+
Project-URL: Changelog, https://github.com/levantolabs/langchain-levanto/blob/main/python/CHANGELOG.md
|
|
8
|
+
Author-email: Levanto <marco@levanto.ai>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: decision model,langchain,levanto,llm,router,sage
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Requires-Python: <4.0,>=3.11
|
|
16
|
+
Requires-Dist: httpx<1.0,>=0.27
|
|
17
|
+
Requires-Dist: langchain-core<2.0.0,>=1.8.0
|
|
18
|
+
Requires-Dist: langchain-openai<2.0.0,>=1.1.0
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# langchain-levanto
|
|
22
|
+
|
|
23
|
+
Levanto for LangChain: Sage decisions and Levanto's LLMs.
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install langchain-levanto
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
It reads your key from `LEVANTO_API_KEY`.
|
|
30
|
+
|
|
31
|
+
## Decisions
|
|
32
|
+
|
|
33
|
+
`LevantoDecisionModel` is a LangChain decision model. It answers yes/no (`Noul`), `Choice` and `Score` questions about text, JSON or chat messages, with full probabilities.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from langchain_core.decisions import Choice, Noul, Score
|
|
37
|
+
from langchain_levanto import LevantoDecisionModel
|
|
38
|
+
|
|
39
|
+
sage = LevantoDecisionModel()
|
|
40
|
+
response = sage.invoke({
|
|
41
|
+
"state": "I was charged twice. Please refund the duplicate today.",
|
|
42
|
+
"questions": {
|
|
43
|
+
"refund": Noul(instructions="Is the customer asking for money back?"),
|
|
44
|
+
"team": Choice(
|
|
45
|
+
instructions="Which team should handle this?",
|
|
46
|
+
criteria={"billing": "Charges and refunds", "technical": "Bugs and outages"},
|
|
47
|
+
),
|
|
48
|
+
"urgency": Score(instructions="How urgent is it?", criteria=["Can wait", "This week", "Today"]),
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
response.nouls["refund"].noul # 0.996
|
|
53
|
+
response.choices["team"].choice # "billing"
|
|
54
|
+
response.scores["urgency"].score # 1.99, from 0 to 2
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Options: `reasoning` (`"off"`, `"auto"`, `"on"`), `grounding`, `timeout` (15 s by default, 60 s with reasoning), `max_retries`. `Box` questions and images aren't supported; for images, call [`POST /decide`](https://docs.levanto.ai/decision-model/quickstart).
|
|
58
|
+
|
|
59
|
+
## Guard and route agents
|
|
60
|
+
|
|
61
|
+
LangChain's agent middleware takes any decision model.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from langchain.agents import create_agent
|
|
65
|
+
from langchain.agents.middleware import AutoModeMiddleware
|
|
66
|
+
|
|
67
|
+
# Sage blocks risky tool calls the user didn't ask for.
|
|
68
|
+
agent = create_agent(
|
|
69
|
+
model,
|
|
70
|
+
tools=[read_file, delete_file],
|
|
71
|
+
middleware=[AutoModeMiddleware(tools=[delete_file], classifier=LevantoDecisionModel())],
|
|
72
|
+
)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`ModelRouterMiddleware(choices=..., instructions=..., classifier=LevantoDecisionModel())` picks a model per run.
|
|
76
|
+
|
|
77
|
+
## LLMs
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from langchain_levanto import ChatLevanto
|
|
81
|
+
|
|
82
|
+
llm = ChatLevanto(target="economy") # model="auto" lets the router pick
|
|
83
|
+
reply = llm.invoke("Summarize this ticket in one sentence: ...")
|
|
84
|
+
reply.response_metadata["model_name"] # the model that answered
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`ChatLevanto` is `ChatOpenAI` pointed at `https://api.levanto.ai/v1`: streaming, tools and `with_structured_output` work as usual. It never reads `OPENAI_API_KEY`.
|
|
88
|
+
|
|
89
|
+
## Development
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
uv venv && uv pip install -e . --group test
|
|
93
|
+
pytest tests/unit_tests
|
|
94
|
+
LEVANTO_API_KEY=... pytest -m live tests/integration_tests
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Docs: https://docs.levanto.ai/integrations/langchain
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# langchain-levanto
|
|
2
|
+
|
|
3
|
+
Levanto for LangChain: Sage decisions and Levanto's LLMs.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install langchain-levanto
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
It reads your key from `LEVANTO_API_KEY`.
|
|
10
|
+
|
|
11
|
+
## Decisions
|
|
12
|
+
|
|
13
|
+
`LevantoDecisionModel` is a LangChain decision model. It answers yes/no (`Noul`), `Choice` and `Score` questions about text, JSON or chat messages, with full probabilities.
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from langchain_core.decisions import Choice, Noul, Score
|
|
17
|
+
from langchain_levanto import LevantoDecisionModel
|
|
18
|
+
|
|
19
|
+
sage = LevantoDecisionModel()
|
|
20
|
+
response = sage.invoke({
|
|
21
|
+
"state": "I was charged twice. Please refund the duplicate today.",
|
|
22
|
+
"questions": {
|
|
23
|
+
"refund": Noul(instructions="Is the customer asking for money back?"),
|
|
24
|
+
"team": Choice(
|
|
25
|
+
instructions="Which team should handle this?",
|
|
26
|
+
criteria={"billing": "Charges and refunds", "technical": "Bugs and outages"},
|
|
27
|
+
),
|
|
28
|
+
"urgency": Score(instructions="How urgent is it?", criteria=["Can wait", "This week", "Today"]),
|
|
29
|
+
},
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
response.nouls["refund"].noul # 0.996
|
|
33
|
+
response.choices["team"].choice # "billing"
|
|
34
|
+
response.scores["urgency"].score # 1.99, from 0 to 2
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Options: `reasoning` (`"off"`, `"auto"`, `"on"`), `grounding`, `timeout` (15 s by default, 60 s with reasoning), `max_retries`. `Box` questions and images aren't supported; for images, call [`POST /decide`](https://docs.levanto.ai/decision-model/quickstart).
|
|
38
|
+
|
|
39
|
+
## Guard and route agents
|
|
40
|
+
|
|
41
|
+
LangChain's agent middleware takes any decision model.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from langchain.agents import create_agent
|
|
45
|
+
from langchain.agents.middleware import AutoModeMiddleware
|
|
46
|
+
|
|
47
|
+
# Sage blocks risky tool calls the user didn't ask for.
|
|
48
|
+
agent = create_agent(
|
|
49
|
+
model,
|
|
50
|
+
tools=[read_file, delete_file],
|
|
51
|
+
middleware=[AutoModeMiddleware(tools=[delete_file], classifier=LevantoDecisionModel())],
|
|
52
|
+
)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`ModelRouterMiddleware(choices=..., instructions=..., classifier=LevantoDecisionModel())` picks a model per run.
|
|
56
|
+
|
|
57
|
+
## LLMs
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from langchain_levanto import ChatLevanto
|
|
61
|
+
|
|
62
|
+
llm = ChatLevanto(target="economy") # model="auto" lets the router pick
|
|
63
|
+
reply = llm.invoke("Summarize this ticket in one sentence: ...")
|
|
64
|
+
reply.response_metadata["model_name"] # the model that answered
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`ChatLevanto` is `ChatOpenAI` pointed at `https://api.levanto.ai/v1`: streaming, tools and `with_structured_output` work as usual. It never reads `OPENAI_API_KEY`.
|
|
68
|
+
|
|
69
|
+
## Development
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
uv venv && uv pip install -e . --group test
|
|
73
|
+
pytest tests/unit_tests
|
|
74
|
+
LEVANTO_API_KEY=... pytest -m live tests/integration_tests
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Docs: https://docs.levanto.ai/integrations/langchain
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Levanto for LangChain: Sage decisions and Levanto's LLMs."""
|
|
2
|
+
|
|
3
|
+
from langchain_levanto._version import __version__
|
|
4
|
+
from langchain_levanto.chat_models import ChatLevanto
|
|
5
|
+
from langchain_levanto.decision_models import LevantoAPIError, LevantoDecisionModel
|
|
6
|
+
|
|
7
|
+
__all__ = ["ChatLevanto", "LevantoAPIError", "LevantoDecisionModel", "__version__"]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
__version__ = version("langchain-levanto")
|
|
5
|
+
except PackageNotFoundError: # pragma: no cover - running from a source checkout
|
|
6
|
+
__version__ = "0.0.0"
|
|
7
|
+
|
|
8
|
+
USER_AGENT = f"langchain-levanto/{__version__}"
|
|
9
|
+
DEFAULT_BASE_URL = "https://api.levanto.ai"
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Levanto's LLMs as a LangChain chat model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
from langchain_core.language_models import LangSmithParams
|
|
9
|
+
from langchain_openai import ChatOpenAI
|
|
10
|
+
from pydantic import Field, model_validator
|
|
11
|
+
from typing_extensions import override
|
|
12
|
+
|
|
13
|
+
from langchain_levanto._version import DEFAULT_BASE_URL, USER_AGENT
|
|
14
|
+
|
|
15
|
+
Target = Literal["economy", "balanced", "quality"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ChatLevanto(ChatOpenAI):
|
|
19
|
+
"""Levanto's LLMs, through the OpenAI-compatible API at `api.levanto.ai/v1`.
|
|
20
|
+
|
|
21
|
+
`model="auto"` (the default) lets the router pick a model per request. Any id from
|
|
22
|
+
`GET /v1/models`, such as `"deepseek/deepseek-v4-flash"`, pins one model. The model
|
|
23
|
+
that answered is in `response.response_metadata["model_name"]`.
|
|
24
|
+
|
|
25
|
+
The key is read from `LEVANTO_API_KEY` when `api_key` is omitted, and the base URL
|
|
26
|
+
from `LEVANTO_BASE_URL` (default `https://api.levanto.ai`). `OPENAI_API_KEY` and
|
|
27
|
+
`OPENAI_BASE_URL` are never used.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from langchain_levanto import ChatLevanto
|
|
31
|
+
|
|
32
|
+
llm = ChatLevanto(target="economy")
|
|
33
|
+
llm.invoke("Summarize this ticket in one sentence: ...")
|
|
34
|
+
```
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
model_name: str = Field(default="auto", alias="model")
|
|
38
|
+
"""`auto` for the router, or a model id from `GET /v1/models`."""
|
|
39
|
+
|
|
40
|
+
target: Target | None = None
|
|
41
|
+
"""The router's spending target. Without it, the key's router setting applies."""
|
|
42
|
+
|
|
43
|
+
routing: dict[str, Any] | None = None
|
|
44
|
+
"""Finer router settings, such as `{"cost_quality_tradeoff": 0}` (0 = best quality,
|
|
45
|
+
10 = cheapest)."""
|
|
46
|
+
|
|
47
|
+
@model_validator(mode="before")
|
|
48
|
+
@classmethod
|
|
49
|
+
def _levanto_defaults(cls, values: Any) -> Any:
|
|
50
|
+
if not isinstance(values, dict):
|
|
51
|
+
return values
|
|
52
|
+
values = dict(values)
|
|
53
|
+
# Accept both the alias and the field name, and never fall back to OPENAI_API_KEY.
|
|
54
|
+
if "openai_api_key" in values:
|
|
55
|
+
values.setdefault("api_key", values.pop("openai_api_key"))
|
|
56
|
+
if values.get("api_key") is None:
|
|
57
|
+
key = os.environ.get("LEVANTO_API_KEY", "").strip()
|
|
58
|
+
if not key:
|
|
59
|
+
msg = "Levanto API key is required. Pass `api_key` or set `LEVANTO_API_KEY`."
|
|
60
|
+
raise ValueError(msg)
|
|
61
|
+
values["api_key"] = key
|
|
62
|
+
|
|
63
|
+
if "openai_api_base" in values:
|
|
64
|
+
values.setdefault("base_url", values.pop("openai_api_base"))
|
|
65
|
+
base = values.get("base_url") or os.environ.get("LEVANTO_BASE_URL", "").strip() or DEFAULT_BASE_URL
|
|
66
|
+
values["base_url"] = _v1(base)
|
|
67
|
+
|
|
68
|
+
values.setdefault("stream_usage", True)
|
|
69
|
+
values.setdefault("use_responses_api", False)
|
|
70
|
+
headers = dict(values.get("default_headers") or {})
|
|
71
|
+
headers.setdefault("User-Agent", USER_AGENT)
|
|
72
|
+
values["default_headers"] = headers
|
|
73
|
+
|
|
74
|
+
extra = dict(values.get("extra_body") or {})
|
|
75
|
+
if values.get("target") is not None:
|
|
76
|
+
extra["target"] = values["target"]
|
|
77
|
+
if values.get("routing") is not None:
|
|
78
|
+
extra["routing"] = values["routing"]
|
|
79
|
+
if extra:
|
|
80
|
+
values["extra_body"] = extra
|
|
81
|
+
return values
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
@override
|
|
85
|
+
def _llm_type(self) -> str:
|
|
86
|
+
return "levanto-chat"
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
@override
|
|
90
|
+
def lc_secrets(self) -> dict[str, str]:
|
|
91
|
+
return {"openai_api_key": "LEVANTO_API_KEY"}
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
@override
|
|
95
|
+
def get_lc_namespace(cls) -> list[str]:
|
|
96
|
+
return ["langchain_levanto", "chat_models"]
|
|
97
|
+
|
|
98
|
+
@override
|
|
99
|
+
def _get_ls_params(self, stop: list[str] | None = None, **kwargs: Any) -> LangSmithParams:
|
|
100
|
+
params = super()._get_ls_params(stop=stop, **kwargs)
|
|
101
|
+
params["ls_provider"] = "levanto"
|
|
102
|
+
return params
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _v1(base: str) -> str:
|
|
106
|
+
base = base.rstrip("/")
|
|
107
|
+
return base if base.endswith("/v1") else f"{base}/v1"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
__all__ = ["ChatLevanto"]
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Levanto Sage as a LangChain decision model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
from langchain_core.decisions import BaseDecisionModel, Box, ClassifierResponse, Question, State
|
|
12
|
+
from langchain_core.messages import BaseMessage, convert_to_openai_messages
|
|
13
|
+
from langchain_core.utils import from_env, secret_from_env
|
|
14
|
+
from pydantic import ConfigDict, Field, JsonValue, SecretStr, field_validator, model_validator
|
|
15
|
+
from typing_extensions import Self, override
|
|
16
|
+
|
|
17
|
+
from langchain_levanto._version import DEFAULT_BASE_URL, USER_AGENT
|
|
18
|
+
|
|
19
|
+
_RETRY_STATUS = {429, 502, 503}
|
|
20
|
+
_MEDIA_TYPES = {"image", "image_url", "file", "audio", "video", "input_image", "input_file"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LevantoAPIError(Exception):
|
|
24
|
+
"""An error response from the Levanto API."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, status_code: int, message: str, code: str | None = None) -> None:
|
|
27
|
+
self.status_code = status_code
|
|
28
|
+
self.code = code
|
|
29
|
+
super().__init__(f"Levanto API error {status_code}{f' ({code})' if code else ''}: {message}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class LevantoDecisionModel(BaseDecisionModel):
|
|
33
|
+
"""Levanto Sage: typed answers about text, JSON or chat messages.
|
|
34
|
+
|
|
35
|
+
Answers `Noul` (yes/no), `Choice` and `Score` questions with full probabilities,
|
|
36
|
+
in about 100–300 ms. Use it directly, or as the `classifier` of LangChain's
|
|
37
|
+
`AutoModeMiddleware` (block risky tool calls) and `ModelRouterMiddleware` (pick a
|
|
38
|
+
model per run).
|
|
39
|
+
|
|
40
|
+
The key is read from `LEVANTO_API_KEY` when `api_key` is omitted, and the base URL
|
|
41
|
+
from `LEVANTO_BASE_URL` (default `https://api.levanto.ai`).
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from langchain_core.decisions import Choice, Noul
|
|
45
|
+
from langchain_levanto import LevantoDecisionModel
|
|
46
|
+
|
|
47
|
+
sage = LevantoDecisionModel()
|
|
48
|
+
response = sage.invoke(
|
|
49
|
+
{
|
|
50
|
+
"state": "I was charged twice. Please refund the duplicate today.",
|
|
51
|
+
"questions": {
|
|
52
|
+
"refund": Noul(instructions="Is the customer asking for money back?"),
|
|
53
|
+
"team": Choice(
|
|
54
|
+
instructions="Which team should handle this?",
|
|
55
|
+
criteria={"billing": "Charges and refunds", "technical": "Bugs"},
|
|
56
|
+
),
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
)
|
|
60
|
+
response.nouls["refund"].noul # 0.997
|
|
61
|
+
response.choices["team"].choice # "billing"
|
|
62
|
+
```
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
model: str = "sage-latest"
|
|
66
|
+
"""`sage-latest` or a pinned Sage model such as `levanto-sage-2`."""
|
|
67
|
+
|
|
68
|
+
api_key: SecretStr = Field(default_factory=secret_from_env("LEVANTO_API_KEY", default=""))
|
|
69
|
+
"""Levanto API key. Defaults to the `LEVANTO_API_KEY` environment variable."""
|
|
70
|
+
|
|
71
|
+
base_url: str = Field(default_factory=from_env("LEVANTO_BASE_URL", default=DEFAULT_BASE_URL))
|
|
72
|
+
"""Defaults to the `LEVANTO_BASE_URL` environment variable, then `https://api.levanto.ai`."""
|
|
73
|
+
|
|
74
|
+
reasoning: Literal["off", "auto", "on"] | None = None
|
|
75
|
+
"""`off` (the API's default), `auto` or `on`. Reasoning answers take several seconds."""
|
|
76
|
+
|
|
77
|
+
grounding: dict[str, JsonValue] | None = None
|
|
78
|
+
"""Search the web before answering: one config, or `{question_id: config}`."""
|
|
79
|
+
|
|
80
|
+
timeout: float | None = Field(default=None, gt=0)
|
|
81
|
+
"""Seconds per request. Defaults to 15, or 60 with reasoning `auto` or `on`."""
|
|
82
|
+
|
|
83
|
+
max_retries: int = Field(default=2, ge=0)
|
|
84
|
+
"""Retries after a connection error, `429`, `502` or `503`."""
|
|
85
|
+
|
|
86
|
+
client: httpx.Client | None = Field(default=None, exclude=True, repr=False)
|
|
87
|
+
"""Optional `httpx.Client`, used as is and never closed by the model."""
|
|
88
|
+
|
|
89
|
+
async_client: httpx.AsyncClient | None = Field(default=None, exclude=True, repr=False)
|
|
90
|
+
"""Optional `httpx.AsyncClient`, used as is and never closed by the model."""
|
|
91
|
+
|
|
92
|
+
model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid", validate_default=True)
|
|
93
|
+
|
|
94
|
+
@field_validator("api_key")
|
|
95
|
+
@classmethod
|
|
96
|
+
def _require_key(cls, api_key: SecretStr) -> SecretStr:
|
|
97
|
+
if not api_key.get_secret_value().strip():
|
|
98
|
+
msg = "Levanto API key is required. Pass `api_key` or set `LEVANTO_API_KEY`."
|
|
99
|
+
raise ValueError(msg)
|
|
100
|
+
return api_key
|
|
101
|
+
|
|
102
|
+
@model_validator(mode="after")
|
|
103
|
+
def _build_clients(self) -> Self:
|
|
104
|
+
timeout = self.timeout or (60.0 if self.reasoning in ("auto", "on") else 15.0)
|
|
105
|
+
if self.client is None:
|
|
106
|
+
self.client = httpx.Client(timeout=timeout)
|
|
107
|
+
if self.async_client is None:
|
|
108
|
+
self.async_client = httpx.AsyncClient(timeout=timeout)
|
|
109
|
+
return self
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
@override
|
|
113
|
+
def is_lc_serializable(cls) -> bool:
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
@classmethod
|
|
117
|
+
@override
|
|
118
|
+
def get_lc_namespace(cls) -> list[str]:
|
|
119
|
+
return ["langchain_levanto", "decision_models"]
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
@override
|
|
123
|
+
def lc_secrets(self) -> dict[str, str]:
|
|
124
|
+
return {"api_key": "LEVANTO_API_KEY"}
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
@override
|
|
128
|
+
def _provider(self) -> str:
|
|
129
|
+
return "levanto"
|
|
130
|
+
|
|
131
|
+
@override
|
|
132
|
+
def _classify(self, state: State, questions: dict[str, Question]) -> ClassifierResponse:
|
|
133
|
+
payload = self._payload(state, questions)
|
|
134
|
+
assert self.client is not None # set by _build_clients
|
|
135
|
+
for attempt in range(self.max_retries + 1):
|
|
136
|
+
try:
|
|
137
|
+
response = self.client.post(self._endpoint, json=payload, headers=self._headers)
|
|
138
|
+
except (httpx.ConnectError, httpx.RemoteProtocolError, httpx.ReadError):
|
|
139
|
+
if attempt == self.max_retries:
|
|
140
|
+
raise
|
|
141
|
+
time.sleep(_backoff(attempt))
|
|
142
|
+
continue
|
|
143
|
+
if response.status_code in _RETRY_STATUS and attempt < self.max_retries:
|
|
144
|
+
time.sleep(_backoff(attempt, response))
|
|
145
|
+
continue
|
|
146
|
+
return _parse(response, questions)
|
|
147
|
+
raise AssertionError("unreachable") # pragma: no cover
|
|
148
|
+
|
|
149
|
+
@override
|
|
150
|
+
async def _aclassify(self, state: State, questions: dict[str, Question]) -> ClassifierResponse:
|
|
151
|
+
payload = self._payload(state, questions)
|
|
152
|
+
assert self.async_client is not None # set by _build_clients
|
|
153
|
+
for attempt in range(self.max_retries + 1):
|
|
154
|
+
try:
|
|
155
|
+
response = await self.async_client.post(self._endpoint, json=payload, headers=self._headers)
|
|
156
|
+
except (httpx.ConnectError, httpx.RemoteProtocolError, httpx.ReadError):
|
|
157
|
+
if attempt == self.max_retries:
|
|
158
|
+
raise
|
|
159
|
+
await asyncio.sleep(_backoff(attempt))
|
|
160
|
+
continue
|
|
161
|
+
if response.status_code in _RETRY_STATUS and attempt < self.max_retries:
|
|
162
|
+
await asyncio.sleep(_backoff(attempt, response))
|
|
163
|
+
continue
|
|
164
|
+
return _parse(response, questions)
|
|
165
|
+
raise AssertionError("unreachable") # pragma: no cover
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def _endpoint(self) -> str:
|
|
169
|
+
return f"{self.base_url.rstrip('/')}/v1/systemone"
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
def _headers(self) -> dict[str, str]:
|
|
173
|
+
return {
|
|
174
|
+
"Authorization": f"Bearer {self.api_key.get_secret_value()}",
|
|
175
|
+
"Content-Type": "application/json",
|
|
176
|
+
"User-Agent": USER_AGENT,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
def _payload(self, state: State, questions: Mapping[str, Question]) -> dict[str, Any]:
|
|
180
|
+
if not questions:
|
|
181
|
+
msg = "Ask at least one question."
|
|
182
|
+
raise ValueError(msg)
|
|
183
|
+
body_questions: dict[str, Any] = {}
|
|
184
|
+
for qid, question in questions.items():
|
|
185
|
+
if isinstance(question, Box):
|
|
186
|
+
msg = f"Levanto doesn't answer Box questions yet (question {qid!r})."
|
|
187
|
+
raise ValueError(msg)
|
|
188
|
+
body_questions[qid] = question.model_dump(mode="json", exclude_none=True)
|
|
189
|
+
body: dict[str, Any] = {
|
|
190
|
+
"model": self.model,
|
|
191
|
+
"state": serialize_state(state),
|
|
192
|
+
"questions": body_questions,
|
|
193
|
+
}
|
|
194
|
+
if _has_media(body):
|
|
195
|
+
msg = (
|
|
196
|
+
"Levanto decision models take text, JSON and chat messages. "
|
|
197
|
+
"For images, call POST /decide: https://docs.levanto.ai/decision-model/quickstart"
|
|
198
|
+
)
|
|
199
|
+
raise ValueError(msg)
|
|
200
|
+
options: dict[str, Any] = {}
|
|
201
|
+
if self.reasoning is not None:
|
|
202
|
+
options["reasoning"] = self.reasoning
|
|
203
|
+
if self.grounding is not None:
|
|
204
|
+
options["grounding"] = self.grounding
|
|
205
|
+
if options:
|
|
206
|
+
body["provider"] = {"options": {"levanto": options}}
|
|
207
|
+
return body
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def serialize_state(state: State) -> JsonValue:
|
|
211
|
+
"""Turn LangChain messages anywhere in the state into `{role, content}` JSON."""
|
|
212
|
+
if state is None or isinstance(state, (bool, int, float)):
|
|
213
|
+
msg = "State must be a string, a JSON object or array, or LangChain messages."
|
|
214
|
+
raise TypeError(msg)
|
|
215
|
+
return _serialize(state)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _serialize(value: Any) -> JsonValue:
|
|
219
|
+
if isinstance(value, BaseMessage):
|
|
220
|
+
return _serialize(convert_to_openai_messages(value))
|
|
221
|
+
if isinstance(value, Mapping):
|
|
222
|
+
if not all(isinstance(k, str) for k in value):
|
|
223
|
+
msg = "State object keys must be strings."
|
|
224
|
+
raise TypeError(msg)
|
|
225
|
+
return {k: _serialize(v) for k, v in value.items()}
|
|
226
|
+
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
|
|
227
|
+
return [_serialize(v) for v in value]
|
|
228
|
+
if value is None or isinstance(value, (str, bool, int, float)):
|
|
229
|
+
return value
|
|
230
|
+
msg = f"Unsupported state value: {type(value).__name__}."
|
|
231
|
+
raise TypeError(msg)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _has_media(value: Any) -> bool:
|
|
235
|
+
if isinstance(value, dict):
|
|
236
|
+
if value.get("type") in _MEDIA_TYPES and any(
|
|
237
|
+
k in value for k in ("base64", "url", "data", "file_id", "image_url", "source_type")
|
|
238
|
+
):
|
|
239
|
+
return True
|
|
240
|
+
return any(_has_media(v) for v in value.values())
|
|
241
|
+
if isinstance(value, list):
|
|
242
|
+
return any(_has_media(v) for v in value)
|
|
243
|
+
return False
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _backoff(attempt: int, response: httpx.Response | None = None) -> float:
|
|
247
|
+
if response is not None:
|
|
248
|
+
retry_after = response.headers.get("retry-after", "")
|
|
249
|
+
try:
|
|
250
|
+
return min(float(retry_after), 10.0)
|
|
251
|
+
except ValueError:
|
|
252
|
+
pass
|
|
253
|
+
return 0.5 * (2**attempt)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _error(response: httpx.Response) -> LevantoAPIError:
|
|
257
|
+
message, code = response.reason_phrase or "request failed", None
|
|
258
|
+
try:
|
|
259
|
+
data = response.json()
|
|
260
|
+
except ValueError:
|
|
261
|
+
data = None
|
|
262
|
+
if isinstance(data, dict):
|
|
263
|
+
detail = data.get("detail")
|
|
264
|
+
if isinstance(detail, str):
|
|
265
|
+
message = detail
|
|
266
|
+
elif isinstance(detail, list):
|
|
267
|
+
message = "; ".join(str(d.get("msg", d)) if isinstance(d, dict) else str(d) for d in detail)
|
|
268
|
+
elif isinstance(data.get("message"), str):
|
|
269
|
+
message = data["message"]
|
|
270
|
+
elif isinstance(data.get("title"), str):
|
|
271
|
+
message = data["title"]
|
|
272
|
+
code = data.get("code") if isinstance(data.get("code"), str) else None
|
|
273
|
+
return LevantoAPIError(response.status_code, message, code)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _parse(response: httpx.Response, questions: Mapping[str, Question]) -> ClassifierResponse:
|
|
277
|
+
if response.status_code >= 400:
|
|
278
|
+
raise _error(response)
|
|
279
|
+
data = response.json()
|
|
280
|
+
raw_answers = data.get("answers") or {}
|
|
281
|
+
answers: dict[str, Any] = {}
|
|
282
|
+
for qid, question in questions.items():
|
|
283
|
+
raw = raw_answers.get(qid)
|
|
284
|
+
if not isinstance(raw, dict):
|
|
285
|
+
msg = f"Levanto returned no answer for question {qid!r}."
|
|
286
|
+
raise LevantoAPIError(response.status_code, msg)
|
|
287
|
+
answer = dict(raw)
|
|
288
|
+
probs = answer.get("probabilities")
|
|
289
|
+
if answer.get("type") in ("choice", "score") and answer.get("confidence") is None and isinstance(probs, dict):
|
|
290
|
+
# The API leaves confidence out on some answers: use the top probability, as it does.
|
|
291
|
+
answer["confidence"] = max(probs.values(), default=0.0)
|
|
292
|
+
if answer.get("type") == "score" and "legend" not in answer:
|
|
293
|
+
answer["legend"] = dict(enumerate(getattr(question, "criteria", [])))
|
|
294
|
+
answers[qid] = answer
|
|
295
|
+
return ClassifierResponse.model_validate(
|
|
296
|
+
{
|
|
297
|
+
"model": data.get("model") or "sage-latest",
|
|
298
|
+
"answers": answers,
|
|
299
|
+
"usage": data.get("usage"),
|
|
300
|
+
"request_id": response.headers.get("x-request-id"),
|
|
301
|
+
}
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
__all__ = ["LevantoAPIError", "LevantoDecisionModel", "serialize_state"]
|
|
File without changes
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-levanto"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Levanto for LangChain: Sage decisions and Levanto's LLMs."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Levanto", email = "marco@levanto.ai" }]
|
|
13
|
+
requires-python = ">=3.11,<4.0"
|
|
14
|
+
dependencies = [
|
|
15
|
+
"langchain-core>=1.8.0,<2.0.0",
|
|
16
|
+
"langchain-openai>=1.1.0,<2.0.0",
|
|
17
|
+
"httpx>=0.27,<1.0",
|
|
18
|
+
]
|
|
19
|
+
keywords = ["langchain", "levanto", "sage", "decision model", "llm", "router"]
|
|
20
|
+
classifiers = [
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"License :: OSI Approved :: MIT License",
|
|
23
|
+
"Operating System :: OS Independent",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://docs.levanto.ai/integrations/langchain"
|
|
28
|
+
Repository = "https://github.com/levantolabs/langchain-levanto"
|
|
29
|
+
Changelog = "https://github.com/levantolabs/langchain-levanto/blob/main/python/CHANGELOG.md"
|
|
30
|
+
|
|
31
|
+
[dependency-groups]
|
|
32
|
+
test = ["pytest>=8", "pytest-asyncio>=0.24", "langchain>=1.5.0,<2.0.0"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["langchain_levanto"]
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.sdist]
|
|
38
|
+
include = ["langchain_levanto", "tests", "README.md", "LICENSE", "CHANGELOG.md"]
|
|
39
|
+
|
|
40
|
+
[tool.pytest.ini_options]
|
|
41
|
+
asyncio_mode = "auto"
|
|
42
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
43
|
+
markers = ["live: calls the real Levanto API (needs LEVANTO_API_KEY)"]
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Live checks against the Levanto API. Run with: LEVANTO_API_KEY=... pytest -m live"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from langchain_core.decisions import Choice, Noul, Score
|
|
7
|
+
from langchain_core.messages import HumanMessage
|
|
8
|
+
from langchain_core.tools import tool
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
|
|
11
|
+
from langchain_levanto import ChatLevanto, LevantoDecisionModel
|
|
12
|
+
|
|
13
|
+
pytestmark = [
|
|
14
|
+
pytest.mark.live,
|
|
15
|
+
pytest.mark.skipif(not os.environ.get("LEVANTO_API_KEY"), reason="needs LEVANTO_API_KEY"),
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_decisions():
|
|
20
|
+
response = LevantoDecisionModel().invoke(
|
|
21
|
+
{
|
|
22
|
+
"state": [HumanMessage("I was charged twice. Please refund the duplicate today!")],
|
|
23
|
+
"questions": {
|
|
24
|
+
"refund": Noul(instructions="Is the customer asking for money back?"),
|
|
25
|
+
"team": Choice(
|
|
26
|
+
instructions="Which team should handle this?",
|
|
27
|
+
criteria={"billing": "Charges and refunds", "technical": "Bugs and outages"},
|
|
28
|
+
),
|
|
29
|
+
"urgency": Score(instructions="How urgent is it?", criteria=["Can wait", "This week", "Today"]),
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
)
|
|
33
|
+
assert response.nouls["refund"].noul > 0.9
|
|
34
|
+
assert response.choices["team"].choice == "billing"
|
|
35
|
+
assert response.scores["urgency"].score > 1.5
|
|
36
|
+
print("decisions", response.nouls["refund"].noul, response.choices["team"].choice, response.scores["urgency"].score)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def test_decisions_async():
|
|
40
|
+
response = await LevantoDecisionModel().ainvoke(
|
|
41
|
+
{"state": "Server is down", "questions": {"bug": Noul(instructions="Is this a technical problem?")}}
|
|
42
|
+
)
|
|
43
|
+
assert response.nouls["bug"].noul > 0.8
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_chat_stream_tools_and_structured_output():
|
|
47
|
+
llm = ChatLevanto(target="economy", timeout=90)
|
|
48
|
+
reply = llm.invoke("Reply with the word ok.")
|
|
49
|
+
assert "ok" in reply.content.lower()
|
|
50
|
+
print("chat", reply.response_metadata["model_name"])
|
|
51
|
+
|
|
52
|
+
chunks = list(llm.stream("Count from 1 to 5, separated by spaces."))
|
|
53
|
+
assert "".join(c.content for c in chunks).strip().startswith("1")
|
|
54
|
+
|
|
55
|
+
@tool
|
|
56
|
+
def weather(city: str) -> str:
|
|
57
|
+
"""Weather for a city."""
|
|
58
|
+
return "21C"
|
|
59
|
+
|
|
60
|
+
call = llm.bind_tools([weather]).invoke("What is the weather in Rome? Use the tool.")
|
|
61
|
+
assert call.tool_calls[0]["name"] == "weather"
|
|
62
|
+
|
|
63
|
+
class City(BaseModel):
|
|
64
|
+
name: str
|
|
65
|
+
population: int
|
|
66
|
+
|
|
67
|
+
city = llm.with_structured_output(City).invoke("Invent a fictional city.")
|
|
68
|
+
assert city.name
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_auto_mode_guard():
|
|
72
|
+
"""Sage blocks a delete the user never asked for, and allows one they authorized."""
|
|
73
|
+
from langchain.agents import create_agent
|
|
74
|
+
from langchain.agents.middleware import AutoModeMiddleware
|
|
75
|
+
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
|
|
76
|
+
from langchain_core.messages import AIMessage
|
|
77
|
+
|
|
78
|
+
class Scripted(FakeMessagesListChatModel):
|
|
79
|
+
def bind_tools(self, tools, **kwargs):
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
executed = []
|
|
83
|
+
|
|
84
|
+
@tool
|
|
85
|
+
def delete_all_files(path: str) -> str:
|
|
86
|
+
"""Delete every file under a path."""
|
|
87
|
+
executed.append(path)
|
|
88
|
+
return "deleted"
|
|
89
|
+
|
|
90
|
+
def run(prompt: str, path: str) -> None:
|
|
91
|
+
model = Scripted(
|
|
92
|
+
responses=[
|
|
93
|
+
AIMessage("", tool_calls=[{"name": "delete_all_files", "args": {"path": path}, "id": "t1"}]),
|
|
94
|
+
AIMessage("done"),
|
|
95
|
+
]
|
|
96
|
+
)
|
|
97
|
+
guard = AutoModeMiddleware(tools=[delete_all_files], classifier=LevantoDecisionModel())
|
|
98
|
+
create_agent(model, tools=[delete_all_files], middleware=[guard]).invoke({"messages": [HumanMessage(prompt)]})
|
|
99
|
+
|
|
100
|
+
run("Summarize notes.txt for me.", "/")
|
|
101
|
+
assert executed == []
|
|
102
|
+
run("Delete every file under /tmp/scratch-test, I authorize it.", "/tmp/scratch-test")
|
|
103
|
+
assert executed == ["/tmp/scratch-test"]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_model_router():
|
|
107
|
+
from langchain.agents import create_agent
|
|
108
|
+
from langchain.agents.middleware import ModelRouterMiddleware
|
|
109
|
+
from langchain.agents.middleware.model_router import ModelChoice
|
|
110
|
+
|
|
111
|
+
router = ModelRouterMiddleware(
|
|
112
|
+
choices={
|
|
113
|
+
"fast": ModelChoice(model=ChatLevanto(model="deepseek/deepseek-v4-flash", timeout=90), criteria="Simple, well-scoped tasks."),
|
|
114
|
+
"strong": ModelChoice(model=ChatLevanto(target="quality", timeout=90), criteria="Hard, multi-step tasks."),
|
|
115
|
+
},
|
|
116
|
+
instructions="Choose the least costly model suited to the task.",
|
|
117
|
+
classifier=LevantoDecisionModel(),
|
|
118
|
+
)
|
|
119
|
+
agent = create_agent(ChatLevanto(timeout=90), middleware=[router])
|
|
120
|
+
result = agent.invoke({"messages": [HumanMessage("Reply with the word ok.")]})
|
|
121
|
+
assert "ok" in result["messages"][-1].content.lower()
|
|
File without changes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
from langchain_levanto import ChatLevanto
|
|
8
|
+
|
|
9
|
+
KEY = "lv_live_test"
|
|
10
|
+
|
|
11
|
+
COMPLETION = {
|
|
12
|
+
"id": "c1",
|
|
13
|
+
"object": "chat.completion",
|
|
14
|
+
"created": 1764000000,
|
|
15
|
+
"model": "deepseek/deepseek-v4-flash",
|
|
16
|
+
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
|
|
17
|
+
"usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def chat(handler, **kwargs) -> ChatLevanto:
|
|
22
|
+
return ChatLevanto(api_key=KEY, http_client=httpx.Client(transport=httpx.MockTransport(handler)), **kwargs)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def recorder(body=COMPLETION):
|
|
26
|
+
calls = []
|
|
27
|
+
|
|
28
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
29
|
+
calls.append(request)
|
|
30
|
+
return httpx.Response(200, json=body)
|
|
31
|
+
|
|
32
|
+
return handler, calls
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_defaults_and_router_fields():
|
|
36
|
+
handler, calls = recorder()
|
|
37
|
+
result = chat(handler, target="economy", routing={"cost_quality_tradeoff": 3}).invoke("Reply with ok.")
|
|
38
|
+
request = calls[0]
|
|
39
|
+
assert str(request.url) == "https://api.levanto.ai/v1/chat/completions"
|
|
40
|
+
assert request.headers["authorization"] == f"Bearer {KEY}"
|
|
41
|
+
assert request.headers["user-agent"].startswith("langchain-levanto/")
|
|
42
|
+
body = json.loads(request.content)
|
|
43
|
+
assert body["model"] == "auto"
|
|
44
|
+
assert body["target"] == "economy"
|
|
45
|
+
assert body["routing"] == {"cost_quality_tradeoff": 3}
|
|
46
|
+
assert result.content == "ok"
|
|
47
|
+
assert result.response_metadata["model_name"] == "deepseek/deepseek-v4-flash"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_never_uses_openai_env(monkeypatch):
|
|
51
|
+
monkeypatch.delenv("LEVANTO_API_KEY", raising=False)
|
|
52
|
+
monkeypatch.setenv("OPENAI_API_KEY", "sk-openai")
|
|
53
|
+
monkeypatch.setenv("OPENAI_BASE_URL", "https://openai.example/v1")
|
|
54
|
+
with pytest.raises(ValueError, match="LEVANTO_API_KEY"):
|
|
55
|
+
ChatLevanto()
|
|
56
|
+
|
|
57
|
+
monkeypatch.setenv("LEVANTO_API_KEY", "lv_live_env")
|
|
58
|
+
monkeypatch.setenv("LEVANTO_BASE_URL", "https://example.test")
|
|
59
|
+
handler, calls = recorder()
|
|
60
|
+
ChatLevanto(http_client=httpx.Client(transport=httpx.MockTransport(handler))).invoke("x")
|
|
61
|
+
assert calls[0].headers["authorization"] == "Bearer lv_live_env"
|
|
62
|
+
assert str(calls[0].url) == "https://example.test/v1/chat/completions"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_pinned_model_and_structured_output():
|
|
66
|
+
class City(BaseModel):
|
|
67
|
+
name: str
|
|
68
|
+
|
|
69
|
+
body = {**COMPLETION, "choices": [{**COMPLETION["choices"][0], "message": {"role": "assistant", "content": '{"name":"Rome"}'}}]}
|
|
70
|
+
handler, calls = recorder(body)
|
|
71
|
+
llm = chat(handler, model="deepseek/deepseek-v4-flash")
|
|
72
|
+
city = llm.with_structured_output(City).invoke("A city.")
|
|
73
|
+
sent = json.loads(calls[0].content)
|
|
74
|
+
assert sent["model"] == "deepseek/deepseek-v4-flash"
|
|
75
|
+
assert sent["response_format"]["type"] == "json_schema"
|
|
76
|
+
assert city == City(name="Rome")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_ls_params_and_secrets():
|
|
80
|
+
handler, _ = recorder()
|
|
81
|
+
llm = chat(handler)
|
|
82
|
+
assert llm._get_ls_params()["ls_provider"] == "levanto"
|
|
83
|
+
assert llm._llm_type == "levanto-chat"
|
|
84
|
+
from langchain_core.load import dumps
|
|
85
|
+
|
|
86
|
+
assert KEY not in dumps(llm)
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
from langchain_core.decisions import Box, Choice, Noul, NoulCriteria, Score
|
|
6
|
+
from langchain_core.messages import AIMessage, HumanMessage
|
|
7
|
+
|
|
8
|
+
from langchain_levanto import LevantoAPIError, LevantoDecisionModel
|
|
9
|
+
|
|
10
|
+
KEY = "lv_live_test"
|
|
11
|
+
|
|
12
|
+
ANSWERS = {
|
|
13
|
+
"model": "levanto-sage-2",
|
|
14
|
+
"answers": {
|
|
15
|
+
"refund": {"type": "noul", "noul": 0.997, "confidence": 0.997},
|
|
16
|
+
"team": {
|
|
17
|
+
"type": "choice",
|
|
18
|
+
"choice": "billing",
|
|
19
|
+
"probabilities": {"billing": 0.95, "technical": 0.05},
|
|
20
|
+
},
|
|
21
|
+
"anger": {
|
|
22
|
+
"type": "score",
|
|
23
|
+
"score": 1.69,
|
|
24
|
+
"confidence": 0.70,
|
|
25
|
+
"legend": {"0": "Calm", "1": "Annoyed", "2": "Furious"},
|
|
26
|
+
"probabilities": {"0": 0.01, "1": 0.29, "2": 0.70},
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
"usage": {"input_tokens": 239, "output_tokens": 0},
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
QUESTIONS = {
|
|
33
|
+
"refund": Noul(instructions="Money back?", criteria=NoulCriteria(true="Asks for a refund")),
|
|
34
|
+
"team": Choice(instructions="Which team?", criteria={"billing": "Charges", "technical": "Bugs"}),
|
|
35
|
+
"anger": Score(instructions="How angry?", criteria=["Calm", "Annoyed", "Furious"]),
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def recorder(responses):
|
|
40
|
+
calls = []
|
|
41
|
+
queue = list(responses)
|
|
42
|
+
|
|
43
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
44
|
+
calls.append(request)
|
|
45
|
+
item = queue.pop(0) if len(queue) > 1 else queue[0]
|
|
46
|
+
if isinstance(item, Exception):
|
|
47
|
+
raise item
|
|
48
|
+
status, body, headers = item if len(item) == 3 else (*item, {})
|
|
49
|
+
return httpx.Response(status, json=body, headers=headers)
|
|
50
|
+
|
|
51
|
+
return handler, calls
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def model(handler, **kwargs) -> LevantoDecisionModel:
|
|
55
|
+
transport = httpx.MockTransport(handler)
|
|
56
|
+
return LevantoDecisionModel(
|
|
57
|
+
api_key=KEY,
|
|
58
|
+
client=httpx.Client(transport=transport),
|
|
59
|
+
async_client=httpx.AsyncClient(transport=transport),
|
|
60
|
+
**kwargs,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_request_and_answers():
|
|
65
|
+
handler, calls = recorder([(200, ANSWERS, {"x-request-id": "req_1"})])
|
|
66
|
+
sage = model(handler, reasoning="auto")
|
|
67
|
+
state = [HumanMessage("I was charged twice, refund me!"), AIMessage("Let me check.")]
|
|
68
|
+
response = sage.invoke({"state": state, "questions": QUESTIONS})
|
|
69
|
+
|
|
70
|
+
request = calls[0]
|
|
71
|
+
assert str(request.url) == "https://api.levanto.ai/v1/systemone"
|
|
72
|
+
assert request.headers["authorization"] == f"Bearer {KEY}"
|
|
73
|
+
assert request.headers["user-agent"].startswith("langchain-levanto/")
|
|
74
|
+
body = json.loads(request.content)
|
|
75
|
+
assert body["model"] == "sage-latest"
|
|
76
|
+
assert body["state"] == [
|
|
77
|
+
{"role": "user", "content": "I was charged twice, refund me!"},
|
|
78
|
+
{"role": "assistant", "content": "Let me check."},
|
|
79
|
+
]
|
|
80
|
+
assert body["questions"]["refund"] == {
|
|
81
|
+
"type": "noul",
|
|
82
|
+
"instructions": "Money back?",
|
|
83
|
+
"criteria": {"true": "Asks for a refund"},
|
|
84
|
+
}
|
|
85
|
+
assert body["questions"]["anger"]["criteria"] == ["Calm", "Annoyed", "Furious"]
|
|
86
|
+
assert body["provider"] == {"options": {"levanto": {"reasoning": "auto"}}}
|
|
87
|
+
|
|
88
|
+
assert response.model == "levanto-sage-2"
|
|
89
|
+
assert response.request_id == "req_1"
|
|
90
|
+
assert response.nouls["refund"].noul == 0.997
|
|
91
|
+
# Missing confidence falls back to the top probability.
|
|
92
|
+
assert response.choices["team"].choice == "billing"
|
|
93
|
+
assert response.choices["team"].confidence == 0.95
|
|
94
|
+
assert response.scores["anger"].probabilities == {0: 0.01, 1: 0.29, 2: 0.70}
|
|
95
|
+
assert response.scores["anger"].legend[2] == "Furious"
|
|
96
|
+
assert response.usage["total_tokens"] == 239
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def test_async_and_retry_after_503():
|
|
100
|
+
handler, calls = recorder([(503, {"detail": "busy"}, {"retry-after": "0"}), (200, ANSWERS)])
|
|
101
|
+
sage = model(handler)
|
|
102
|
+
response = await sage.ainvoke({"state": "refund please", "questions": {"refund": QUESTIONS["refund"]}})
|
|
103
|
+
assert len(calls) == 2
|
|
104
|
+
assert response.nouls["refund"].noul == 0.997
|
|
105
|
+
assert "provider" not in json.loads(calls[0].content)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_retries_a_dropped_connection_then_gives_up():
|
|
109
|
+
handler, calls = recorder([httpx.ConnectError("reset")])
|
|
110
|
+
sage = model(handler, max_retries=1)
|
|
111
|
+
with pytest.raises(httpx.ConnectError):
|
|
112
|
+
sage.invoke({"state": "x", "questions": {"refund": QUESTIONS["refund"]}})
|
|
113
|
+
assert len(calls) == 2
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_error_messages():
|
|
117
|
+
detail = [{"loc": ["body", "questions"], "msg": "score levels can't be null"}]
|
|
118
|
+
handler, _ = recorder([(422, {"detail": detail})])
|
|
119
|
+
with pytest.raises(LevantoAPIError, match="score levels can't be null") as err:
|
|
120
|
+
model(handler).invoke({"state": "x", "questions": {"refund": QUESTIONS["refund"]}})
|
|
121
|
+
assert err.value.status_code == 422
|
|
122
|
+
|
|
123
|
+
handler, _ = recorder([(402, {"title": "Payment required", "code": "payment_required"})])
|
|
124
|
+
with pytest.raises(LevantoAPIError, match=r"402 \(payment_required\)"):
|
|
125
|
+
model(handler).invoke({"state": "x", "questions": {"refund": QUESTIONS["refund"]}})
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_rejects_box_images_and_missing_answers():
|
|
129
|
+
handler, calls = recorder([(200, ANSWERS)])
|
|
130
|
+
sage = model(handler)
|
|
131
|
+
with pytest.raises(ValueError, match="Box"):
|
|
132
|
+
sage.invoke({"state": "x", "questions": {"where": Box(instructions="Find the logo")}})
|
|
133
|
+
image = HumanMessage(content=[{"type": "image", "base64": "AAAA", "mime_type": "image/png"}])
|
|
134
|
+
with pytest.raises(ValueError, match="POST /decide"):
|
|
135
|
+
sage.invoke({"state": [image], "questions": {"refund": QUESTIONS["refund"]}})
|
|
136
|
+
assert calls == []
|
|
137
|
+
with pytest.raises(LevantoAPIError, match="no answer"):
|
|
138
|
+
sage.invoke({"state": "x", "questions": {"other": QUESTIONS["refund"]}})
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_key_from_env(monkeypatch):
|
|
142
|
+
monkeypatch.setenv("LEVANTO_API_KEY", "lv_live_env")
|
|
143
|
+
monkeypatch.setenv("LEVANTO_BASE_URL", "https://example.test/")
|
|
144
|
+
handler, calls = recorder([(200, ANSWERS)])
|
|
145
|
+
transport = httpx.MockTransport(handler)
|
|
146
|
+
LevantoDecisionModel(client=httpx.Client(transport=transport)).invoke(
|
|
147
|
+
{"state": "x", "questions": {"refund": QUESTIONS["refund"]}}
|
|
148
|
+
)
|
|
149
|
+
assert calls[0].headers["authorization"] == "Bearer lv_live_env"
|
|
150
|
+
assert str(calls[0].url) == "https://example.test/v1/systemone"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_missing_key(monkeypatch):
|
|
154
|
+
monkeypatch.delenv("LEVANTO_API_KEY", raising=False)
|
|
155
|
+
with pytest.raises(ValueError, match="LEVANTO_API_KEY"):
|
|
156
|
+
LevantoDecisionModel()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def test_key_is_not_serialized():
|
|
160
|
+
handler, _ = recorder([(200, ANSWERS)])
|
|
161
|
+
from langchain_core.load import dumps
|
|
162
|
+
|
|
163
|
+
assert KEY not in dumps(model(handler))
|