langchain-levanto 0.1.0__py3-none-any.whl
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/__init__.py +7 -0
- langchain_levanto/_version.py +9 -0
- langchain_levanto/chat_models.py +110 -0
- langchain_levanto/decision_models.py +305 -0
- langchain_levanto/py.typed +0 -0
- langchain_levanto-0.1.0.dist-info/METADATA +97 -0
- langchain_levanto-0.1.0.dist-info/RECORD +9 -0
- langchain_levanto-0.1.0.dist-info/WHEEL +4 -0
- langchain_levanto-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -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,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,9 @@
|
|
|
1
|
+
langchain_levanto/__init__.py,sha256=DRqoJJpm8hcahaEqI_roWXuzxdS3BQojNeVzYR3w5XA,339
|
|
2
|
+
langchain_levanto/_version.py,sha256=Is7xKHDj7K23mzg06ltphGSKEK-_IxpLQYFTAao_8vU,315
|
|
3
|
+
langchain_levanto/chat_models.py,sha256=P6I1fwVijzupROJ2i8zLUh0kNzvQza-54tHVmaUWLrQ,3851
|
|
4
|
+
langchain_levanto/decision_models.py,sha256=pN8wQF3RoMu0y3gdgKYOXGEV5ac2vr8Hb8x5vIIUa0Y,12388
|
|
5
|
+
langchain_levanto/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
langchain_levanto-0.1.0.dist-info/METADATA,sha256=AQx6q_BCFj5PVHbY2qYGyWghvxMFeDvrUkVIQeyU9gs,3446
|
|
7
|
+
langchain_levanto-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
langchain_levanto-0.1.0.dist-info/licenses/LICENSE,sha256=bazsDucEYycOO-tJiOIfuYmtDiMscBehFmD3tmRopNg,1064
|
|
9
|
+
langchain_levanto-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|