llm-agent-base 0.3.2__tar.gz → 0.3.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llm-agent-base
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: Lightweight Python framework for building LLM agents with tool calling and RAG
5
5
  Author-email: Paweł Gryka <pawel.m.gryka@gmail.com>
6
6
  License-Expression: MIT
@@ -42,6 +42,7 @@ pip install llm-agent-base
42
42
  - **Conversational chat** — `chat()` maintains conversation history across calls; `reset_conversation()` starts fresh
43
43
  - **File attachments** — pass images, PDFs, and text files directly to `ask()`, `run()`, or `chat()` via the `files` parameter
44
44
  - **Tool calling** — register plain Python functions as LLM-callable tools; schemas are built automatically from type hints and docstrings, including per-parameter descriptions and enum values
45
+ - **Robust inline tool calls** — handles models that emit tool calls as JSON text (e.g. GLM), including batched and variant-encoded arguments, while gating on the tool registry so genuine JSON output is never mistaken for a malformed call
45
46
  - **RAG** — ingest a folder of documents (`.txt`, `.md`, `.json`, `.pdf`) into a FAISS vector index and inject relevant chunks into every prompt
46
47
  - **Incremental re-indexing** — edit a document and only that file is re-embedded; unchanged chunks keep their vectors
47
48
  - **Knowledge search tool** — when a knowledge base is configured, the agent automatically gains a `search_knowledge` tool (semantic/vector) and a `read_knowledge_files` tool (keyword search returning full file contents); both are optional and independently toggleable
@@ -129,16 +130,20 @@ def search_orders(customer: str, status: Literal["open", "shipped", "cancelled"]
129
130
  """
130
131
  ```
131
132
 
132
- The tool-calling loop handles both the standard OpenAI `tool_calls` field and the fallback case where a model emits a tool call as inline JSON text in the message content — a behaviour seen on some OpenAI-compatible endpoints (e.g. GLM models). Two inline shapes are recognised:
133
+ The tool-calling loop handles both the standard OpenAI `tool_calls` field and the fallback case where a model emits a tool call as inline JSON text in the message content — a behaviour seen on some OpenAI-compatible endpoints (e.g. GLM models). Both of these inline shapes are recognised:
133
134
 
134
135
  ```json
135
136
  {"name": "get_weather", "arguments": {"city": "Tokyo"}}
136
137
  {"get_weather": {"city": "Tokyo"}}
137
138
  ```
138
139
 
139
- The second form — the tool name as the single top-level key, arguments as the nested object — is also produced by GLM models. When an inline call is detected and the tool name is registered, the tool is executed, the result is fed back, and the loop continues exactly as with a structural call. Unknown tool names and non-tool JSON are returned unchanged. A safety cap of 5 consecutive text-emitted calls prevents infinite loops.
140
+ The second form — the tool name as the single top-level key, arguments as the nested object — is also produced by GLM models. Either shape may **batch** several calls to the same tool by supplying a list of argument objects (`{"get_weather": [{"city": "Tokyo"}, {"city": "Paris"}]}`); each is executed and fed back with a distinct id, and a batch counts as one round against the safety cap. The arguments payload is also normalised across common variants — a single-element list wrapper (`[{"city": "Tokyo"}]`) or a double-encoded JSON string — so a recoverable call is not silently dropped.
140
141
 
141
- The loop is bounded by `max_iterations` (default 10). Once the budget is spent, the tools are withheld from the request so the model has to answer in text — the loop always terminates and always returns a string, even against a model that would otherwise keep calling tools forever.
142
+ Crucially, an inline call is only intercepted when its tool name matches a **registered** tool. Because both shapes are indistinguishable from ordinary JSON a model might emit as its genuine answer (`{"result": {...}}` or `{"name": "Alice", "arguments": {...}}`), gating on the tool registry ensures real JSON output is returned unchanged rather than mistaken for a malformed tool call. When a call *is* detected, the tool runs, the result is fed back, and the loop continues exactly as with a structural call.
143
+
144
+ Tool results are made actionable for the model: a tool that raises gets an error message naming the tool and instructing the model to proceed, and a tool that returns `None` or an empty string is reported as an explicit "no results" message so the model never confuses "found nothing" with "the call failed" — for both inline and structural calls.
145
+
146
+ The loop is bounded by `max_iterations` (default 10) and a safety cap of 5 consecutive text-emitted calls. Once either budget is spent, the tools are withheld and the model is told to give a final answer in text — so even a model that would otherwise keep calling tools forever always terminates with a real answer instead of leaking its last tool-call JSON. The loop always returns a string.
142
147
 
143
148
  ```python
144
149
  agent = AgentBase(..., max_iterations=25) # allow longer tool chains
@@ -17,6 +17,7 @@ pip install llm-agent-base
17
17
  - **Conversational chat** — `chat()` maintains conversation history across calls; `reset_conversation()` starts fresh
18
18
  - **File attachments** — pass images, PDFs, and text files directly to `ask()`, `run()`, or `chat()` via the `files` parameter
19
19
  - **Tool calling** — register plain Python functions as LLM-callable tools; schemas are built automatically from type hints and docstrings, including per-parameter descriptions and enum values
20
+ - **Robust inline tool calls** — handles models that emit tool calls as JSON text (e.g. GLM), including batched and variant-encoded arguments, while gating on the tool registry so genuine JSON output is never mistaken for a malformed call
20
21
  - **RAG** — ingest a folder of documents (`.txt`, `.md`, `.json`, `.pdf`) into a FAISS vector index and inject relevant chunks into every prompt
21
22
  - **Incremental re-indexing** — edit a document and only that file is re-embedded; unchanged chunks keep their vectors
22
23
  - **Knowledge search tool** — when a knowledge base is configured, the agent automatically gains a `search_knowledge` tool (semantic/vector) and a `read_knowledge_files` tool (keyword search returning full file contents); both are optional and independently toggleable
@@ -104,16 +105,20 @@ def search_orders(customer: str, status: Literal["open", "shipped", "cancelled"]
104
105
  """
105
106
  ```
106
107
 
107
- The tool-calling loop handles both the standard OpenAI `tool_calls` field and the fallback case where a model emits a tool call as inline JSON text in the message content — a behaviour seen on some OpenAI-compatible endpoints (e.g. GLM models). Two inline shapes are recognised:
108
+ The tool-calling loop handles both the standard OpenAI `tool_calls` field and the fallback case where a model emits a tool call as inline JSON text in the message content — a behaviour seen on some OpenAI-compatible endpoints (e.g. GLM models). Both of these inline shapes are recognised:
108
109
 
109
110
  ```json
110
111
  {"name": "get_weather", "arguments": {"city": "Tokyo"}}
111
112
  {"get_weather": {"city": "Tokyo"}}
112
113
  ```
113
114
 
114
- The second form — the tool name as the single top-level key, arguments as the nested object — is also produced by GLM models. When an inline call is detected and the tool name is registered, the tool is executed, the result is fed back, and the loop continues exactly as with a structural call. Unknown tool names and non-tool JSON are returned unchanged. A safety cap of 5 consecutive text-emitted calls prevents infinite loops.
115
+ The second form — the tool name as the single top-level key, arguments as the nested object — is also produced by GLM models. Either shape may **batch** several calls to the same tool by supplying a list of argument objects (`{"get_weather": [{"city": "Tokyo"}, {"city": "Paris"}]}`); each is executed and fed back with a distinct id, and a batch counts as one round against the safety cap. The arguments payload is also normalised across common variants — a single-element list wrapper (`[{"city": "Tokyo"}]`) or a double-encoded JSON string — so a recoverable call is not silently dropped.
115
116
 
116
- The loop is bounded by `max_iterations` (default 10). Once the budget is spent, the tools are withheld from the request so the model has to answer in text — the loop always terminates and always returns a string, even against a model that would otherwise keep calling tools forever.
117
+ Crucially, an inline call is only intercepted when its tool name matches a **registered** tool. Because both shapes are indistinguishable from ordinary JSON a model might emit as its genuine answer (`{"result": {...}}` or `{"name": "Alice", "arguments": {...}}`), gating on the tool registry ensures real JSON output is returned unchanged rather than mistaken for a malformed tool call. When a call *is* detected, the tool runs, the result is fed back, and the loop continues exactly as with a structural call.
118
+
119
+ Tool results are made actionable for the model: a tool that raises gets an error message naming the tool and instructing the model to proceed, and a tool that returns `None` or an empty string is reported as an explicit "no results" message so the model never confuses "found nothing" with "the call failed" — for both inline and structural calls.
120
+
121
+ The loop is bounded by `max_iterations` (default 10) and a safety cap of 5 consecutive text-emitted calls. Once either budget is spent, the tools are withheld and the model is told to give a final answer in text — so even a model that would otherwise keep calling tools forever always terminates with a real answer instead of leaking its last tool-call JSON. The loop always returns a string.
117
122
 
118
123
  ```python
119
124
  agent = AgentBase(..., max_iterations=25) # allow longer tool chains
@@ -89,7 +89,15 @@ class AgentBase:
89
89
  self.load_or_ingest_knowledge()
90
90
 
91
91
  def register_tool(self, fn: Callable) -> Callable:
92
- """Register a Python function as a callable tool. Can be used as a decorator."""
92
+ """Register a Python function as a callable tool. Can be used as a decorator.
93
+
94
+ A tool must return a non-empty, human-readable string. When it finds
95
+ nothing, it must say so explicitly (e.g. "No matching records found.")
96
+ rather than returning ``None`` or ``""`` — an empty result leaves the
97
+ model unable to tell "found nothing" from "the call failed". The tool
98
+ loop replaces an empty/``None`` result with a generic "no results"
99
+ message as a safety net, but a tool-specific message is clearer.
100
+ """
93
101
  self._tools[fn.__name__] = (fn, build_tool_schema(fn))
94
102
  return fn
95
103
 
@@ -215,7 +215,9 @@ def build_tool_schema(fn: Callable) -> dict:
215
215
  }
216
216
 
217
217
 
218
- def _extract_text_tool_call(text: str) -> list[tuple[str, dict]] | None:
218
+ def _extract_text_tool_call(
219
+ text: str, known_tools=None
220
+ ) -> list[tuple[str, dict]] | None:
219
221
  """Find inline tool-call JSON object(s) in ``text``.
220
222
 
221
223
  Recognizes the shapes models emit when they call a tool in prose instead of
@@ -230,10 +232,24 @@ def _extract_text_tool_call(text: str) -> list[tuple[str, dict]] | None:
230
232
  :func:`_normalize_tool_arguments`, so variant encodings (a JSON string, a
231
233
  list wrapper) are accepted too.
232
234
 
235
+ Both shapes are indistinguishable from ordinary JSON the model might emit as
236
+ its genuine answer — ``{"result": {...}}`` or ``{"name": "Alice",
237
+ "arguments": {...}}`` are perfectly valid data. To avoid mistaking such
238
+ output for a tool call, a match is only reported when the referenced tool is
239
+ one of ``known_tools``. When ``known_tools`` is ``None`` the parser stays
240
+ permissive (shape detection only), but callers with a tool registry should
241
+ always pass it.
242
+
233
243
  Returns a list of ``(tool_name, arguments_dict)`` tuples, or ``None``.
234
244
  """
235
245
  if not text or "{" not in text:
236
246
  return None
247
+
248
+ def _is_tool(candidate) -> bool:
249
+ return isinstance(candidate, str) and (
250
+ known_tools is None or candidate in known_tools
251
+ )
252
+
237
253
  decoder = json.JSONDecoder()
238
254
  for i, ch in enumerate(text):
239
255
  if ch != "{":
@@ -245,13 +261,13 @@ def _extract_text_tool_call(text: str) -> list[tuple[str, dict]] | None:
245
261
  if not isinstance(obj, dict):
246
262
  continue
247
263
  name = obj.get("name")
248
- if isinstance(name, str):
264
+ if "arguments" in obj and _is_tool(name):
249
265
  batch = _tool_argument_batch(obj.get("arguments"))
250
266
  if batch is not None:
251
267
  return [(name, args) for args in batch]
252
268
  if len(obj) == 1:
253
269
  key, value = next(iter(obj.items()))
254
- if isinstance(key, str):
270
+ if _is_tool(key):
255
271
  batch = _tool_argument_batch(value)
256
272
  if batch is not None:
257
273
  return [(key, args) for args in batch]
@@ -354,11 +370,21 @@ def execute_tool_loop(
354
370
  "tool arguments must be a JSON object, got "
355
371
  f"{raw!r}"
356
372
  )
357
- result = str(fn(**args))
373
+ raw_result = fn(**args)
374
+ result = "" if raw_result is None else str(raw_result)
375
+ if not result.strip():
376
+ result = (
377
+ f"Tool '{tc.function.name}' returned no results. "
378
+ "The information you requested was not found."
379
+ )
358
380
  if debug:
359
381
  print(f"[debug] tool '{tc.function.name}' args={args} result={result}")
360
382
  except Exception as e:
361
- result = f"Error: {e}"
383
+ result = (
384
+ f"Error: tool '{tc.function.name}' failed: {e}. "
385
+ "Proceed without this tool's result using the "
386
+ "information you already have."
387
+ )
362
388
  messages.append({
363
389
  "role": "tool",
364
390
  "tool_call_id": tc.id,
@@ -369,13 +395,43 @@ def execute_tool_loop(
369
395
  # No structural tool calls: check for tool call(s) emitted as inline
370
396
  # JSON text before returning the content as the final answer.
371
397
  content = msg.content
372
- found = _extract_text_tool_call(content) if content else None
373
- if (
374
- found is not None
375
- and all(name in tools for name, _ in found)
376
- and text_tool_calls < _MAX_TEXT_TOOL_CALLS
377
- and offer_tools
378
- ):
398
+ # Only tool calls that name a registered tool are intercepted; genuine
399
+ # JSON output that merely resembles a tool call is left as the answer.
400
+ found = _extract_text_tool_call(content, set(tools)) if content else None
401
+
402
+ if found is not None:
403
+ # Budget exhausted: the call is valid but cannot run. Tell the model
404
+ # why and force a single final answer without tools, instead of
405
+ # leaking the raw tool-call JSON as the answer.
406
+ if not offer_tools or text_tool_calls >= _MAX_TEXT_TOOL_CALLS:
407
+ reason = (
408
+ "the maximum number of tool calls has been reached"
409
+ if text_tool_calls >= _MAX_TEXT_TOOL_CALLS
410
+ else "the maximum number of iterations has been reached"
411
+ )
412
+ if debug:
413
+ print(f"[debug] inline tool call not executed ({reason}); forcing final answer")
414
+ messages.append({"role": "assistant", "content": content})
415
+ messages.append({
416
+ "role": "user",
417
+ "content": (
418
+ f"Your tool call could not be executed because {reason}. "
419
+ "No further tool calls are allowed. Using only the "
420
+ "information already gathered, provide your final answer "
421
+ "now in the required output format, without any tool calls."
422
+ ),
423
+ })
424
+ # One final call with tools withheld so the model must answer in
425
+ # text. Returns immediately: the budget counters are not
426
+ # advanced here, so continuing would loop without progress.
427
+ final_kwargs = {"model": model, "messages": messages}
428
+ if temperature is not None:
429
+ final_kwargs["temperature"] = temperature
430
+ if response_format is not None:
431
+ final_kwargs["response_format"] = response_format
432
+ final = client.chat.completions.create(**final_kwargs)
433
+ return final.choices[0].message.content or ""
434
+
379
435
  assistant_text = content
380
436
  for tool_name in dict.fromkeys(name for name, _ in found):
381
437
  assistant_text = _strip_tool_call(assistant_text, tool_name)
@@ -389,11 +445,21 @@ def execute_tool_loop(
389
445
  for index, (tool_name, args) in enumerate(found):
390
446
  fn, _ = tools[tool_name]
391
447
  try:
392
- result = str(fn(**args))
448
+ raw_result = fn(**args)
449
+ result = "" if raw_result is None else str(raw_result)
450
+ if not result.strip():
451
+ result = (
452
+ f"Tool '{tool_name}' returned no results. "
453
+ "The information you requested was not found."
454
+ )
393
455
  if debug:
394
456
  print(f"[debug] text tool call '{tool_name}' args={args} result={result}")
395
457
  except Exception as e:
396
- result = f"Error: {e}"
458
+ result = (
459
+ f"Error: tool '{tool_name}' failed: {e}. "
460
+ "Proceed without this tool's result using the "
461
+ "information you already have."
462
+ )
397
463
  if debug:
398
464
  print(f"[debug] text tool call '{tool_name}' raised: {e}")
399
465
  messages.append({
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llm-agent-base
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: Lightweight Python framework for building LLM agents with tool calling and RAG
5
5
  Author-email: Paweł Gryka <pawel.m.gryka@gmail.com>
6
6
  License-Expression: MIT
@@ -42,6 +42,7 @@ pip install llm-agent-base
42
42
  - **Conversational chat** — `chat()` maintains conversation history across calls; `reset_conversation()` starts fresh
43
43
  - **File attachments** — pass images, PDFs, and text files directly to `ask()`, `run()`, or `chat()` via the `files` parameter
44
44
  - **Tool calling** — register plain Python functions as LLM-callable tools; schemas are built automatically from type hints and docstrings, including per-parameter descriptions and enum values
45
+ - **Robust inline tool calls** — handles models that emit tool calls as JSON text (e.g. GLM), including batched and variant-encoded arguments, while gating on the tool registry so genuine JSON output is never mistaken for a malformed call
45
46
  - **RAG** — ingest a folder of documents (`.txt`, `.md`, `.json`, `.pdf`) into a FAISS vector index and inject relevant chunks into every prompt
46
47
  - **Incremental re-indexing** — edit a document and only that file is re-embedded; unchanged chunks keep their vectors
47
48
  - **Knowledge search tool** — when a knowledge base is configured, the agent automatically gains a `search_knowledge` tool (semantic/vector) and a `read_knowledge_files` tool (keyword search returning full file contents); both are optional and independently toggleable
@@ -129,16 +130,20 @@ def search_orders(customer: str, status: Literal["open", "shipped", "cancelled"]
129
130
  """
130
131
  ```
131
132
 
132
- The tool-calling loop handles both the standard OpenAI `tool_calls` field and the fallback case where a model emits a tool call as inline JSON text in the message content — a behaviour seen on some OpenAI-compatible endpoints (e.g. GLM models). Two inline shapes are recognised:
133
+ The tool-calling loop handles both the standard OpenAI `tool_calls` field and the fallback case where a model emits a tool call as inline JSON text in the message content — a behaviour seen on some OpenAI-compatible endpoints (e.g. GLM models). Both of these inline shapes are recognised:
133
134
 
134
135
  ```json
135
136
  {"name": "get_weather", "arguments": {"city": "Tokyo"}}
136
137
  {"get_weather": {"city": "Tokyo"}}
137
138
  ```
138
139
 
139
- The second form — the tool name as the single top-level key, arguments as the nested object — is also produced by GLM models. When an inline call is detected and the tool name is registered, the tool is executed, the result is fed back, and the loop continues exactly as with a structural call. Unknown tool names and non-tool JSON are returned unchanged. A safety cap of 5 consecutive text-emitted calls prevents infinite loops.
140
+ The second form — the tool name as the single top-level key, arguments as the nested object — is also produced by GLM models. Either shape may **batch** several calls to the same tool by supplying a list of argument objects (`{"get_weather": [{"city": "Tokyo"}, {"city": "Paris"}]}`); each is executed and fed back with a distinct id, and a batch counts as one round against the safety cap. The arguments payload is also normalised across common variants — a single-element list wrapper (`[{"city": "Tokyo"}]`) or a double-encoded JSON string — so a recoverable call is not silently dropped.
140
141
 
141
- The loop is bounded by `max_iterations` (default 10). Once the budget is spent, the tools are withheld from the request so the model has to answer in text — the loop always terminates and always returns a string, even against a model that would otherwise keep calling tools forever.
142
+ Crucially, an inline call is only intercepted when its tool name matches a **registered** tool. Because both shapes are indistinguishable from ordinary JSON a model might emit as its genuine answer (`{"result": {...}}` or `{"name": "Alice", "arguments": {...}}`), gating on the tool registry ensures real JSON output is returned unchanged rather than mistaken for a malformed tool call. When a call *is* detected, the tool runs, the result is fed back, and the loop continues exactly as with a structural call.
143
+
144
+ Tool results are made actionable for the model: a tool that raises gets an error message naming the tool and instructing the model to proceed, and a tool that returns `None` or an empty string is reported as an explicit "no results" message so the model never confuses "found nothing" with "the call failed" — for both inline and structural calls.
145
+
146
+ The loop is bounded by `max_iterations` (default 10) and a safety cap of 5 consecutive text-emitted calls. Once either budget is spent, the tools are withheld and the model is told to give a final answer in text — so even a model that would otherwise keep calling tools forever always terminates with a real answer instead of leaking its last tool-call JSON. The loop always returns a string.
142
147
 
143
148
  ```python
144
149
  agent = AgentBase(..., max_iterations=25) # allow longer tool chains
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "llm-agent-base"
7
- version = "0.3.2"
7
+ version = "0.3.4"
8
8
  description = "Lightweight Python framework for building LLM agents with tool calling and RAG"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
File without changes