sinapsis-chatbots-base 0.2.0__tar.gz → 0.2.2__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.
Files changed (34) hide show
  1. {sinapsis_chatbots_base-0.2.0/src/sinapsis_chatbots_base.egg-info → sinapsis_chatbots_base-0.2.2}/PKG-INFO +9 -3
  2. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/README.md +8 -2
  3. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/pyproject.toml +1 -1
  4. sinapsis_chatbots_base-0.2.2/src/sinapsis_chatbots_base/helpers/endpoint_mcp_helpers.py +407 -0
  5. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/helpers/llm_conversation.py +2 -2
  6. sinapsis_chatbots_base-0.2.2/src/sinapsis_chatbots_base/helpers/mcp_retry_helpers.py +76 -0
  7. sinapsis_chatbots_base-0.2.2/src/sinapsis_chatbots_base/helpers/performance.py +92 -0
  8. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/helpers/tags.py +1 -1
  9. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/__init__.py +3 -0
  10. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/endpoint_llm_completion.py +19 -5
  11. sinapsis_chatbots_base-0.2.2/src/sinapsis_chatbots_base/templates/endpoint_llm_completion_mcp.py +606 -0
  12. sinapsis_chatbots_base-0.2.2/src/sinapsis_chatbots_base/templates/endpoint_llm_multimodal.py +71 -0
  13. sinapsis_chatbots_base-0.2.2/src/sinapsis_chatbots_base/templates/endpoint_llm_streaming_completion.py +337 -0
  14. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/llm_conversation_input.py +1 -0
  15. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/llm_streaming_base.py +5 -3
  16. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/llm_template_base.py +1 -0
  17. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/query_contextualize.py +1 -0
  18. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/query_contextualize_from_file.py +2 -0
  19. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2/src/sinapsis_chatbots_base.egg-info}/PKG-INFO +9 -3
  20. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base.egg-info/SOURCES.txt +6 -0
  21. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/LICENSE +0 -0
  22. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/setup.cfg +0 -0
  23. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/__init__.py +0 -0
  24. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/__init__.py +0 -0
  25. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/helpers/__init__.py +0 -0
  26. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/helpers/env_vars.py +0 -0
  27. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/helpers/llm_keys.py +0 -0
  28. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/helpers/postprocess_text.py +0 -0
  29. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/helpers/schemas.py +0 -0
  30. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/llm_multimodal_base.py +0 -0
  31. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base/templates/llm_runtime_base.py +0 -0
  32. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base.egg-info/dependency_links.txt +0 -0
  33. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base.egg-info/requires.txt +0 -0
  34. {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.2}/src/sinapsis_chatbots_base.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sinapsis-chatbots-base
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Sinapsis templates for shared chatbot foundations.
5
5
  Author-email: SinapsisAI <dev@sinapsis.tech>
6
6
  Project-URL: Homepage, https://sinapsis.tech
@@ -32,7 +32,7 @@ Sinapsis Chatbots Base
32
32
  <br>
33
33
  </h1>
34
34
 
35
- <h4 align="center">Sinapsis templates for chatbot inputs, contextualization, and endpoint completions.</h4>
35
+ <h4 align="center">Sinapsis templates for chatbot inputs, contextualization, and endpoint-backed completions.</h4>
36
36
 
37
37
  <p align="center">
38
38
  <a href="#installation">🐍 Installation</a> •
@@ -61,7 +61,7 @@ pip install sinapsis-chatbots-base --extra-index-url https://pypi.sinapsis.tech
61
61
  ```
62
62
 
63
63
  > [!IMPORTANT]
64
- > `EndpointLLMCompletion` requires the optional `endpoint` extra:
64
+ > `EndpointLLMCompletion` and `EndpointLLMCompletionWithMCP` require the optional `endpoint` extra:
65
65
  >
66
66
  > ```bash
67
67
  > uv pip install sinapsis-chatbots-base[endpoint] --extra-index-url https://pypi.sinapsis.tech
@@ -80,6 +80,12 @@ pip install sinapsis-chatbots-base --extra-index-url https://pypi.sinapsis.tech
80
80
  - **LLMConversationInput**: Creates an `LLMConversationPacket` from a prompt, system prompt, and packet metadata.
81
81
  - **QueryContextualizeFromFile**: Builds packet contexts from files or documents already loaded into the container.
82
82
  - **EndpointLLMCompletion**: Sends chat requests to OpenAI-compatible endpoints such as OpenAI, Ollama, llama.cpp server, vLLM server, or compatible hosted APIs.
83
+ - **EndpointLLMCompletionWithMCP**: Adds MCP tool support on top of `EndpointLLMCompletion` for OpenAI-compatible endpoints.
84
+ - **EndpointLLMStreamingCompletion**: Streams chat-completion chunks from OpenAI-compatible endpoints and emits partial packet updates.
85
+ - **EndpointLLMMultiModal**: Sends text + image user turns to OpenAI-compatible multimodal endpoints.
86
+
87
+ > [!NOTE]
88
+ > `EndpointLLMCompletionWithMCP` is currently validated for llama.cpp served Qwen 3.5 models and other OpenAI-compatible endpoints may also work depending on tool-calling behavior.
83
89
 
84
90
  > [!TIP]
85
91
  > Use CLI command ``` sinapsis info --all-template-names``` to show a list with all the available Template names installed with Sinapsis Chatbots Base.
@@ -10,7 +10,7 @@ Sinapsis Chatbots Base
10
10
  <br>
11
11
  </h1>
12
12
 
13
- <h4 align="center">Sinapsis templates for chatbot inputs, contextualization, and endpoint completions.</h4>
13
+ <h4 align="center">Sinapsis templates for chatbot inputs, contextualization, and endpoint-backed completions.</h4>
14
14
 
15
15
  <p align="center">
16
16
  <a href="#installation">🐍 Installation</a> •
@@ -39,7 +39,7 @@ pip install sinapsis-chatbots-base --extra-index-url https://pypi.sinapsis.tech
39
39
  ```
40
40
 
41
41
  > [!IMPORTANT]
42
- > `EndpointLLMCompletion` requires the optional `endpoint` extra:
42
+ > `EndpointLLMCompletion` and `EndpointLLMCompletionWithMCP` require the optional `endpoint` extra:
43
43
  >
44
44
  > ```bash
45
45
  > uv pip install sinapsis-chatbots-base[endpoint] --extra-index-url https://pypi.sinapsis.tech
@@ -58,6 +58,12 @@ pip install sinapsis-chatbots-base --extra-index-url https://pypi.sinapsis.tech
58
58
  - **LLMConversationInput**: Creates an `LLMConversationPacket` from a prompt, system prompt, and packet metadata.
59
59
  - **QueryContextualizeFromFile**: Builds packet contexts from files or documents already loaded into the container.
60
60
  - **EndpointLLMCompletion**: Sends chat requests to OpenAI-compatible endpoints such as OpenAI, Ollama, llama.cpp server, vLLM server, or compatible hosted APIs.
61
+ - **EndpointLLMCompletionWithMCP**: Adds MCP tool support on top of `EndpointLLMCompletion` for OpenAI-compatible endpoints.
62
+ - **EndpointLLMStreamingCompletion**: Streams chat-completion chunks from OpenAI-compatible endpoints and emits partial packet updates.
63
+ - **EndpointLLMMultiModal**: Sends text + image user turns to OpenAI-compatible multimodal endpoints.
64
+
65
+ > [!NOTE]
66
+ > `EndpointLLMCompletionWithMCP` is currently validated for llama.cpp served Qwen 3.5 models and other OpenAI-compatible endpoints may also work depending on tool-calling behavior.
61
67
 
62
68
  > [!TIP]
63
69
  > Use CLI command ``` sinapsis info --all-template-names``` to show a list with all the available Template names installed with Sinapsis Chatbots Base.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sinapsis-chatbots-base"
3
- version = "0.2.0"
3
+ version = "0.2.2"
4
4
  description = "Sinapsis templates for shared chatbot foundations."
5
5
  authors = [
6
6
  {name = "SinapsisAI", email = "dev@sinapsis.tech"},
@@ -0,0 +1,407 @@
1
+ import json
2
+ import re
3
+ from typing import Any
4
+
5
+ from sinapsis_chatbots_base.helpers.llm_conversation import normalize_tool_definition
6
+ from sinapsis_chatbots_base.helpers.llm_keys import LLMChatKeys, MCPKeys
7
+ from sinapsis_core.utils.logging_utils import sinapsis_logger
8
+
9
+
10
+ class EndpointMCPConstants:
11
+ """Constants used by endpoint-backed MCP integration.
12
+
13
+ Attributes:
14
+ TOOL_CALL_START (str): Marker that starts a plain-text fallback tool call block.
15
+ TOOL_CALL_END (str): Marker that ends a plain-text fallback tool call block.
16
+ TOOL_CALL_FAILED_PREFIX (str): Prefix added to tool-result text when a tool call failed.
17
+ DEFAULT_SYSTEM_PROMPT (str): Default system prompt used when injecting tool guidance.
18
+ TOOL_USAGE_GUIDELINES (str): Prompt snippet that explains fallback tool-call formatting.
19
+ """
20
+
21
+ TOOL_CALL_START = "TOOL_CALL"
22
+ TOOL_CALL_END = "END_TOOL_CALL"
23
+
24
+ TOOL_CALL_FAILED_PREFIX = "TOOL CALL FAILED: "
25
+
26
+ DEFAULT_SYSTEM_PROMPT = (
27
+ "You are a helpful AI assistant with access to tools. "
28
+ "Use tools whenever you need current or external information."
29
+ )
30
+
31
+ TOOL_USAGE_GUIDELINES = """
32
+
33
+ # Tool Usage Guidelines
34
+
35
+ If native tool calling is available, use it.
36
+ Otherwise emit tool calls exactly with this plain-text format and no markdown fences:
37
+
38
+ TOOL_CALL
39
+ tool_name: exact_tool_name_here
40
+ args: {"param": "value"}
41
+ END_TOOL_CALL
42
+
43
+ Use the exact tool name and valid JSON arguments.
44
+ """
45
+
46
+
47
+ def _normalize_parameters_schema(input_schema: dict[str, Any] | None) -> dict[str, Any]:
48
+ """Normalize an MCP input schema into an endpoint-compatible parameters schema.
49
+
50
+ Args:
51
+ input_schema (dict[str, Any] | None): Original MCP input schema.
52
+
53
+ Returns:
54
+ dict[str, Any]: Normalized object schema compatible with OpenAI-style tools.
55
+ """
56
+ if not isinstance(input_schema, dict) or not input_schema:
57
+ return {MCPKeys.tool_type: "object", MCPKeys.properties: {}}
58
+
59
+ normalized_schema = dict(input_schema)
60
+ normalized_schema.setdefault(MCPKeys.tool_type, "object")
61
+ normalized_schema.setdefault(MCPKeys.properties, {})
62
+ return normalized_schema
63
+
64
+
65
+ def make_tools_endpoint_compatible(tools: list[Any]) -> list[dict[str, Any]]:
66
+ """Convert packet tools into OpenAI-compatible function tool definitions.
67
+
68
+ Args:
69
+ tools (list[Any]): Tool definitions stored on the conversation packet.
70
+
71
+ Returns:
72
+ list[dict[str, Any]]: Endpoint-compatible function tool payloads.
73
+ """
74
+ endpoint_tools: list[dict[str, Any]] = []
75
+ for tool in tools:
76
+ normalized_tool = normalize_tool_definition(tool)
77
+ endpoint_tools.append(
78
+ {
79
+ MCPKeys.tool_type: MCPKeys.function,
80
+ MCPKeys.function: {
81
+ MCPKeys.name: normalized_tool[MCPKeys.name],
82
+ MCPKeys.description: normalized_tool.get(MCPKeys.description, "") or "",
83
+ MCPKeys.parameters: _normalize_parameters_schema(normalized_tool.get(MCPKeys.input_schema)),
84
+ },
85
+ }
86
+ )
87
+ return endpoint_tools
88
+
89
+
90
+ def extract_tool_calls_from_content(content: str) -> list[dict[str, Any]] | None:
91
+ """Extract fallback tool calls from assistant text.
92
+
93
+ Args:
94
+ content (str): Assistant text that may contain fallback tool-call blocks.
95
+
96
+ Returns:
97
+ list[dict[str, Any]] | None: Parsed fallback tool calls, or `None` when none were found.
98
+ """
99
+ tool_calls = _extract_explicit_tool_call_blocks(content)
100
+ tool_calls.extend(_extract_xml_tool_call_blocks(content))
101
+
102
+ return tool_calls if tool_calls else None
103
+
104
+
105
+ def _extract_explicit_tool_call_blocks(content: str) -> list[dict[str, Any]]:
106
+ """Extract `TOOL_CALL ... END_TOOL_CALL` fallback blocks.
107
+
108
+ Args:
109
+ content (str): Assistant text that may contain explicit fallback blocks.
110
+
111
+ Returns:
112
+ list[dict[str, Any]]: Parsed tool-call payloads extracted from explicit blocks.
113
+ """
114
+ pattern = (
115
+ rf"{re.escape(EndpointMCPConstants.TOOL_CALL_START)}\s*\n"
116
+ rf"(.*?)(?:\n{re.escape(EndpointMCPConstants.TOOL_CALL_END)}|$)"
117
+ )
118
+ blocks = re.findall(pattern, content, re.DOTALL)
119
+ tool_calls = []
120
+ for block in blocks:
121
+ parsed = _parse_tool_block(block)
122
+ if parsed is not None:
123
+ tool_calls.append(parsed)
124
+ return tool_calls
125
+
126
+
127
+ def _extract_xml_tool_call_blocks(content: str) -> list[dict[str, Any]]:
128
+ """Extract XML-like `<tool_call>` fallback blocks.
129
+
130
+ Args:
131
+ content (str): Assistant text that may contain XML-like tool-call blocks.
132
+
133
+ Returns:
134
+ list[dict[str, Any]]: Parsed tool-call payloads extracted from XML-like blocks.
135
+ """
136
+ pattern = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)
137
+ blocks = pattern.findall(content)
138
+ tool_calls = []
139
+ for block in blocks:
140
+ parsed = _parse_xml_tool_call_block(block)
141
+ if parsed is not None:
142
+ tool_calls.append(parsed)
143
+ return tool_calls
144
+
145
+
146
+ def _parse_tool_block(block: str) -> dict[str, Any] | None:
147
+ """Parse one plain-text fallback tool-call block.
148
+
149
+ Args:
150
+ block (str): Tool-call block body without the wrapper markers.
151
+
152
+ Returns:
153
+ dict[str, Any] | None: Normalized tool-call payload, or `None` when parsing fails.
154
+ """
155
+ lines = [line.strip() for line in block.strip().split("\n") if line.strip()]
156
+ if not lines:
157
+ return None
158
+
159
+ tool_name = _extract_tool_name(lines)
160
+ args_dict = _extract_tool_args(lines)
161
+ if not tool_name:
162
+ return None
163
+
164
+ return {
165
+ MCPKeys.tool_name: tool_name,
166
+ MCPKeys.args: args_dict,
167
+ MCPKeys.tool_use_id: f"{tool_name}_{hash(block) % 1000}",
168
+ }
169
+
170
+
171
+ def _extract_tool_name(lines: list[str]) -> str | None:
172
+ """Extract the tool name from fallback tool-call lines.
173
+
174
+ Args:
175
+ lines (list[str]): Normalized non-empty lines from one fallback tool-call block.
176
+
177
+ Returns:
178
+ str | None: Extracted tool name, or `None` when no name could be inferred.
179
+ """
180
+ tool_name_from_keyword = None
181
+ tool_name_from_standalone = None
182
+
183
+ for line in lines:
184
+ if line.startswith(f"{MCPKeys.tool_name}:"):
185
+ tool_name_from_keyword = line.split(":", 1)[1].strip()
186
+ elif ":" in line and not line.startswith(("args:", f"{MCPKeys.args}:")):
187
+ key_part = line.split(":", 1)[0].strip()
188
+ value_part = line.split(":", 1)[1].strip()
189
+ if value_part.startswith(("{", "[")):
190
+ return key_part
191
+ elif (
192
+ not line.startswith(("args:", f"{MCPKeys.args}:", f"{MCPKeys.tool_name}:"))
193
+ and not line.startswith(("{", "["))
194
+ and tool_name_from_standalone is None
195
+ ):
196
+ tool_name_from_standalone = line
197
+
198
+ return tool_name_from_keyword or tool_name_from_standalone
199
+
200
+
201
+ def _extract_tool_args(lines: list[str]) -> dict[str, Any]:
202
+ """Extract JSON arguments from fallback tool-call lines.
203
+
204
+ Args:
205
+ lines (list[str]): Normalized non-empty lines from one fallback tool-call block.
206
+
207
+ Returns:
208
+ dict[str, Any]: Parsed JSON arguments, or an empty dict on failure.
209
+ """
210
+ for line in lines:
211
+ args_str = None
212
+
213
+ if line.startswith(("args:", f"{MCPKeys.args}:")):
214
+ args_str = line.split(":", 1)[1].strip()
215
+ elif ":" in line and not line.startswith(f"{MCPKeys.tool_name}:"):
216
+ value_part = line.split(":", 1)[1].strip()
217
+ if value_part.startswith(("{", "[")):
218
+ args_str = value_part
219
+
220
+ if args_str is None:
221
+ continue
222
+
223
+ if args_str in {"{}", "", "null", "None"}:
224
+ return {}
225
+
226
+ try:
227
+ parsed = json.loads(args_str)
228
+ except json.JSONDecodeError as exc:
229
+ sinapsis_logger.warning(f"Failed to parse MCP fallback tool args: {args_str}. Error: {exc}")
230
+ return {}
231
+
232
+ return parsed if isinstance(parsed, dict) else {}
233
+
234
+ return {}
235
+
236
+
237
+ def _parse_xml_tool_call_block(block: str) -> dict[str, Any] | None:
238
+ """Parse one XML-like tool-call block.
239
+
240
+ Args:
241
+ block (str): XML-like tool-call block body without the outer tags.
242
+
243
+ Returns:
244
+ dict[str, Any] | None: Normalized tool-call payload, or `None` when parsing fails.
245
+ """
246
+ function_match = re.search(r"<function=([^>]+)>", block)
247
+ if function_match is None:
248
+ return None
249
+
250
+ tool_name = function_match.group(1).strip()
251
+ if not tool_name:
252
+ return None
253
+
254
+ arguments: dict[str, Any] = {}
255
+ for parameter_name, parameter_value in re.findall(
256
+ r"<parameter=([^>]+)>\s*(.*?)\s*</parameter>",
257
+ block,
258
+ re.DOTALL,
259
+ ):
260
+ normalized_name = parameter_name.strip()
261
+ normalized_value = parameter_value.strip()
262
+ if not normalized_name:
263
+ continue
264
+ arguments[normalized_name] = normalized_value
265
+
266
+ return {
267
+ MCPKeys.tool_name: tool_name,
268
+ MCPKeys.args: arguments,
269
+ MCPKeys.tool_use_id: f"{tool_name}_{hash(block) % 1000}",
270
+ }
271
+
272
+
273
+ def strip_tool_call_blocks(content: str | None) -> str | None:
274
+ """Remove fallback tool-call blocks from assistant text.
275
+
276
+ Args:
277
+ content (str | None): Assistant text that may contain fallback tool-call blocks.
278
+
279
+ Returns:
280
+ str | None: Assistant text with fallback tool-call blocks removed.
281
+ """
282
+ if not content:
283
+ return content
284
+
285
+ explicit_pattern = re.compile(
286
+ rf"{re.escape(EndpointMCPConstants.TOOL_CALL_START)}\s*\n"
287
+ rf".*?(?:\n{re.escape(EndpointMCPConstants.TOOL_CALL_END)}|$)",
288
+ flags=re.DOTALL,
289
+ )
290
+ xml_pattern = re.compile(r"<tool_call>\s*.*?\s*</tool_call>", flags=re.DOTALL)
291
+ stripped = explicit_pattern.sub("", content)
292
+ stripped = xml_pattern.sub("", stripped)
293
+ stripped = re.sub(r"\n{3,}", "\n\n", stripped).strip()
294
+ return stripped or None
295
+
296
+
297
+ def format_json_content(raw_text: str) -> str:
298
+ """Pretty-print JSON content when it looks like a JSON object.
299
+
300
+ Args:
301
+ raw_text (str): Raw text returned by a tool or extracted from a payload.
302
+
303
+ Returns:
304
+ str: Pretty-printed JSON text when parsing succeeds, otherwise the original text.
305
+ """
306
+ text = raw_text.strip()
307
+ if not (text.startswith("{") and text.endswith("}")):
308
+ return raw_text
309
+
310
+ try:
311
+ parsed_data = json.loads(raw_text)
312
+ except json.JSONDecodeError:
313
+ return raw_text
314
+
315
+ return json.dumps(parsed_data, indent=2)
316
+
317
+
318
+ def build_tool_description(tool: dict[str, Any]) -> str:
319
+ """Build a readable tool description block for prompt injection.
320
+
321
+ Args:
322
+ tool (dict[str, Any]): Endpoint-compatible tool definition.
323
+
324
+ Returns:
325
+ str: Human-readable prompt fragment describing the tool and its parameters.
326
+ """
327
+ if not (tool.get(MCPKeys.tool_type) == MCPKeys.function and MCPKeys.function in tool):
328
+ return ""
329
+
330
+ function = tool[MCPKeys.function]
331
+ description = f"\n## {function[MCPKeys.name]}\n"
332
+ description += f"Description: {function.get(MCPKeys.description, '')}\n"
333
+
334
+ parameters = function.get(MCPKeys.parameters, {})
335
+ if parameters.get(MCPKeys.properties):
336
+ description += "Parameters:\n"
337
+ required_params = parameters.get(MCPKeys.required, [])
338
+
339
+ for param_name, param_info in parameters[MCPKeys.properties].items():
340
+ param_type = param_info.get(MCPKeys.tool_type, "string")
341
+ param_desc = param_info.get(MCPKeys.description, "")
342
+ req_text = " (required)" if param_name in required_params else " (optional)"
343
+ description += f" - {param_name} ({param_type}){req_text}: {param_desc}\n"
344
+
345
+ return description + "\n"
346
+
347
+
348
+ def _extract_text_content_item(content_item: Any) -> str | None:
349
+ """Extract one text fragment from a tool-result content item.
350
+
351
+ Args:
352
+ content_item (Any): Tool-result content item in string, dict, or object form.
353
+
354
+ Returns:
355
+ str | None: Extracted text fragment, or `None` when no text could be derived.
356
+ """
357
+ if content_item is None:
358
+ return None
359
+
360
+ if isinstance(content_item, str):
361
+ return content_item
362
+
363
+ if isinstance(content_item, dict):
364
+ text_value = content_item.get(MCPKeys.text)
365
+ if isinstance(text_value, str):
366
+ return text_value
367
+
368
+ content_value = content_item.get(LLMChatKeys.content)
369
+ if isinstance(content_value, str):
370
+ return content_value
371
+
372
+ return json.dumps(content_item, ensure_ascii=True, default=str)
373
+
374
+ if hasattr(content_item, MCPKeys.text):
375
+ text_value = getattr(content_item, MCPKeys.text)
376
+ if isinstance(text_value, str):
377
+ return text_value
378
+
379
+ if hasattr(content_item, LLMChatKeys.content):
380
+ content_value = getattr(content_item, LLMChatKeys.content)
381
+ if isinstance(content_value, str):
382
+ return content_value
383
+
384
+ return json.dumps(content_item, ensure_ascii=True, default=str)
385
+
386
+
387
+ def extract_text_content(content: Any) -> str:
388
+ """Extract text content from a normalized tool-result payload.
389
+
390
+ Args:
391
+ content (Any): Tool-result content payload in string, list, dict, or object form.
392
+
393
+ Returns:
394
+ str: Joined text extracted from the payload.
395
+ """
396
+ if content is None:
397
+ return ""
398
+
399
+ if isinstance(content, str):
400
+ return content
401
+
402
+ if isinstance(content, list):
403
+ parts = [text for item in content if (text := _extract_text_content_item(item))]
404
+ return "\n".join(parts)
405
+
406
+ extracted_text = _extract_text_content_item(content)
407
+ return extracted_text or ""
@@ -1,7 +1,7 @@
1
1
  import base64
2
2
  from dataclasses import asdict, is_dataclass
3
3
  from io import BytesIO
4
- from typing import Any
4
+ from typing import Any, Literal
5
5
 
6
6
  from PIL import Image
7
7
  from sinapsis_chatbots_base.helpers.llm_keys import LLMChatKeys, MCPKeys
@@ -84,7 +84,7 @@ def normalize_tool_definition(tool: Any) -> dict[str, Any]:
84
84
 
85
85
 
86
86
  def build_packet_message(
87
- role: str,
87
+ role: Literal["system", "user", "assistant", "tool", "developer"],
88
88
  content: Any,
89
89
  name: str | None = None,
90
90
  metadata: dict[str, Any] | None = None,
@@ -0,0 +1,76 @@
1
+ from sinapsis_core.data_containers.data_packet import LLMConversationPacket
2
+ from sinapsis_core.data_containers.model_types import LLMTermination
3
+ from sinapsis_core.utils.logging_utils import sinapsis_logger
4
+
5
+ _FALLBACK_RESPONSE = "I was unable to complete the request due to repeated tool failures."
6
+
7
+
8
+ def get_tool_failure_count(llm_conversation: LLMConversationPacket) -> int:
9
+ """Return the consecutive tool-failure count for one packet.
10
+
11
+ Args:
12
+ llm_conversation (LLMConversationPacket): Conversation packet to inspect.
13
+
14
+ Returns:
15
+ int: Number of consecutive tool rounds that ended with at least one error.
16
+ """
17
+ if llm_conversation.termination is None:
18
+ return 0
19
+ return llm_conversation.termination.consecutive_tool_failures
20
+
21
+
22
+ def update_tool_failure_count(llm_conversation: LLMConversationPacket) -> None:
23
+ """Update consecutive tool-failure count from the current tool results.
24
+
25
+ Args:
26
+ llm_conversation (LLMConversationPacket): Conversation packet whose tool results were updated.
27
+ """
28
+ if not llm_conversation.tool_results:
29
+ return
30
+
31
+ if llm_conversation.termination is None:
32
+ llm_conversation.termination = LLMTermination()
33
+
34
+ if any(result.is_error for result in llm_conversation.tool_results):
35
+ llm_conversation.termination.consecutive_tool_failures += 1
36
+ else:
37
+ llm_conversation.termination.consecutive_tool_failures = 0
38
+
39
+
40
+ def cleanup_conversation_state(llm_conversation: LLMConversationPacket) -> None:
41
+ """Clear transient MCP state from a completed conversation packet.
42
+
43
+ Args:
44
+ llm_conversation (LLMConversationPacket): Conversation packet to clean up.
45
+ """
46
+ llm_conversation.tool_calls = []
47
+ llm_conversation.tool_results = []
48
+ if llm_conversation.termination is not None:
49
+ llm_conversation.termination.consecutive_tool_failures = 0
50
+
51
+
52
+ def stop_packet_after_max_retries(
53
+ llm_conversation: LLMConversationPacket,
54
+ instance_name: str | None = None,
55
+ ) -> None:
56
+ """Stop an MCP loop after too many consecutive tool failures.
57
+
58
+ Args:
59
+ llm_conversation (LLMConversationPacket): Conversation packet to mark as stopped.
60
+ instance_name (str | None): Template instance name for logging context.
61
+ """
62
+ failure_count = get_tool_failure_count(llm_conversation)
63
+ sinapsis_logger.warning(
64
+ f"[{instance_name}] Stopping MCP loop for packet {llm_conversation.id} after "
65
+ f"{failure_count} consecutive tool failures."
66
+ )
67
+
68
+ if llm_conversation.response is None:
69
+ llm_conversation.response = _FALLBACK_RESPONSE
70
+
71
+ if llm_conversation.termination is None:
72
+ llm_conversation.termination = LLMTermination()
73
+
74
+ llm_conversation.termination.is_partial = False
75
+ llm_conversation.termination.stop_reason = "max_tool_retries"
76
+ llm_conversation.termination.consecutive_tool_failures = failure_count
@@ -0,0 +1,92 @@
1
+ from collections.abc import Callable
2
+ from time import perf_counter
3
+ from typing import Any
4
+
5
+ from sinapsis_core.data_containers.model_types import LLMPerformance
6
+
7
+
8
+ def measure_call_latency(function: Callable[..., Any], *args: Any, **kwargs: Any) -> tuple[Any, float]:
9
+ """Execute a synchronous callable and return its result plus wall-clock latency.
10
+
11
+ Args:
12
+ function (Callable[..., _ReturnT]): Callable to execute.
13
+ *args (Any): Positional arguments passed to the callable.
14
+ **kwargs (Any): Keyword arguments passed to the callable.
15
+
16
+ Returns:
17
+ tuple[_ReturnT, float]: Callable result and elapsed seconds.
18
+ """
19
+ start_time = perf_counter()
20
+ result = function(*args, **kwargs)
21
+ latency_seconds = perf_counter() - start_time
22
+ return result, latency_seconds
23
+
24
+
25
+ def compute_tokens_per_second(
26
+ output_tokens: int | None,
27
+ latency_seconds: float | None,
28
+ current_tokens_per_second: float | None = None,
29
+ ) -> float | None:
30
+ """Derive output throughput from token count and latency.
31
+
32
+ Args:
33
+ output_tokens (int | None): Generated output token count.
34
+ latency_seconds (float | None): Measured request latency.
35
+ current_tokens_per_second (float | None): Existing throughput value to preserve when inputs are missing.
36
+
37
+ Returns:
38
+ float | None: Derived throughput when possible.
39
+ """
40
+ if output_tokens is None:
41
+ return current_tokens_per_second
42
+
43
+ if latency_seconds is None or latency_seconds <= 0:
44
+ return None
45
+
46
+ return output_tokens / latency_seconds
47
+
48
+
49
+ def build_client_side_performance(
50
+ current_performance: LLMPerformance | None = None,
51
+ latency_seconds: float | None = None,
52
+ output_tokens: int | None = None,
53
+ time_to_first_token: float | None = None,
54
+ ) -> LLMPerformance | None:
55
+ """Build or update client-side performance metrics for a request.
56
+
57
+ This helper is intended for backends that do not expose native per-request
58
+ performance objects. It stores end-to-end wall-clock latency and derives
59
+ output tokens per second when token counts are available.
60
+
61
+ Args:
62
+ current_performance (LLMPerformance | None): Existing performance object to update.
63
+ latency_seconds (float | None): End-to-end elapsed request time.
64
+ output_tokens (int | None): Generated output token count.
65
+ time_to_first_token (float | None): Optional first-token latency.
66
+
67
+ Returns:
68
+ LLMPerformance | None: Updated performance object when at least one metric is available.
69
+ """
70
+ performance = current_performance or LLMPerformance()
71
+
72
+ if time_to_first_token is not None:
73
+ performance.time_to_first_token = time_to_first_token
74
+
75
+ if latency_seconds is not None:
76
+ performance.latency_seconds = latency_seconds
77
+
78
+ effective_latency = performance.latency_seconds
79
+ performance.tokens_per_second = compute_tokens_per_second(
80
+ output_tokens=output_tokens,
81
+ latency_seconds=effective_latency,
82
+ current_tokens_per_second=performance.tokens_per_second,
83
+ )
84
+
85
+ if (
86
+ performance.time_to_first_token is None
87
+ and performance.latency_seconds is None
88
+ and performance.tokens_per_second is None
89
+ ):
90
+ return None
91
+
92
+ return performance
@@ -1,7 +1,7 @@
1
1
  from enum import Enum
2
2
 
3
3
 
4
- class Tags(Enum):
4
+ class Tags(str, Enum):
5
5
  """Tags for LLM templates."""
6
6
 
7
7
  ANTHROPIC = "anthropic"