langchain-llama-cpp 0.1.0__tar.gz → 0.3.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_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/PKG-INFO +54 -20
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/README.md +52 -17
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/pyproject.toml +3 -4
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/pyproject.toml.orig +3 -4
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/_wire.py +8 -5
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/chat_models.py +271 -43
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/LICENSE +0 -0
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/__init__.py +0 -0
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/content_blocks.py +0 -0
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/exceptions.py +0 -0
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/py.typed +0 -0
- {langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: langchain-llama-cpp
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: An integration package connecting llama.cpp's llama-server and LangChain, with reasoning, timings, structured output and tool calling
|
|
5
5
|
Keywords: langchain,llama.cpp,llama-server,llama-swap,llm,local-llm,chat-model
|
|
6
6
|
Author: Bharathan Mudaliar
|
|
@@ -10,7 +10,6 @@ License-File: LICENSE
|
|
|
10
10
|
Classifier: Development Status :: 3 - Alpha
|
|
11
11
|
Classifier: Intended Audience :: Developers
|
|
12
12
|
Classifier: Programming Language :: Python :: 3
|
|
13
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
14
13
|
Classifier: Programming Language :: Python :: 3.11
|
|
15
14
|
Classifier: Programming Language :: Python :: 3.12
|
|
16
15
|
Classifier: Programming Language :: Python :: 3.13
|
|
@@ -19,7 +18,7 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
|
19
18
|
Classifier: Typing :: Typed
|
|
20
19
|
Requires-Dist: httpx>=0.27,<1
|
|
21
20
|
Requires-Dist: langchain-core>=1.6,<2
|
|
22
|
-
Requires-Python: >=3.
|
|
21
|
+
Requires-Python: >=3.11
|
|
23
22
|
Project-URL: Repository, https://github.com/bharat029/langchain-llama-cpp
|
|
24
23
|
Project-URL: Issues, https://github.com/bharat029/langchain-llama-cpp/issues
|
|
25
24
|
Description-Content-Type: text/markdown
|
|
@@ -37,8 +36,6 @@ directly, so nothing llama-server sends back is lost on the way.
|
|
|
37
36
|
that `ChatOpenAI` drops or gets wrong:
|
|
38
37
|
|
|
39
38
|
- it drops `reasoning_content` (the model's thinking) and llama-server's `timings`;
|
|
40
|
-
- it sends a named `tool_choice` as an object, which llama-server silently turns
|
|
41
|
-
into `"auto"`;
|
|
42
39
|
- it can't send llama.cpp's own sampling fields (`top_k`, `min_p`, `samplers`,
|
|
43
40
|
DRY, XTC, ...) as typed parameters.
|
|
44
41
|
|
|
@@ -48,14 +45,18 @@ that `ChatOpenAI` drops or gets wrong:
|
|
|
48
45
|
pip install langchain-llama-cpp
|
|
49
46
|
```
|
|
50
47
|
|
|
51
|
-
or `uv add langchain-llama-cpp`. Python 3.
|
|
48
|
+
or `uv add langchain-llama-cpp`. Python 3.11+.
|
|
52
49
|
|
|
53
50
|
## Tested setup
|
|
54
51
|
|
|
55
52
|
- **llama-swap** in front of llama-server. `model` is the llama-swap entry to
|
|
56
53
|
use. A bare llama-server (no llama-swap) is not tested yet.
|
|
57
|
-
-
|
|
58
|
-
langchain-core 1.
|
|
54
|
+
- Live integration tests: gemma 4, thinking off and on. Last full run on
|
|
55
|
+
llama.cpp v1.1.0 (build b12774) with langchain-core 1.9.0 (2026-12-03).
|
|
56
|
+
Qwen3.6 and gpt-oss were tested on llama-server b11429 with langchain-core
|
|
57
|
+
1.6, and are no longer in the suite.
|
|
58
|
+
- Request fields and reply shapes follow the llama.cpp source of the latest
|
|
59
|
+
release, **v1.1.0** (build b12774).
|
|
59
60
|
|
|
60
61
|
## Quick start
|
|
61
62
|
|
|
@@ -131,10 +132,15 @@ msg = llm_with_tools.invoke("What's the weather in Paris?")
|
|
|
131
132
|
msg.tool_calls # [{'name': 'get_weather', 'args': {'city': 'Paris'}, 'id': '...', ...}]
|
|
132
133
|
```
|
|
133
134
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
135
|
+
`tool_choice` takes `"auto"`, `"none"`, `"required"` (also `"any"` or `True`),
|
|
136
|
+
or a tool's name. A name is sent as OpenAI's object form,
|
|
137
|
+
`{"type": "function", "function": {"name": ...}}`, with every bound tool still
|
|
138
|
+
in `tools`. llama.cpp v1.1.0 and later then require a tool call, limited to the
|
|
139
|
+
named tool on the generic chat handler; the gemma4, qwen3-coder and gpt-oss
|
|
140
|
+
handlers still accept any bound tool. Older servers ignore the object and run
|
|
141
|
+
with `"auto"`. OpenAI's `{"type": "allowed_tools", ...}` form is checked (mode
|
|
142
|
+
`auto` or `required`, bound tool names) and sent unchanged; v1.1.0 limits the
|
|
143
|
+
model to the listed tools on the same terms.
|
|
138
144
|
|
|
139
145
|
### Structured output
|
|
140
146
|
|
|
@@ -164,9 +170,35 @@ sees the schema's field descriptions: asked for an age described as "in months",
|
|
|
164
170
|
it fills in years. Pass `include_format_instructions=True` with `json_schema` or
|
|
165
171
|
`json_mode` to add the schema to the system message.
|
|
166
172
|
|
|
173
|
+
### Model profile
|
|
174
|
+
|
|
175
|
+
At construction, `profile` is filled from the server's `/props`
|
|
176
|
+
(`/upstream/<model>/props` behind llama-swap, which starts the entry; `/props`
|
|
177
|
+
on a plain llama-server):
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
ChatLlama(model="gemma").profile
|
|
181
|
+
# {'text_inputs': True, 'max_input_tokens': 262144, 'image_inputs': False,
|
|
182
|
+
# 'audio_inputs': False, 'video_inputs': False, 'tool_calling': True}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`max_input_tokens` is the per-slot context window (`n_ctx`), which LangChain and
|
|
186
|
+
Deep Agents use to size things such as summarization. It's fetched once per
|
|
187
|
+
`(base_url, model)` per process. If the server can't be reached, `profile` stays
|
|
188
|
+
`None`. Pass `profile=` to set your own, or `fetch_profile=False` to skip the
|
|
189
|
+
request. The request uses a separate client, not your `http_client`, which is
|
|
190
|
+
used only for chat requests.
|
|
191
|
+
|
|
192
|
+
`structured_output` is deliberately not set, so `create_agent` uses
|
|
193
|
+
`ToolStrategy` for a `response_format`. llama-server can't combine `tools` with
|
|
194
|
+
a `json_schema` `response_format`. The response-format grammar replaces the
|
|
195
|
+
tool-call grammar, so the model answers in JSON straight away and never calls a
|
|
196
|
+
tool. With Qwen-style templates, v0.9.0 fails the request instead, with
|
|
197
|
+
"failed to parse grammar" (fixed in v1.0.0).
|
|
198
|
+
|
|
167
199
|
### Request parameters
|
|
168
200
|
|
|
169
|
-
Every field `/v1/chat/completions` accepts in
|
|
201
|
+
Every field `/v1/chat/completions` accepts in v1.1.0 is a typed parameter:
|
|
170
202
|
`temperature`, `top_k`, `top_p`, `min_p`, `samplers`, `repeat_penalty`, the DRY
|
|
171
203
|
and XTC samplers, `grammar`, `json_schema`, `reasoning_budget_tokens`,
|
|
172
204
|
`cache_prompt`, `id_slot`, `lora` and more. Set them on the model or per call:
|
|
@@ -213,13 +245,15 @@ seconds and defaults to `None` (no timeout), since local generation can be slow.
|
|
|
213
245
|
models lets the model write text before the call and won't let it stop
|
|
214
246
|
without one. A model that doesn't want a tool keeps writing until
|
|
215
247
|
`max_tokens`, and there's no tool call. This is
|
|
216
|
-
[ggml-org/llama.cpp#27217](https://github.com/ggml-org/llama.cpp/issues/27217)
|
|
217
|
-
keep `max_tokens` set.
|
|
218
|
-
- **A named `tool_choice`**
|
|
248
|
+
[ggml-org/llama.cpp#27217](https://github.com/ggml-org/llama.cpp/issues/27217)
|
|
249
|
+
(closed as stale without a fix); keep `max_tokens` set.
|
|
250
|
+
- **A named `tool_choice`** needs llama.cpp v1.1.0 or later, and Gemma 4,
|
|
251
|
+
Qwen3.5/3.6 and gpt-oss may still call another bound tool (see Tool calling).
|
|
219
252
|
- **JSON schema bounds on numbers** (`minimum`, `maximum`, `multipleOf` on
|
|
220
253
|
`number`) aren't enforced by llama-server's grammar. Integer bounds are.
|
|
221
254
|
- **Bare llama-server** (without llama-swap) isn't tested; `get_server_defaults`
|
|
222
|
-
needs llama-swap's `/upstream/<model>/props
|
|
255
|
+
needs llama-swap's `/upstream/<model>/props` (the profile falls back to `/props`).
|
|
256
|
+
- **Tools and `response_format` together** give no tool calls (see Model profile).
|
|
223
257
|
|
|
224
258
|
## Development
|
|
225
259
|
|
|
@@ -232,9 +266,9 @@ uv run pytest tests/unit_tests # offline
|
|
|
232
266
|
uv run ruff check && uv run ruff format --check && uv run pyright
|
|
233
267
|
```
|
|
234
268
|
|
|
235
|
-
The integration tests (LangChain's standard `langchain-tests` suite, on
|
|
236
|
-
|
|
237
|
-
set `LLAMA_BASE_URL`, then:
|
|
269
|
+
The integration tests (LangChain's standard `langchain-tests` suite, on Gemma 4
|
|
270
|
+
with thinking off and on) need a llama-swap server with a `gemma` entry. Copy
|
|
271
|
+
`.env.example` to `.env` and set `LLAMA_BASE_URL`, then:
|
|
238
272
|
|
|
239
273
|
```bash
|
|
240
274
|
uv run --env-file .env pytest tests/integration_tests
|
|
@@ -11,8 +11,6 @@ directly, so nothing llama-server sends back is lost on the way.
|
|
|
11
11
|
that `ChatOpenAI` drops or gets wrong:
|
|
12
12
|
|
|
13
13
|
- it drops `reasoning_content` (the model's thinking) and llama-server's `timings`;
|
|
14
|
-
- it sends a named `tool_choice` as an object, which llama-server silently turns
|
|
15
|
-
into `"auto"`;
|
|
16
14
|
- it can't send llama.cpp's own sampling fields (`top_k`, `min_p`, `samplers`,
|
|
17
15
|
DRY, XTC, ...) as typed parameters.
|
|
18
16
|
|
|
@@ -22,14 +20,18 @@ that `ChatOpenAI` drops or gets wrong:
|
|
|
22
20
|
pip install langchain-llama-cpp
|
|
23
21
|
```
|
|
24
22
|
|
|
25
|
-
or `uv add langchain-llama-cpp`. Python 3.
|
|
23
|
+
or `uv add langchain-llama-cpp`. Python 3.11+.
|
|
26
24
|
|
|
27
25
|
## Tested setup
|
|
28
26
|
|
|
29
27
|
- **llama-swap** in front of llama-server. `model` is the llama-swap entry to
|
|
30
28
|
use. A bare llama-server (no llama-swap) is not tested yet.
|
|
31
|
-
-
|
|
32
|
-
langchain-core 1.
|
|
29
|
+
- Live integration tests: gemma 4, thinking off and on. Last full run on
|
|
30
|
+
llama.cpp v1.1.0 (build b12774) with langchain-core 1.9.0 (2026-12-03).
|
|
31
|
+
Qwen3.6 and gpt-oss were tested on llama-server b11429 with langchain-core
|
|
32
|
+
1.6, and are no longer in the suite.
|
|
33
|
+
- Request fields and reply shapes follow the llama.cpp source of the latest
|
|
34
|
+
release, **v1.1.0** (build b12774).
|
|
33
35
|
|
|
34
36
|
## Quick start
|
|
35
37
|
|
|
@@ -105,10 +107,15 @@ msg = llm_with_tools.invoke("What's the weather in Paris?")
|
|
|
105
107
|
msg.tool_calls # [{'name': 'get_weather', 'args': {'city': 'Paris'}, 'id': '...', ...}]
|
|
106
108
|
```
|
|
107
109
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
110
|
+
`tool_choice` takes `"auto"`, `"none"`, `"required"` (also `"any"` or `True`),
|
|
111
|
+
or a tool's name. A name is sent as OpenAI's object form,
|
|
112
|
+
`{"type": "function", "function": {"name": ...}}`, with every bound tool still
|
|
113
|
+
in `tools`. llama.cpp v1.1.0 and later then require a tool call, limited to the
|
|
114
|
+
named tool on the generic chat handler; the gemma4, qwen3-coder and gpt-oss
|
|
115
|
+
handlers still accept any bound tool. Older servers ignore the object and run
|
|
116
|
+
with `"auto"`. OpenAI's `{"type": "allowed_tools", ...}` form is checked (mode
|
|
117
|
+
`auto` or `required`, bound tool names) and sent unchanged; v1.1.0 limits the
|
|
118
|
+
model to the listed tools on the same terms.
|
|
112
119
|
|
|
113
120
|
### Structured output
|
|
114
121
|
|
|
@@ -138,9 +145,35 @@ sees the schema's field descriptions: asked for an age described as "in months",
|
|
|
138
145
|
it fills in years. Pass `include_format_instructions=True` with `json_schema` or
|
|
139
146
|
`json_mode` to add the schema to the system message.
|
|
140
147
|
|
|
148
|
+
### Model profile
|
|
149
|
+
|
|
150
|
+
At construction, `profile` is filled from the server's `/props`
|
|
151
|
+
(`/upstream/<model>/props` behind llama-swap, which starts the entry; `/props`
|
|
152
|
+
on a plain llama-server):
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
ChatLlama(model="gemma").profile
|
|
156
|
+
# {'text_inputs': True, 'max_input_tokens': 262144, 'image_inputs': False,
|
|
157
|
+
# 'audio_inputs': False, 'video_inputs': False, 'tool_calling': True}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`max_input_tokens` is the per-slot context window (`n_ctx`), which LangChain and
|
|
161
|
+
Deep Agents use to size things such as summarization. It's fetched once per
|
|
162
|
+
`(base_url, model)` per process. If the server can't be reached, `profile` stays
|
|
163
|
+
`None`. Pass `profile=` to set your own, or `fetch_profile=False` to skip the
|
|
164
|
+
request. The request uses a separate client, not your `http_client`, which is
|
|
165
|
+
used only for chat requests.
|
|
166
|
+
|
|
167
|
+
`structured_output` is deliberately not set, so `create_agent` uses
|
|
168
|
+
`ToolStrategy` for a `response_format`. llama-server can't combine `tools` with
|
|
169
|
+
a `json_schema` `response_format`. The response-format grammar replaces the
|
|
170
|
+
tool-call grammar, so the model answers in JSON straight away and never calls a
|
|
171
|
+
tool. With Qwen-style templates, v0.9.0 fails the request instead, with
|
|
172
|
+
"failed to parse grammar" (fixed in v1.0.0).
|
|
173
|
+
|
|
141
174
|
### Request parameters
|
|
142
175
|
|
|
143
|
-
Every field `/v1/chat/completions` accepts in
|
|
176
|
+
Every field `/v1/chat/completions` accepts in v1.1.0 is a typed parameter:
|
|
144
177
|
`temperature`, `top_k`, `top_p`, `min_p`, `samplers`, `repeat_penalty`, the DRY
|
|
145
178
|
and XTC samplers, `grammar`, `json_schema`, `reasoning_budget_tokens`,
|
|
146
179
|
`cache_prompt`, `id_slot`, `lora` and more. Set them on the model or per call:
|
|
@@ -187,13 +220,15 @@ seconds and defaults to `None` (no timeout), since local generation can be slow.
|
|
|
187
220
|
models lets the model write text before the call and won't let it stop
|
|
188
221
|
without one. A model that doesn't want a tool keeps writing until
|
|
189
222
|
`max_tokens`, and there's no tool call. This is
|
|
190
|
-
[ggml-org/llama.cpp#27217](https://github.com/ggml-org/llama.cpp/issues/27217)
|
|
191
|
-
keep `max_tokens` set.
|
|
192
|
-
- **A named `tool_choice`**
|
|
223
|
+
[ggml-org/llama.cpp#27217](https://github.com/ggml-org/llama.cpp/issues/27217)
|
|
224
|
+
(closed as stale without a fix); keep `max_tokens` set.
|
|
225
|
+
- **A named `tool_choice`** needs llama.cpp v1.1.0 or later, and Gemma 4,
|
|
226
|
+
Qwen3.5/3.6 and gpt-oss may still call another bound tool (see Tool calling).
|
|
193
227
|
- **JSON schema bounds on numbers** (`minimum`, `maximum`, `multipleOf` on
|
|
194
228
|
`number`) aren't enforced by llama-server's grammar. Integer bounds are.
|
|
195
229
|
- **Bare llama-server** (without llama-swap) isn't tested; `get_server_defaults`
|
|
196
|
-
needs llama-swap's `/upstream/<model>/props
|
|
230
|
+
needs llama-swap's `/upstream/<model>/props` (the profile falls back to `/props`).
|
|
231
|
+
- **Tools and `response_format` together** give no tool calls (see Model profile).
|
|
197
232
|
|
|
198
233
|
## Development
|
|
199
234
|
|
|
@@ -206,9 +241,9 @@ uv run pytest tests/unit_tests # offline
|
|
|
206
241
|
uv run ruff check && uv run ruff format --check && uv run pyright
|
|
207
242
|
```
|
|
208
243
|
|
|
209
|
-
The integration tests (LangChain's standard `langchain-tests` suite, on
|
|
210
|
-
|
|
211
|
-
set `LLAMA_BASE_URL`, then:
|
|
244
|
+
The integration tests (LangChain's standard `langchain-tests` suite, on Gemma 4
|
|
245
|
+
with thinking off and on) need a llama-swap server with a `gemma` entry. Copy
|
|
246
|
+
`.env.example` to `.env` and set `LLAMA_BASE_URL`, then:
|
|
212
247
|
|
|
213
248
|
```bash
|
|
214
249
|
uv run --env-file .env pytest tests/integration_tests
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "langchain-llama-cpp"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
description = "An integration package connecting llama.cpp's llama-server and LangChain, with reasoning, timings, structured output and tool calling"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
7
7
|
license-files = ["LICENSE"]
|
|
8
|
-
requires-python = ">=3.
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
9
|
keywords = [
|
|
10
10
|
"langchain",
|
|
11
11
|
"llama.cpp",
|
|
@@ -19,7 +19,6 @@ classifiers = [
|
|
|
19
19
|
"Development Status :: 3 - Alpha",
|
|
20
20
|
"Intended Audience :: Developers",
|
|
21
21
|
"Programming Language :: Python :: 3",
|
|
22
|
-
"Programming Language :: Python :: 3.10",
|
|
23
22
|
"Programming Language :: Python :: 3.11",
|
|
24
23
|
"Programming Language :: Python :: 3.12",
|
|
25
24
|
"Programming Language :: Python :: 3.13",
|
|
@@ -105,7 +104,7 @@ include = [
|
|
|
105
104
|
"src",
|
|
106
105
|
"tests",
|
|
107
106
|
]
|
|
108
|
-
pythonVersion = "3.
|
|
107
|
+
pythonVersion = "3.11"
|
|
109
108
|
venvPath = "."
|
|
110
109
|
venv = ".venv"
|
|
111
110
|
typeCheckingMode = "standard"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "langchain-llama-cpp"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
description = "An integration package connecting llama.cpp's llama-server and LangChain, with reasoning, timings, structured output and tool calling"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -8,13 +8,12 @@ license-files = ["LICENSE"]
|
|
|
8
8
|
authors = [
|
|
9
9
|
{ name = "Bharathan Mudaliar", email = "bharathanmudaliar@gmail.com" }
|
|
10
10
|
]
|
|
11
|
-
requires-python = ">=3.
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
12
|
keywords = ["langchain", "llama.cpp", "llama-server", "llama-swap", "llm", "local-llm", "chat-model"]
|
|
13
13
|
classifiers = [
|
|
14
14
|
"Development Status :: 3 - Alpha",
|
|
15
15
|
"Intended Audience :: Developers",
|
|
16
16
|
"Programming Language :: Python :: 3",
|
|
17
|
-
"Programming Language :: Python :: 3.10",
|
|
18
17
|
"Programming Language :: Python :: 3.11",
|
|
19
18
|
"Programming Language :: Python :: 3.12",
|
|
20
19
|
"Programming Language :: Python :: 3.13",
|
|
@@ -95,7 +94,7 @@ asyncio_default_fixture_loop_scope = "function"
|
|
|
95
94
|
# Pyright is the engine inside Pylance, so VS Code and `uv run pyright` agree.
|
|
96
95
|
[tool.pyright]
|
|
97
96
|
include = ["src", "tests"]
|
|
98
|
-
pythonVersion = "3.
|
|
97
|
+
pythonVersion = "3.11"
|
|
99
98
|
venvPath = "."
|
|
100
99
|
venv = ".venv"
|
|
101
100
|
typeCheckingMode = "standard"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""The JSON llama-server sends back from `/v1/chat/completions` (
|
|
1
|
+
"""The JSON llama-server sends back from `/v1/chat/completions` (v1.1.0).
|
|
2
2
|
|
|
3
3
|
Types for the type checker only: replies are plain dicts from `json.loads`,
|
|
4
4
|
never validated, so a server that sends something else isn't rejected here.
|
|
@@ -6,7 +6,7 @@ Every class is `total=False` because the code reads each key with `.get()`
|
|
|
6
6
|
and copes when it's missing; the docstrings say which keys the server always
|
|
7
7
|
sends.
|
|
8
8
|
|
|
9
|
-
Sources (llama.cpp
|
|
9
|
+
Sources (llama.cpp v1.1.0, build b12774): `tools/server/server-task.cpp`
|
|
10
10
|
(`to_json_oaicompat_chat`, `to_json_oaicompat_chat_stream`,
|
|
11
11
|
`server_task_result_cmpl_partial::to_json_oaicompat_chat`,
|
|
12
12
|
`probs_vector_to_json`, `result_prompt_progress::to_json`),
|
|
@@ -55,7 +55,7 @@ the stream ends without `[DONE]`.
|
|
|
55
55
|
from typing import Literal, TypedDict
|
|
56
56
|
|
|
57
57
|
FinishReason = Literal["stop", "length", "tool_calls"]
|
|
58
|
-
"""`length` when `max_tokens` or the context window ran out (
|
|
58
|
+
"""`length` when `max_tokens` or the context window ran out (v1.1.0 sends
|
|
59
59
|
`length` for every stop that isn't an end-of-sequence token or a stop string)."""
|
|
60
60
|
|
|
61
61
|
|
|
@@ -101,6 +101,9 @@ class LlamaContentPart(TypedDict, total=False):
|
|
|
101
101
|
type: str
|
|
102
102
|
text: str
|
|
103
103
|
|
|
104
|
+
name: str
|
|
105
|
+
"""In place of `text` on a `tool_reference` part."""
|
|
106
|
+
|
|
104
107
|
|
|
105
108
|
class LlamaMessage(TypedDict, total=False):
|
|
106
109
|
"""`choices[].message` in a reply. Always `role` and `content`."""
|
|
@@ -190,7 +193,7 @@ class LlamaPromptTokensDetails(TypedDict, total=False):
|
|
|
190
193
|
class LlamaCompletionTokensDetails(TypedDict, total=False):
|
|
191
194
|
"""`usage.completion_tokens_details`, as OpenAI sends it.
|
|
192
195
|
|
|
193
|
-
|
|
196
|
+
v1.1.0 never sends it (reasoning tokens are counted in
|
|
194
197
|
`completion_tokens` but not reported apart); read in case a build does.
|
|
195
198
|
"""
|
|
196
199
|
|
|
@@ -198,7 +201,7 @@ class LlamaCompletionTokensDetails(TypedDict, total=False):
|
|
|
198
201
|
|
|
199
202
|
|
|
200
203
|
class LlamaUsage(TypedDict, total=False):
|
|
201
|
-
"""`usage`.
|
|
204
|
+
"""`usage`. v1.1.0 always sends the four keys below except the last."""
|
|
202
205
|
|
|
203
206
|
prompt_tokens: int
|
|
204
207
|
|
{langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/chat_models.py
RENAMED
|
@@ -20,6 +20,7 @@ from langchain_core.language_models import (
|
|
|
20
20
|
LangSmithParams,
|
|
21
21
|
LanguageModelInput,
|
|
22
22
|
)
|
|
23
|
+
from langchain_core.language_models.model_profile import ModelProfile
|
|
23
24
|
from langchain_core.messages import (
|
|
24
25
|
AIMessage,
|
|
25
26
|
AIMessageChunk,
|
|
@@ -94,6 +95,10 @@ INITIAL_RETRY_DELAY = 0.5
|
|
|
94
95
|
MAX_RETRY_DELAY = 8.0
|
|
95
96
|
MAX_RETRY_AFTER = 60.0
|
|
96
97
|
|
|
98
|
+
# The `/props` fetch behind `profile`. Behind llama-swap it starts the entry,
|
|
99
|
+
# which can take tens of seconds for a large model; connecting must not.
|
|
100
|
+
PROFILE_TIMEOUT = httpx.Timeout(120.0, connect=10.0)
|
|
101
|
+
|
|
97
102
|
# ChatLlama fields that configure the client rather than the request.
|
|
98
103
|
_CLIENT_FIELDS = frozenset(
|
|
99
104
|
{
|
|
@@ -103,11 +108,16 @@ _CLIENT_FIELDS = frozenset(
|
|
|
103
108
|
"max_retries",
|
|
104
109
|
"streaming",
|
|
105
110
|
"stream_usage",
|
|
111
|
+
"fetch_profile",
|
|
106
112
|
"http_client",
|
|
107
113
|
"http_async_client",
|
|
108
114
|
}
|
|
109
115
|
)
|
|
110
116
|
|
|
117
|
+
# Profiles fetched from `/props`, per (base_url, model), for the process.
|
|
118
|
+
# Only successes are kept, so a server that was down is asked again.
|
|
119
|
+
_PROFILE_CACHE: dict[tuple[str, str], ModelProfile] = {}
|
|
120
|
+
|
|
111
121
|
_AsyncClients = weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, httpx.AsyncClient]
|
|
112
122
|
|
|
113
123
|
# What `_chunk_from_line` returns for `data: [DONE]`, the end of a finished stream.
|
|
@@ -182,7 +192,7 @@ class ChatLlama(BaseChatModel):
|
|
|
182
192
|
"""Server root, e.g. `http://localhost:8080`. Defaults to `LLAMA_BASE_URL`."""
|
|
183
193
|
|
|
184
194
|
# --- Request fields -----------------------------------------------------
|
|
185
|
-
# Every field accepted by /v1/chat/completions in llama.cpp
|
|
195
|
+
# Every field accepted by /v1/chat/completions in llama.cpp v1.1.0 (b12774)
|
|
186
196
|
# (tools/server/server-common.cpp oaicompat_chat_params_parse,
|
|
187
197
|
# server-schema.cpp make_llama_cmpl_schema, server-context.cpp id_slot).
|
|
188
198
|
# Each is sent under its own name; None (the default) leaves it out, so the
|
|
@@ -338,7 +348,11 @@ class ChatLlama(BaseChatModel):
|
|
|
338
348
|
"""Continue the last assistant message instead of starting a new turn."""
|
|
339
349
|
|
|
340
350
|
echo: bool | None = None
|
|
341
|
-
"""
|
|
351
|
+
"""With `continue_final_message`, include the continued text in the reply.
|
|
352
|
+
|
|
353
|
+
By default the reply holds only the newly generated text. (In b11429 and
|
|
354
|
+
older builds it meant echoing the input tokens.)
|
|
355
|
+
"""
|
|
342
356
|
|
|
343
357
|
# Probabilities and debugging output
|
|
344
358
|
logprobs: bool | None = None
|
|
@@ -406,8 +420,23 @@ class ChatLlama(BaseChatModel):
|
|
|
406
420
|
`timings`. Can be overridden per call with `stream_usage=`.
|
|
407
421
|
"""
|
|
408
422
|
|
|
423
|
+
fetch_profile: bool = True
|
|
424
|
+
"""Fill `profile` from the server's `/props` at construction (default on).
|
|
425
|
+
|
|
426
|
+
Reads `GET /upstream/<model>/props` (llama-swap; this starts the entry),
|
|
427
|
+
falling back to `GET /props` (a plain llama-server) on a 404. Gives
|
|
428
|
+
`max_input_tokens` (the per-slot `n_ctx`), the input modalities and
|
|
429
|
+
`tool_calling`. Fetched once per `(base_url, model)` per process. Any failure
|
|
430
|
+
leaves `profile` at `None`. A `profile=` you pass is used as it is, with no
|
|
431
|
+
fetch. Turn it off for offline use. `/props` is fetched with a separate
|
|
432
|
+
client, not `http_client`.
|
|
433
|
+
"""
|
|
434
|
+
|
|
409
435
|
http_client: httpx.Client | None = Field(default=None, exclude=True)
|
|
410
|
-
"""Your own `httpx.Client
|
|
436
|
+
"""Your own `httpx.Client` for chat requests (not the `/props` profile fetch).
|
|
437
|
+
|
|
438
|
+
If given, `timeout` is not applied to it.
|
|
439
|
+
"""
|
|
411
440
|
|
|
412
441
|
http_async_client: httpx.AsyncClient | None = Field(default=None, exclude=True)
|
|
413
442
|
"""Your own `httpx.AsyncClient` for async calls. `timeout` isn't applied to it."""
|
|
@@ -481,22 +510,38 @@ class ChatLlama(BaseChatModel):
|
|
|
481
510
|
tools: Anything `convert_to_openai_tool` accepts: `@tool` functions,
|
|
482
511
|
`BaseTool`s, Pydantic classes, `TypedDict`s, plain functions or
|
|
483
512
|
OpenAI tool dicts.
|
|
484
|
-
tool_choice:
|
|
485
|
-
`"
|
|
486
|
-
`"
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
`
|
|
499
|
-
|
|
513
|
+
tool_choice: `"auto"`, `"none"` and `"required"` are sent as they
|
|
514
|
+
are; `"any"` and `True` become `"required"`. A bound tool's
|
|
515
|
+
name, or `{"type": "function", "function": {"name": ...}}`, is
|
|
516
|
+
sent as that object, with every bound tool still in `tools`.
|
|
517
|
+
What the server does with it depends on its version and on the
|
|
518
|
+
chat handler it picks for the model's template:
|
|
519
|
+
|
|
520
|
+
- llama.cpp v1.1.0 and later: the model must call a tool.
|
|
521
|
+
Models on the generic (auto-parser) handler can call only the
|
|
522
|
+
named one; the gemma4, qwen3-coder and gpt-oss handlers still
|
|
523
|
+
allow any bound tool, as with `"required"`.
|
|
524
|
+
- Older servers: the object is ignored and the request runs
|
|
525
|
+
with `"auto"`, so the model may answer without a tool call.
|
|
526
|
+
|
|
527
|
+
OpenAI's `{"type": "allowed_tools", "allowed_tools": {"mode":
|
|
528
|
+
"auto" | "required", "tools": [{"type": "function", "function":
|
|
529
|
+
{"name": ...}}, ...]}}` is checked (the mode, and that every
|
|
530
|
+
name is bound; `"required"` needs at least one) and sent
|
|
531
|
+
unchanged. v1.1.0 limits the model to the listed tools on the
|
|
532
|
+
generic handler (an empty `"auto"` list acts as `"none"`). The
|
|
533
|
+
gemma4, qwen3-coder and gpt-oss handlers apply only the mode,
|
|
534
|
+
and older servers run with `"auto"`.
|
|
535
|
+
|
|
536
|
+
`None`, `False` and `""` leave it out.
|
|
537
|
+
|
|
538
|
+
How strictly `"required"` holds also depends on the handler.
|
|
539
|
+
For Qwen3.5/3.6 (the handler llama.cpp names "qwen3-coder") the
|
|
540
|
+
grammar lets the model write text before the call and forbids
|
|
541
|
+
ending without one, so a model that doesn't want a tool keeps
|
|
542
|
+
writing until `max_tokens`, with no tool call (llama.cpp issue
|
|
543
|
+
#27217, closed as stale without a fix; unchanged as of v1.1.0).
|
|
544
|
+
Keep `max_tokens` set when forcing tools.
|
|
500
545
|
strict: Sent as `strict` on each tool when set. llama-server
|
|
501
546
|
ignores it: its grammar always enforces the schema.
|
|
502
547
|
parallel_tool_calls: Sent when set.
|
|
@@ -520,28 +565,9 @@ class ChatLlama(BaseChatModel):
|
|
|
520
565
|
if "function" in tool
|
|
521
566
|
]
|
|
522
567
|
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
tool_choice = "required"
|
|
527
|
-
elif not (
|
|
528
|
-
isinstance(tool_choice, str)
|
|
529
|
-
and tool_choice in {"auto", "none", "required"}
|
|
530
|
-
):
|
|
531
|
-
name: object = tool_choice
|
|
532
|
-
if isinstance(tool_choice, dict):
|
|
533
|
-
function: object = tool_choice.get("function")
|
|
534
|
-
if isinstance(function, dict):
|
|
535
|
-
name = cast("dict[str, Any]", function).get("name")
|
|
536
|
-
if not (isinstance(name, str) and name in tool_names):
|
|
537
|
-
msg = (
|
|
538
|
-
"tool_choice must be 'auto', 'none', 'required', 'any', "
|
|
539
|
-
"True, or the name of a bound tool "
|
|
540
|
-
f"({', '.join(tool_names)}); got {tool_choice!r}"
|
|
541
|
-
)
|
|
542
|
-
raise ValueError(msg)
|
|
543
|
-
tool_choice = "required"
|
|
544
|
-
kwargs["tool_choice"] = tool_choice
|
|
568
|
+
kwargs["tool_choice"] = _format_tool_choice(
|
|
569
|
+
tool_choice=tool_choice, tool_names=tool_names
|
|
570
|
+
)
|
|
545
571
|
|
|
546
572
|
if parallel_tool_calls is not None:
|
|
547
573
|
kwargs["parallel_tool_calls"] = parallel_tool_calls
|
|
@@ -718,6 +744,52 @@ class ChatLlama(BaseChatModel):
|
|
|
718
744
|
|
|
719
745
|
# --- LangChain core hooks ---------------------------------------------
|
|
720
746
|
|
|
747
|
+
def _resolve_model_profile(self) -> ModelProfile | None:
|
|
748
|
+
"""The profile from the server's `/props`, or None (see `fetch_profile`).
|
|
749
|
+
|
|
750
|
+
Core calls this at construction when no `profile` was passed, and turns
|
|
751
|
+
any exception into None; failures return None here already.
|
|
752
|
+
"""
|
|
753
|
+
if not self.fetch_profile:
|
|
754
|
+
return None
|
|
755
|
+
|
|
756
|
+
base_url = self.base_url.rstrip("/")
|
|
757
|
+
key = (base_url, self.model)
|
|
758
|
+
if (cached := _PROFILE_CACHE.get(key)) is None:
|
|
759
|
+
props = self._fetch_props(base_url)
|
|
760
|
+
profile = _profile_from_props(props) if props is not None else None
|
|
761
|
+
if profile is None:
|
|
762
|
+
return None
|
|
763
|
+
_PROFILE_CACHE[key] = cached = profile
|
|
764
|
+
return ModelProfile(**cached) # a copy: the caller may change it
|
|
765
|
+
|
|
766
|
+
def _fetch_props(self, base_url: str) -> dict[str, Any] | None:
|
|
767
|
+
"""`/props` of this model's server: llama-swap's path, then llama-server's.
|
|
768
|
+
|
|
769
|
+
One attempt each, no retries, with `PROFILE_TIMEOUT`. Always on a
|
|
770
|
+
short-lived client of its own, never `http_client`: that client's event
|
|
771
|
+
hooks (e.g. a recorder of chat requests) shouldn't see this GET.
|
|
772
|
+
ChatLlama sends no auth headers, so nothing from it is needed.
|
|
773
|
+
"""
|
|
774
|
+
paths = (f"/upstream/{self.model}/props", "/props")
|
|
775
|
+
client = _props_client()
|
|
776
|
+
try:
|
|
777
|
+
for path in paths:
|
|
778
|
+
response = client.get(base_url + path, timeout=PROFILE_TIMEOUT)
|
|
779
|
+
if response.status_code == 404: # noqa: PLR2004
|
|
780
|
+
continue # not llama-swap: try a plain llama-server
|
|
781
|
+
if not response.is_success:
|
|
782
|
+
return None
|
|
783
|
+
props: object = response.json()
|
|
784
|
+
return (
|
|
785
|
+
cast("dict[str, Any]", props) if isinstance(props, dict) else None
|
|
786
|
+
)
|
|
787
|
+
except (httpx.HTTPError, ValueError): # unreachable, timed out, not JSON
|
|
788
|
+
return None
|
|
789
|
+
finally:
|
|
790
|
+
client.close()
|
|
791
|
+
return None
|
|
792
|
+
|
|
721
793
|
def _get_ls_params(
|
|
722
794
|
self, stop: list[str] | None = None, **kwargs: Any
|
|
723
795
|
) -> LangSmithParams:
|
|
@@ -1040,9 +1112,132 @@ def _without_none(**items: Any) -> dict[str, Any]:
|
|
|
1040
1112
|
return {key: value for key, value in items.items() if value is not None}
|
|
1041
1113
|
|
|
1042
1114
|
|
|
1115
|
+
# --- Profile --------------------------------------------------------------
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
def _props_client() -> httpx.Client:
|
|
1119
|
+
"""A new client for the `/props` fetch (a function so tests can swap it)."""
|
|
1120
|
+
return httpx.Client()
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
def _profile_from_props(props: Mapping[str, Any]) -> ModelProfile | None:
|
|
1124
|
+
"""A `ModelProfile` from llama-server's `/props`, or None if it isn't one.
|
|
1125
|
+
|
|
1126
|
+
Fields as of llama.cpp v1.1.0 (`server-context.cpp` `get_res_props`):
|
|
1127
|
+
|
|
1128
|
+
- `default_generation_settings.n_ctx`: the per-slot context window, which
|
|
1129
|
+
holds the prompt and the reply → `max_input_tokens`.
|
|
1130
|
+
- `modalities.{vision, audio, video}` → `image_inputs`, `audio_inputs`,
|
|
1131
|
+
`video_inputs`.
|
|
1132
|
+
- `chat_template_caps.supports_tool_calls` → `tool_calling`. Without it the
|
|
1133
|
+
server's generic parser doesn't parse tool calls at all
|
|
1134
|
+
(`chat-auto-parser-generator.cpp`).
|
|
1135
|
+
|
|
1136
|
+
`structured_output` is left out on purpose: with `tools` in the request, a
|
|
1137
|
+
`response_format` grammar replaces the tool-call grammar in every chat
|
|
1138
|
+
handler, so an agent's model could no longer call tools.
|
|
1139
|
+
"""
|
|
1140
|
+
settings: object = props.get("default_generation_settings")
|
|
1141
|
+
if not isinstance(settings, dict):
|
|
1142
|
+
return None # a 200 from something that isn't llama-server
|
|
1143
|
+
|
|
1144
|
+
profile = ModelProfile(text_inputs=True)
|
|
1145
|
+
|
|
1146
|
+
n_ctx: object = cast("dict[str, Any]", settings).get("n_ctx")
|
|
1147
|
+
if isinstance(n_ctx, int) and not isinstance(n_ctx, bool) and n_ctx > 0:
|
|
1148
|
+
profile["max_input_tokens"] = n_ctx
|
|
1149
|
+
|
|
1150
|
+
modalities: object = props.get("modalities")
|
|
1151
|
+
if isinstance(modalities, dict):
|
|
1152
|
+
modality = cast("dict[str, Any]", modalities)
|
|
1153
|
+
if isinstance(vision := modality.get("vision"), bool):
|
|
1154
|
+
profile["image_inputs"] = vision
|
|
1155
|
+
if isinstance(audio := modality.get("audio"), bool):
|
|
1156
|
+
profile["audio_inputs"] = audio
|
|
1157
|
+
if isinstance(video := modality.get("video"), bool):
|
|
1158
|
+
profile["video_inputs"] = video
|
|
1159
|
+
|
|
1160
|
+
caps: object = props.get("chat_template_caps")
|
|
1161
|
+
if isinstance(caps, dict):
|
|
1162
|
+
tool_calls = cast("dict[str, Any]", caps).get("supports_tool_calls")
|
|
1163
|
+
if isinstance(tool_calls, bool):
|
|
1164
|
+
profile["tool_calling"] = tool_calls
|
|
1165
|
+
|
|
1166
|
+
return profile
|
|
1167
|
+
|
|
1168
|
+
|
|
1043
1169
|
# --- Tools and structured output ------------------------------------------
|
|
1044
1170
|
|
|
1045
1171
|
|
|
1172
|
+
def _format_tool_choice(
|
|
1173
|
+
*, tool_choice: dict[str, Any] | str | bool, tool_names: Sequence[str]
|
|
1174
|
+
) -> dict[str, Any] | str:
|
|
1175
|
+
"""Turn a `bind_tools` `tool_choice` into what is sent; see `bind_tools`.
|
|
1176
|
+
|
|
1177
|
+
Checks what llama.cpp v1.1.0 would reject with a 400 (`common/chat.cpp`
|
|
1178
|
+
`common_chat_tool_choice_parse_oaicompat`) here instead, and also rejects
|
|
1179
|
+
names that aren't bound, which older servers would silently ignore.
|
|
1180
|
+
"""
|
|
1181
|
+
if tool_choice is True or tool_choice == "any":
|
|
1182
|
+
return "required"
|
|
1183
|
+
if isinstance(tool_choice, str) and tool_choice in {"auto", "none", "required"}:
|
|
1184
|
+
return tool_choice
|
|
1185
|
+
if isinstance(tool_choice, dict) and tool_choice.get("type") == "allowed_tools":
|
|
1186
|
+
return _check_allowed_tools(tool_choice, tool_names)
|
|
1187
|
+
|
|
1188
|
+
# A named tool goes as the object form, as in ChatOpenAI.
|
|
1189
|
+
name = _function_name(tool_choice) if isinstance(tool_choice, dict) else tool_choice
|
|
1190
|
+
if not (isinstance(name, str) and name in tool_names):
|
|
1191
|
+
msg = (
|
|
1192
|
+
"tool_choice must be 'auto', 'none', 'required', 'any', True, the "
|
|
1193
|
+
f"name of a bound tool ({', '.join(tool_names)}) or an "
|
|
1194
|
+
f"'allowed_tools' object; got {tool_choice!r}"
|
|
1195
|
+
)
|
|
1196
|
+
raise ValueError(msg)
|
|
1197
|
+
return {"type": "function", "function": {"name": name}}
|
|
1198
|
+
|
|
1199
|
+
|
|
1200
|
+
def _function_name(tool: Mapping[str, Any]) -> object:
|
|
1201
|
+
"""`tool["function"]["name"]`, or None when it isn't there."""
|
|
1202
|
+
function: object = tool.get("function")
|
|
1203
|
+
if isinstance(function, dict):
|
|
1204
|
+
return cast("dict[str, Any]", function).get("name")
|
|
1205
|
+
return None
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
def _check_allowed_tools(
|
|
1209
|
+
tool_choice: dict[str, Any], tool_names: Sequence[str]
|
|
1210
|
+
) -> dict[str, Any]:
|
|
1211
|
+
"""Check an `allowed_tools` `tool_choice` and return it unchanged."""
|
|
1212
|
+
allowed: object = tool_choice.get("allowed_tools")
|
|
1213
|
+
mode: object = None
|
|
1214
|
+
entries: object = None
|
|
1215
|
+
if isinstance(allowed, dict):
|
|
1216
|
+
allowed_dict = cast("dict[str, Any]", allowed)
|
|
1217
|
+
mode = allowed_dict.get("mode")
|
|
1218
|
+
entries = allowed_dict.get("tools")
|
|
1219
|
+
if mode not in {"auto", "required"} or not isinstance(entries, list):
|
|
1220
|
+
msg = (
|
|
1221
|
+
"allowed_tools needs {'mode': 'auto' | 'required', 'tools': [...]}; "
|
|
1222
|
+
f"got {tool_choice!r}"
|
|
1223
|
+
)
|
|
1224
|
+
raise ValueError(msg)
|
|
1225
|
+
for entry in cast("list[object]", entries):
|
|
1226
|
+
entry_dict = cast("dict[str, Any]", entry) if isinstance(entry, dict) else {}
|
|
1227
|
+
name = _function_name(entry_dict)
|
|
1228
|
+
if entry_dict.get("type") != "function" or name not in tool_names:
|
|
1229
|
+
msg = (
|
|
1230
|
+
"allowed_tools entries must be {'type': 'function', 'function': "
|
|
1231
|
+
f"{{'name': ...}}}} naming a bound tool ({', '.join(tool_names)}); "
|
|
1232
|
+
f"got {entry!r}"
|
|
1233
|
+
)
|
|
1234
|
+
raise ValueError(msg)
|
|
1235
|
+
if mode == "required" and not entries:
|
|
1236
|
+
msg = "allowed_tools with mode 'required' must list at least one tool"
|
|
1237
|
+
raise ValueError(msg)
|
|
1238
|
+
return tool_choice
|
|
1239
|
+
|
|
1240
|
+
|
|
1046
1241
|
def _json_schema_response_format(
|
|
1047
1242
|
schema: dict[str, Any] | type, *, strict: bool | None
|
|
1048
1243
|
) -> dict[str, Any]:
|
|
@@ -1140,6 +1335,30 @@ def _format_instructions(schema: dict[str, Any] | type) -> str:
|
|
|
1140
1335
|
# --- Replies --------------------------------------------------------------
|
|
1141
1336
|
|
|
1142
1337
|
|
|
1338
|
+
_NORMALIZED_FINISH_REASONS = {
|
|
1339
|
+
"stop": "stop",
|
|
1340
|
+
"length": "length",
|
|
1341
|
+
"tool_calls": "tool_call",
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
def _finish_reason_fields(
|
|
1346
|
+
finish_reason: str | None, *, has_tool_calls: bool = False
|
|
1347
|
+
) -> dict[str, str]:
|
|
1348
|
+
"""`finish_reason` plus core's `normalized_finish_reason` (core 1.8.4).
|
|
1349
|
+
|
|
1350
|
+
The mapping is ChatOpenAI's for Chat Completions. llama-server (v1.1.0
|
|
1351
|
+
`server-task.cpp`) sends only `stop`, `length` and `tool_calls`; anything
|
|
1352
|
+
else becomes `other`, never `stop`.
|
|
1353
|
+
"""
|
|
1354
|
+
if not finish_reason:
|
|
1355
|
+
return {}
|
|
1356
|
+
normalized = _NORMALIZED_FINISH_REASONS.get(finish_reason, "other")
|
|
1357
|
+
if normalized == "stop" and has_tool_calls:
|
|
1358
|
+
normalized = "tool_call"
|
|
1359
|
+
return {"finish_reason": finish_reason, "normalized_finish_reason": normalized}
|
|
1360
|
+
|
|
1361
|
+
|
|
1143
1362
|
def _create_chat_result(data: LlamaResponse) -> ChatResult:
|
|
1144
1363
|
usage = data.get("usage")
|
|
1145
1364
|
response_metadata = _without_none(
|
|
@@ -1157,7 +1376,13 @@ def _create_chat_result(data: LlamaResponse) -> ChatResult:
|
|
|
1157
1376
|
if usage:
|
|
1158
1377
|
message.usage_metadata = _create_usage_metadata(usage)
|
|
1159
1378
|
|
|
1160
|
-
generation_info: dict[str, Any] = {
|
|
1379
|
+
generation_info: dict[str, Any] = {
|
|
1380
|
+
"finish_reason": choice.get("finish_reason"),
|
|
1381
|
+
**_finish_reason_fields(
|
|
1382
|
+
choice.get("finish_reason"),
|
|
1383
|
+
has_tool_calls=bool(message.tool_calls or message.invalid_tool_calls),
|
|
1384
|
+
),
|
|
1385
|
+
}
|
|
1161
1386
|
if logprobs := choice.get("logprobs"):
|
|
1162
1387
|
generation_info["logprobs"] = logprobs
|
|
1163
1388
|
generations.append(
|
|
@@ -1339,8 +1564,11 @@ def _convert_chunk(event: LlamaChunk) -> ChatGenerationChunk | None:
|
|
|
1339
1564
|
|
|
1340
1565
|
generation_info: dict[str, Any] = {}
|
|
1341
1566
|
if finish_reason := choice.get("finish_reason"):
|
|
1567
|
+
# Tool calls arrive in earlier chunks, but llama-server already says
|
|
1568
|
+
# `tool_calls` whenever it parsed one; core also corrects a `stop` on
|
|
1569
|
+
# the merged message in `stream_events`.
|
|
1342
1570
|
generation_info = _without_none(
|
|
1343
|
-
finish_reason
|
|
1571
|
+
**_finish_reason_fields(finish_reason),
|
|
1344
1572
|
model_name=event.get("model"),
|
|
1345
1573
|
system_fingerprint=event.get("system_fingerprint"),
|
|
1346
1574
|
id=event.get("id"),
|
|
File without changes
|
|
File without changes
|
{langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/content_blocks.py
RENAMED
|
File without changes
|
{langchain_llama_cpp-0.1.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/exceptions.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|