langchain-llama-cpp 0.2.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.2.0 → langchain_llama_cpp-0.3.0}/PKG-INFO +19 -16
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/README.md +17 -13
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/pyproject.toml +3 -4
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/pyproject.toml.orig +3 -4
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/_wire.py +5 -5
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/chat_models.py +141 -43
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/LICENSE +0 -0
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/__init__.py +0 -0
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/content_blocks.py +0 -0
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/exceptions.py +0 -0
- {langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/py.typed +0 -0
- {langchain_llama_cpp-0.2.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,18 +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
54
|
- Live integration tests: gemma 4, thinking off and on. Last full run on
|
|
58
|
-
llama.cpp
|
|
55
|
+
llama.cpp v1.1.0 (build b12774) with langchain-core 1.9.0 (2026-12-03).
|
|
59
56
|
Qwen3.6 and gpt-oss were tested on llama-server b11429 with langchain-core
|
|
60
57
|
1.6, and are no longer in the suite.
|
|
61
58
|
- Request fields and reply shapes follow the llama.cpp source of the latest
|
|
62
|
-
release, **
|
|
59
|
+
release, **v1.1.0** (build b12774).
|
|
63
60
|
|
|
64
61
|
## Quick start
|
|
65
62
|
|
|
@@ -135,10 +132,15 @@ msg = llm_with_tools.invoke("What's the weather in Paris?")
|
|
|
135
132
|
msg.tool_calls # [{'name': 'get_weather', 'args': {'city': 'Paris'}, 'id': '...', ...}]
|
|
136
133
|
```
|
|
137
134
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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.
|
|
142
144
|
|
|
143
145
|
### Structured output
|
|
144
146
|
|
|
@@ -191,12 +193,12 @@ used only for chat requests.
|
|
|
191
193
|
`ToolStrategy` for a `response_format`. llama-server can't combine `tools` with
|
|
192
194
|
a `json_schema` `response_format`. The response-format grammar replaces the
|
|
193
195
|
tool-call grammar, so the model answers in JSON straight away and never calls a
|
|
194
|
-
tool. With Qwen-style templates
|
|
195
|
-
"failed to parse grammar".
|
|
196
|
+
tool. With Qwen-style templates, v0.9.0 fails the request instead, with
|
|
197
|
+
"failed to parse grammar" (fixed in v1.0.0).
|
|
196
198
|
|
|
197
199
|
### Request parameters
|
|
198
200
|
|
|
199
|
-
Every field `/v1/chat/completions` accepts in
|
|
201
|
+
Every field `/v1/chat/completions` accepts in v1.1.0 is a typed parameter:
|
|
200
202
|
`temperature`, `top_k`, `top_p`, `min_p`, `samplers`, `repeat_penalty`, the DRY
|
|
201
203
|
and XTC samplers, `grammar`, `json_schema`, `reasoning_budget_tokens`,
|
|
202
204
|
`cache_prompt`, `id_slot`, `lora` and more. Set them on the model or per call:
|
|
@@ -245,7 +247,8 @@ seconds and defaults to `None` (no timeout), since local generation can be slow.
|
|
|
245
247
|
`max_tokens`, and there's no tool call. This is
|
|
246
248
|
[ggml-org/llama.cpp#27217](https://github.com/ggml-org/llama.cpp/issues/27217)
|
|
247
249
|
(closed as stale without a fix); keep `max_tokens` set.
|
|
248
|
-
- **A named `tool_choice`**
|
|
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).
|
|
249
252
|
- **JSON schema bounds on numbers** (`minimum`, `maximum`, `multipleOf` on
|
|
250
253
|
`number`) aren't enforced by llama-server's grammar. Integer bounds are.
|
|
251
254
|
- **Bare llama-server** (without llama-swap) isn't tested; `get_server_defaults`
|
|
@@ -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,18 +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
29
|
- Live integration tests: gemma 4, thinking off and on. Last full run on
|
|
32
|
-
llama.cpp
|
|
30
|
+
llama.cpp v1.1.0 (build b12774) with langchain-core 1.9.0 (2026-12-03).
|
|
33
31
|
Qwen3.6 and gpt-oss were tested on llama-server b11429 with langchain-core
|
|
34
32
|
1.6, and are no longer in the suite.
|
|
35
33
|
- Request fields and reply shapes follow the llama.cpp source of the latest
|
|
36
|
-
release, **
|
|
34
|
+
release, **v1.1.0** (build b12774).
|
|
37
35
|
|
|
38
36
|
## Quick start
|
|
39
37
|
|
|
@@ -109,10 +107,15 @@ msg = llm_with_tools.invoke("What's the weather in Paris?")
|
|
|
109
107
|
msg.tool_calls # [{'name': 'get_weather', 'args': {'city': 'Paris'}, 'id': '...', ...}]
|
|
110
108
|
```
|
|
111
109
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
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.
|
|
116
119
|
|
|
117
120
|
### Structured output
|
|
118
121
|
|
|
@@ -165,12 +168,12 @@ used only for chat requests.
|
|
|
165
168
|
`ToolStrategy` for a `response_format`. llama-server can't combine `tools` with
|
|
166
169
|
a `json_schema` `response_format`. The response-format grammar replaces the
|
|
167
170
|
tool-call grammar, so the model answers in JSON straight away and never calls a
|
|
168
|
-
tool. With Qwen-style templates
|
|
169
|
-
"failed to parse grammar".
|
|
171
|
+
tool. With Qwen-style templates, v0.9.0 fails the request instead, with
|
|
172
|
+
"failed to parse grammar" (fixed in v1.0.0).
|
|
170
173
|
|
|
171
174
|
### Request parameters
|
|
172
175
|
|
|
173
|
-
Every field `/v1/chat/completions` accepts in
|
|
176
|
+
Every field `/v1/chat/completions` accepts in v1.1.0 is a typed parameter:
|
|
174
177
|
`temperature`, `top_k`, `top_p`, `min_p`, `samplers`, `repeat_penalty`, the DRY
|
|
175
178
|
and XTC samplers, `grammar`, `json_schema`, `reasoning_budget_tokens`,
|
|
176
179
|
`cache_prompt`, `id_slot`, `lora` and more. Set them on the model or per call:
|
|
@@ -219,7 +222,8 @@ seconds and defaults to `None` (no timeout), since local generation can be slow.
|
|
|
219
222
|
`max_tokens`, and there's no tool call. This is
|
|
220
223
|
[ggml-org/llama.cpp#27217](https://github.com/ggml-org/llama.cpp/issues/27217)
|
|
221
224
|
(closed as stale without a fix); keep `max_tokens` set.
|
|
222
|
-
- **A named `tool_choice`**
|
|
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).
|
|
223
227
|
- **JSON schema bounds on numbers** (`minimum`, `maximum`, `multipleOf` on
|
|
224
228
|
`number`) aren't enforced by llama-server's grammar. Integer bounds are.
|
|
225
229
|
- **Bare llama-server** (without llama-swap) isn't tested; `get_server_defaults`
|
|
@@ -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
|
|
|
@@ -193,7 +193,7 @@ class LlamaPromptTokensDetails(TypedDict, total=False):
|
|
|
193
193
|
class LlamaCompletionTokensDetails(TypedDict, total=False):
|
|
194
194
|
"""`usage.completion_tokens_details`, as OpenAI sends it.
|
|
195
195
|
|
|
196
|
-
|
|
196
|
+
v1.1.0 never sends it (reasoning tokens are counted in
|
|
197
197
|
`completion_tokens` but not reported apart); read in case a build does.
|
|
198
198
|
"""
|
|
199
199
|
|
|
@@ -201,7 +201,7 @@ class LlamaCompletionTokensDetails(TypedDict, total=False):
|
|
|
201
201
|
|
|
202
202
|
|
|
203
203
|
class LlamaUsage(TypedDict, total=False):
|
|
204
|
-
"""`usage`.
|
|
204
|
+
"""`usage`. v1.1.0 always sends the four keys below except the last."""
|
|
205
205
|
|
|
206
206
|
prompt_tokens: int
|
|
207
207
|
|
{langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/chat_models.py
RENAMED
|
@@ -192,7 +192,7 @@ class ChatLlama(BaseChatModel):
|
|
|
192
192
|
"""Server root, e.g. `http://localhost:8080`. Defaults to `LLAMA_BASE_URL`."""
|
|
193
193
|
|
|
194
194
|
# --- Request fields -----------------------------------------------------
|
|
195
|
-
# 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)
|
|
196
196
|
# (tools/server/server-common.cpp oaicompat_chat_params_parse,
|
|
197
197
|
# server-schema.cpp make_llama_cmpl_schema, server-context.cpp id_slot).
|
|
198
198
|
# Each is sent under its own name; None (the default) leaves it out, so the
|
|
@@ -510,23 +510,38 @@ class ChatLlama(BaseChatModel):
|
|
|
510
510
|
tools: Anything `convert_to_openai_tool` accepts: `@tool` functions,
|
|
511
511
|
`BaseTool`s, Pydantic classes, `TypedDict`s, plain functions or
|
|
512
512
|
OpenAI tool dicts.
|
|
513
|
-
tool_choice:
|
|
514
|
-
`"
|
|
515
|
-
`"
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
`
|
|
528
|
-
|
|
529
|
-
`
|
|
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.
|
|
530
545
|
strict: Sent as `strict` on each tool when set. llama-server
|
|
531
546
|
ignores it: its grammar always enforces the schema.
|
|
532
547
|
parallel_tool_calls: Sent when set.
|
|
@@ -550,28 +565,9 @@ class ChatLlama(BaseChatModel):
|
|
|
550
565
|
if "function" in tool
|
|
551
566
|
]
|
|
552
567
|
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
tool_choice = "required"
|
|
557
|
-
elif not (
|
|
558
|
-
isinstance(tool_choice, str)
|
|
559
|
-
and tool_choice in {"auto", "none", "required"}
|
|
560
|
-
):
|
|
561
|
-
name: object = tool_choice
|
|
562
|
-
if isinstance(tool_choice, dict):
|
|
563
|
-
function: object = tool_choice.get("function")
|
|
564
|
-
if isinstance(function, dict):
|
|
565
|
-
name = cast("dict[str, Any]", function).get("name")
|
|
566
|
-
if not (isinstance(name, str) and name in tool_names):
|
|
567
|
-
msg = (
|
|
568
|
-
"tool_choice must be 'auto', 'none', 'required', 'any', "
|
|
569
|
-
"True, or the name of a bound tool "
|
|
570
|
-
f"({', '.join(tool_names)}); got {tool_choice!r}"
|
|
571
|
-
)
|
|
572
|
-
raise ValueError(msg)
|
|
573
|
-
tool_choice = "required"
|
|
574
|
-
kwargs["tool_choice"] = tool_choice
|
|
568
|
+
kwargs["tool_choice"] = _format_tool_choice(
|
|
569
|
+
tool_choice=tool_choice, tool_names=tool_names
|
|
570
|
+
)
|
|
575
571
|
|
|
576
572
|
if parallel_tool_calls is not None:
|
|
577
573
|
kwargs["parallel_tool_calls"] = parallel_tool_calls
|
|
@@ -1127,7 +1123,7 @@ def _props_client() -> httpx.Client:
|
|
|
1127
1123
|
def _profile_from_props(props: Mapping[str, Any]) -> ModelProfile | None:
|
|
1128
1124
|
"""A `ModelProfile` from llama-server's `/props`, or None if it isn't one.
|
|
1129
1125
|
|
|
1130
|
-
Fields as of llama.cpp
|
|
1126
|
+
Fields as of llama.cpp v1.1.0 (`server-context.cpp` `get_res_props`):
|
|
1131
1127
|
|
|
1132
1128
|
- `default_generation_settings.n_ctx`: the per-slot context window, which
|
|
1133
1129
|
holds the prompt and the reply → `max_input_tokens`.
|
|
@@ -1173,6 +1169,75 @@ def _profile_from_props(props: Mapping[str, Any]) -> ModelProfile | None:
|
|
|
1173
1169
|
# --- Tools and structured output ------------------------------------------
|
|
1174
1170
|
|
|
1175
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
|
+
|
|
1176
1241
|
def _json_schema_response_format(
|
|
1177
1242
|
schema: dict[str, Any] | type, *, strict: bool | None
|
|
1178
1243
|
) -> dict[str, Any]:
|
|
@@ -1270,6 +1335,30 @@ def _format_instructions(schema: dict[str, Any] | type) -> str:
|
|
|
1270
1335
|
# --- Replies --------------------------------------------------------------
|
|
1271
1336
|
|
|
1272
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
|
+
|
|
1273
1362
|
def _create_chat_result(data: LlamaResponse) -> ChatResult:
|
|
1274
1363
|
usage = data.get("usage")
|
|
1275
1364
|
response_metadata = _without_none(
|
|
@@ -1287,7 +1376,13 @@ def _create_chat_result(data: LlamaResponse) -> ChatResult:
|
|
|
1287
1376
|
if usage:
|
|
1288
1377
|
message.usage_metadata = _create_usage_metadata(usage)
|
|
1289
1378
|
|
|
1290
|
-
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
|
+
}
|
|
1291
1386
|
if logprobs := choice.get("logprobs"):
|
|
1292
1387
|
generation_info["logprobs"] = logprobs
|
|
1293
1388
|
generations.append(
|
|
@@ -1469,8 +1564,11 @@ def _convert_chunk(event: LlamaChunk) -> ChatGenerationChunk | None:
|
|
|
1469
1564
|
|
|
1470
1565
|
generation_info: dict[str, Any] = {}
|
|
1471
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`.
|
|
1472
1570
|
generation_info = _without_none(
|
|
1473
|
-
finish_reason
|
|
1571
|
+
**_finish_reason_fields(finish_reason),
|
|
1474
1572
|
model_name=event.get("model"),
|
|
1475
1573
|
system_fingerprint=event.get("system_fingerprint"),
|
|
1476
1574
|
id=event.get("id"),
|
|
File without changes
|
|
File without changes
|
{langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/content_blocks.py
RENAMED
|
File without changes
|
{langchain_llama_cpp-0.2.0 → langchain_llama_cpp-0.3.0}/src/langchain_llama_cpp/exceptions.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|