sinapsis-chatbots-base 0.2.0__tar.gz → 0.2.1__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.
- {sinapsis_chatbots_base-0.2.0/src/sinapsis_chatbots_base.egg-info → sinapsis_chatbots_base-0.2.1}/PKG-INFO +4 -2
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/README.md +3 -1
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/pyproject.toml +1 -1
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/helpers/performance.py +92 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/__init__.py +2 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/endpoint_llm_completion.py +14 -3
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/endpoint_llm_multimodal.py +69 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/endpoint_llm_streaming_completion.py +333 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base.egg-info}/PKG-INFO +4 -2
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base.egg-info/SOURCES.txt +3 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/LICENSE +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/setup.cfg +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/__init__.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/__init__.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/__init__.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/env_vars.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/llm_conversation.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/llm_keys.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/postprocess_text.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/schemas.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/tags.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/llm_conversation_input.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/llm_multimodal_base.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/llm_runtime_base.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/llm_streaming_base.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/llm_template_base.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/query_contextualize.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/query_contextualize_from_file.py +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base.egg-info/dependency_links.txt +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base.egg-info/requires.txt +0 -0
- {sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/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.
|
|
3
|
+
Version: 0.2.1
|
|
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> •
|
|
@@ -80,6 +80,8 @@ 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
|
+
- **EndpointLLMStreamingCompletion**: Streams chat-completion chunks from OpenAI-compatible endpoints and emits partial packet updates.
|
|
84
|
+
- **EndpointLLMMultiModal**: Sends text + image user turns to OpenAI-compatible multimodal endpoints.
|
|
83
85
|
|
|
84
86
|
> [!TIP]
|
|
85
87
|
> 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> •
|
|
@@ -58,6 +58,8 @@ 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
|
+
- **EndpointLLMStreamingCompletion**: Streams chat-completion chunks from OpenAI-compatible endpoints and emits partial packet updates.
|
|
62
|
+
- **EndpointLLMMultiModal**: Sends text + image user turns to OpenAI-compatible multimodal endpoints.
|
|
61
63
|
|
|
62
64
|
> [!TIP]
|
|
63
65
|
> Use CLI command ``` sinapsis info --all-template-names``` to show a list with all the available Template names installed with Sinapsis Chatbots Base.
|
|
@@ -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
|
|
@@ -5,6 +5,8 @@ _root_lib_path = "sinapsis_chatbots_base.templates"
|
|
|
5
5
|
|
|
6
6
|
_template_lookup = {
|
|
7
7
|
"EndpointLLMCompletion": f"{_root_lib_path}.endpoint_llm_completion",
|
|
8
|
+
"EndpointLLMMultiModal": f"{_root_lib_path}.endpoint_llm_multimodal",
|
|
9
|
+
"EndpointLLMStreamingCompletion": f"{_root_lib_path}.endpoint_llm_streaming_completion",
|
|
8
10
|
"LLMConversationInput": f"{_root_lib_path}.llm_conversation_input",
|
|
9
11
|
"QueryContextualizeFromFile": f"{_root_lib_path}.query_contextualize_from_file",
|
|
10
12
|
}
|
|
@@ -3,6 +3,7 @@ from typing import Any
|
|
|
3
3
|
from openai import OpenAI
|
|
4
4
|
from pydantic import Field
|
|
5
5
|
from sinapsis_chatbots_base.helpers.env_vars import LLM_API_KEY
|
|
6
|
+
from sinapsis_chatbots_base.helpers.performance import build_client_side_performance, measure_call_latency
|
|
6
7
|
from sinapsis_chatbots_base.helpers.schemas import (
|
|
7
8
|
JSON_OBJECT_RESPONSE_FORMAT,
|
|
8
9
|
JSON_SCHEMA_RESPONSE_FORMAT,
|
|
@@ -180,9 +181,13 @@ class EndpointLLMCompletion(LLMTemplateBase):
|
|
|
180
181
|
Returns:
|
|
181
182
|
Any: Raw OpenAI client response object.
|
|
182
183
|
"""
|
|
183
|
-
_ = llm_conversation
|
|
184
184
|
self.logger.debug(f"Endpoint request payload: {payload}")
|
|
185
|
-
|
|
185
|
+
response, latency_seconds = measure_call_latency(self.llm.chat.completions.create, **payload)
|
|
186
|
+
llm_conversation.performance = build_client_side_performance(
|
|
187
|
+
llm_conversation.performance,
|
|
188
|
+
latency_seconds=latency_seconds,
|
|
189
|
+
)
|
|
190
|
+
return response
|
|
186
191
|
|
|
187
192
|
def update_packet_from_response(self, llm_conversation: LLMConversationPacket, response: Any) -> None:
|
|
188
193
|
"""Update the packet from the endpoint response.
|
|
@@ -201,6 +206,7 @@ class EndpointLLMCompletion(LLMTemplateBase):
|
|
|
201
206
|
completion_token_details = (
|
|
202
207
|
getattr(response.usage, "completion_tokens_details", None) if response.usage else None
|
|
203
208
|
)
|
|
209
|
+
output_tokens = getattr(response.usage, "completion_tokens", None) if response.usage else None
|
|
204
210
|
reasoning_tokens = getattr(response.usage, "reasoning_tokens", None) if response.usage else None
|
|
205
211
|
if reasoning_tokens is None and completion_token_details is not None:
|
|
206
212
|
reasoning_tokens = getattr(completion_token_details, "reasoning_tokens", None)
|
|
@@ -219,7 +225,12 @@ class EndpointLLMCompletion(LLMTemplateBase):
|
|
|
219
225
|
if response.usage is not None:
|
|
220
226
|
llm_conversation.usage = LLMUsage(
|
|
221
227
|
input_tokens=getattr(response.usage, "prompt_tokens", None),
|
|
222
|
-
output_tokens=
|
|
228
|
+
output_tokens=output_tokens,
|
|
223
229
|
reasoning_tokens=reasoning_tokens,
|
|
224
230
|
total_tokens=getattr(response.usage, "total_tokens", None),
|
|
225
231
|
)
|
|
232
|
+
|
|
233
|
+
llm_conversation.performance = build_client_side_performance(
|
|
234
|
+
llm_conversation.performance,
|
|
235
|
+
output_tokens=output_tokens,
|
|
236
|
+
)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from sinapsis_chatbots_base.helpers.llm_conversation import image_array_to_data_uri
|
|
4
|
+
from sinapsis_chatbots_base.helpers.tags import Tags
|
|
5
|
+
from sinapsis_chatbots_base.templates.endpoint_llm_completion import EndpointLLMCompletion
|
|
6
|
+
from sinapsis_chatbots_base.templates.llm_multimodal_base import LLMMultimodalTemplateBase
|
|
7
|
+
from sinapsis_core.data_containers.data_packet import DataContainer
|
|
8
|
+
from sinapsis_core.template_base.base_models import OutputTypes, UIPropertiesMetadata
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EndpointLLMMultiModal(LLMMultimodalTemplateBase, EndpointLLMCompletion):
|
|
12
|
+
"""Template for image + text completion using OpenAI-compatible endpoints.
|
|
13
|
+
|
|
14
|
+
Usage example:
|
|
15
|
+
|
|
16
|
+
agent:
|
|
17
|
+
name: my_test_agent
|
|
18
|
+
templates:
|
|
19
|
+
- template_name: InputTemplate
|
|
20
|
+
class_name: InputTemplate
|
|
21
|
+
attributes: {}
|
|
22
|
+
- template_name: EndpointLLMMultiModal
|
|
23
|
+
class_name: EndpointLLMMultiModal
|
|
24
|
+
template_input: LLMConversationInput
|
|
25
|
+
attributes:
|
|
26
|
+
init_args:
|
|
27
|
+
base_url: "http://127.0.0.1:8000/v1"
|
|
28
|
+
llm_model_name: "Qwen/Qwen2.5-VL-3B-Instruct"
|
|
29
|
+
completion_args:
|
|
30
|
+
max_tokens: 1024
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
UIProperties = UIPropertiesMetadata(
|
|
34
|
+
category="Chatbots",
|
|
35
|
+
output_type=OutputTypes.TEXT,
|
|
36
|
+
tags=[Tags.CHATBOTS, Tags.LLM, Tags.TEXT_COMPLETION, Tags.TEXT, Tags.MULTIMODAL, Tags.IMAGE_TO_TEXT],
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
AttributesBaseModel = EndpointLLMCompletion.AttributesBaseModel
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def extract_additional_content(container: DataContainer) -> list[dict[str, Any]]:
|
|
43
|
+
"""Extract image packets as OpenAI-compatible image blocks.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
container (DataContainer): Container holding image packets.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
list[dict[str, Any]]: Encoded image content blocks.
|
|
50
|
+
"""
|
|
51
|
+
return [
|
|
52
|
+
{
|
|
53
|
+
"type": "image_url",
|
|
54
|
+
"image_url": {"url": image_array_to_data_uri(image_packet.content)},
|
|
55
|
+
}
|
|
56
|
+
for image_packet in container.images
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def build_text_content_part(text: str) -> dict[str, str]:
|
|
61
|
+
"""Build an OpenAI-compatible text block.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
text (str): Text content.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
dict[str, str]: Text content block.
|
|
68
|
+
"""
|
|
69
|
+
return {"type": "text", "text": text}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
from collections.abc import AsyncGenerator
|
|
2
|
+
from time import perf_counter
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from openai import AsyncOpenAI
|
|
6
|
+
from sinapsis_chatbots_base.helpers.performance import build_client_side_performance
|
|
7
|
+
from sinapsis_chatbots_base.helpers.tags import Tags
|
|
8
|
+
from sinapsis_chatbots_base.templates.endpoint_llm_completion import EndpointLLMCompletion
|
|
9
|
+
from sinapsis_chatbots_base.templates.llm_streaming_base import LLMStreamingTemplateBase
|
|
10
|
+
from sinapsis_core.data_containers.data_packet import DataContainer, LLMConversationPacket
|
|
11
|
+
from sinapsis_core.data_containers.model_types import LLMProviderInfo, LLMTermination, LLMUsage
|
|
12
|
+
from sinapsis_core.template_base.base_models import OutputTypes, UIPropertiesMetadata
|
|
13
|
+
|
|
14
|
+
_STREAM_START_TIME_KEY = "_endpoint_stream_started_at"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class EndpointLLMStreamingCompletion(LLMStreamingTemplateBase, EndpointLLMCompletion):
|
|
18
|
+
"""Streaming template for OpenAI-compatible chat completion endpoints.
|
|
19
|
+
|
|
20
|
+
Usage example:
|
|
21
|
+
|
|
22
|
+
agent:
|
|
23
|
+
name: my_test_agent
|
|
24
|
+
templates:
|
|
25
|
+
- template_name: InputTemplate
|
|
26
|
+
class_name: InputTemplate
|
|
27
|
+
attributes: {}
|
|
28
|
+
- template_name: EndpointLLMStreamingCompletion
|
|
29
|
+
class_name: EndpointLLMStreamingCompletion
|
|
30
|
+
template_input: InputTemplate
|
|
31
|
+
attributes:
|
|
32
|
+
init_args:
|
|
33
|
+
base_url: "http://127.0.0.1:8000/v1"
|
|
34
|
+
llm_model_name: "Qwen/Qwen3-4B"
|
|
35
|
+
completion_args:
|
|
36
|
+
max_tokens: 1024
|
|
37
|
+
temperature: 0.7
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
UIProperties = UIPropertiesMetadata(
|
|
41
|
+
category="Chatbots",
|
|
42
|
+
output_type=OutputTypes.TEXT,
|
|
43
|
+
tags=[Tags.CHATBOTS, Tags.CONTEXT, Tags.LLM, Tags.TEXT_COMPLETION, Tags.TEXT, Tags.STREAMING],
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
AttributesBaseModel = EndpointLLMCompletion.AttributesBaseModel
|
|
47
|
+
IS_STREAMING = True
|
|
48
|
+
|
|
49
|
+
def init_llm_model(self) -> AsyncOpenAI:
|
|
50
|
+
"""Initialize the async OpenAI-compatible client.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
AsyncOpenAI: Configured async client instance.
|
|
54
|
+
"""
|
|
55
|
+
init_args = self.attributes.init_args.model_dump(exclude={"llm_model_name", "api_key"})
|
|
56
|
+
return AsyncOpenAI(api_key=self._get_api_key(), **init_args)
|
|
57
|
+
|
|
58
|
+
@staticmethod
|
|
59
|
+
def invoke_backend(payload: Any, llm_conversation: LLMConversationPacket) -> Any:
|
|
60
|
+
"""Streaming templates do not use the synchronous backend path.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
payload (Any): Unused synchronous payload.
|
|
64
|
+
llm_conversation (LLMConversationPacket): Unused conversation packet.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
Any: This method does not return a value.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
NotImplementedError: Always raised for the sync path.
|
|
71
|
+
"""
|
|
72
|
+
_ = payload
|
|
73
|
+
_ = llm_conversation
|
|
74
|
+
raise NotImplementedError("Use `async_execute` for EndpointLLMStreamingCompletion.")
|
|
75
|
+
|
|
76
|
+
def build_backend_payload(
|
|
77
|
+
self,
|
|
78
|
+
llm_conversation: LLMConversationPacket,
|
|
79
|
+
container: DataContainer | None = None,
|
|
80
|
+
) -> dict[str, Any]:
|
|
81
|
+
"""Build the request payload for the streaming endpoint.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
llm_conversation (LLMConversationPacket): Conversation packet to convert.
|
|
85
|
+
container (DataContainer | None): Optional container holding shared context.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
dict[str, Any]: Streaming chat completion payload.
|
|
89
|
+
"""
|
|
90
|
+
payload = super().build_backend_payload(llm_conversation, container)
|
|
91
|
+
payload["stream"] = True
|
|
92
|
+
stream_options = payload.get("stream_options")
|
|
93
|
+
if stream_options is None:
|
|
94
|
+
payload["stream_options"] = {"include_usage": True}
|
|
95
|
+
elif isinstance(stream_options, dict) and "include_usage" not in stream_options:
|
|
96
|
+
payload["stream_options"] = {
|
|
97
|
+
**stream_options,
|
|
98
|
+
"include_usage": True,
|
|
99
|
+
}
|
|
100
|
+
return payload
|
|
101
|
+
|
|
102
|
+
async def stream_backend(
|
|
103
|
+
self,
|
|
104
|
+
payload: Any,
|
|
105
|
+
llm_conversation: LLMConversationPacket,
|
|
106
|
+
) -> AsyncGenerator[Any, None]:
|
|
107
|
+
"""Yield raw stream events from the async OpenAI-compatible client.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
payload (Any): Client payload for the request.
|
|
111
|
+
llm_conversation (LLMConversationPacket): Conversation packet being processed.
|
|
112
|
+
|
|
113
|
+
Yields:
|
|
114
|
+
Any: Raw OpenAI-compatible stream events.
|
|
115
|
+
"""
|
|
116
|
+
request_payload = dict(payload)
|
|
117
|
+
request_payload["stream"] = True
|
|
118
|
+
llm_conversation.generic_data[_STREAM_START_TIME_KEY] = perf_counter()
|
|
119
|
+
stream = await self.llm.chat.completions.create(**request_payload)
|
|
120
|
+
async for event in stream:
|
|
121
|
+
yield event
|
|
122
|
+
|
|
123
|
+
@staticmethod
|
|
124
|
+
def _extract_first_choice(event: Any) -> Any | None:
|
|
125
|
+
"""Return the first streamed choice when present.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
event (Any): Raw streamed event.
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
Any | None: First streamed choice when available.
|
|
132
|
+
"""
|
|
133
|
+
choices = getattr(event, "choices", None) or []
|
|
134
|
+
return choices[0] if choices else None
|
|
135
|
+
|
|
136
|
+
@staticmethod
|
|
137
|
+
def _extract_text_from_delta(delta: Any) -> str | None:
|
|
138
|
+
"""Extract text content from a streamed delta block.
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
delta (Any): Provider delta object.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
str | None: Text content extracted from the delta.
|
|
145
|
+
"""
|
|
146
|
+
if delta is None:
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
content = getattr(delta, "content", None)
|
|
150
|
+
if content is None:
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
if isinstance(content, str):
|
|
154
|
+
return content or None
|
|
155
|
+
|
|
156
|
+
if isinstance(content, list):
|
|
157
|
+
parts: list[str] = []
|
|
158
|
+
for item in content:
|
|
159
|
+
text = getattr(item, "text", None)
|
|
160
|
+
if text:
|
|
161
|
+
parts.append(str(text))
|
|
162
|
+
elif isinstance(item, dict) and item.get("text"):
|
|
163
|
+
parts.append(str(item["text"]))
|
|
164
|
+
return "".join(parts) or None
|
|
165
|
+
|
|
166
|
+
return str(content)
|
|
167
|
+
|
|
168
|
+
@staticmethod
|
|
169
|
+
def _extract_reasoning_from_delta(delta: Any) -> str | None:
|
|
170
|
+
"""Extract provider reasoning text from a streamed delta block.
|
|
171
|
+
|
|
172
|
+
Args:
|
|
173
|
+
delta (Any): Provider delta object.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
str | None: Reasoning content extracted from the delta.
|
|
177
|
+
"""
|
|
178
|
+
if delta is None:
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
for attr_name in ("reasoning", "reasoning_content"):
|
|
182
|
+
reasoning = getattr(delta, attr_name, None)
|
|
183
|
+
if reasoning is None:
|
|
184
|
+
continue
|
|
185
|
+
|
|
186
|
+
if isinstance(reasoning, str):
|
|
187
|
+
return reasoning or None
|
|
188
|
+
|
|
189
|
+
if isinstance(reasoning, list):
|
|
190
|
+
parts: list[str] = []
|
|
191
|
+
for item in reasoning:
|
|
192
|
+
text = getattr(item, "text", None)
|
|
193
|
+
if text:
|
|
194
|
+
parts.append(str(text))
|
|
195
|
+
elif isinstance(item, dict) and item.get("text"):
|
|
196
|
+
parts.append(str(item["text"]))
|
|
197
|
+
return "".join(parts) or None
|
|
198
|
+
|
|
199
|
+
return str(reasoning)
|
|
200
|
+
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
def aggregate_stream_event(
|
|
204
|
+
self,
|
|
205
|
+
aggregated_event: dict[str, Any] | None,
|
|
206
|
+
event: Any,
|
|
207
|
+
) -> dict[str, Any]:
|
|
208
|
+
"""Aggregate stream events into one final packet state.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
aggregated_event (dict[str, Any] | None): Aggregated stream state so far.
|
|
212
|
+
event (Any): Current stream event.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
dict[str, Any]: Updated aggregated stream state.
|
|
216
|
+
"""
|
|
217
|
+
if aggregated_event is None:
|
|
218
|
+
aggregated_event = {
|
|
219
|
+
"response_text": "",
|
|
220
|
+
"reasoning_text": "",
|
|
221
|
+
"usage": None,
|
|
222
|
+
"finish_reason": None,
|
|
223
|
+
"model_name": getattr(event, "model", None),
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
choice = self._extract_first_choice(event)
|
|
227
|
+
delta = getattr(choice, "delta", None) if choice is not None else None
|
|
228
|
+
delta_text = self._extract_text_from_delta(delta)
|
|
229
|
+
delta_reasoning = self._extract_reasoning_from_delta(delta)
|
|
230
|
+
|
|
231
|
+
if delta_text:
|
|
232
|
+
aggregated_event["response_text"] = f"{aggregated_event['response_text']}{delta_text}"
|
|
233
|
+
if delta_reasoning:
|
|
234
|
+
aggregated_event["reasoning_text"] = f"{aggregated_event['reasoning_text']}{delta_reasoning}"
|
|
235
|
+
|
|
236
|
+
finish_reason = getattr(choice, "finish_reason", None) if choice is not None else None
|
|
237
|
+
if finish_reason is not None:
|
|
238
|
+
aggregated_event["finish_reason"] = finish_reason
|
|
239
|
+
|
|
240
|
+
usage = getattr(event, "usage", None)
|
|
241
|
+
if usage is not None:
|
|
242
|
+
aggregated_event["usage"] = usage
|
|
243
|
+
|
|
244
|
+
model_name = getattr(event, "model", None)
|
|
245
|
+
if model_name:
|
|
246
|
+
aggregated_event["model_name"] = model_name
|
|
247
|
+
|
|
248
|
+
return aggregated_event
|
|
249
|
+
|
|
250
|
+
def extract_stream_delta(self, event: Any) -> str | None:
|
|
251
|
+
"""Extract the assistant text delta from one streamed event.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
event (Any): Current stream event.
|
|
255
|
+
|
|
256
|
+
Returns:
|
|
257
|
+
str | None: Assistant text delta, if available.
|
|
258
|
+
"""
|
|
259
|
+
choice = self._extract_first_choice(event)
|
|
260
|
+
delta = getattr(choice, "delta", None) if choice is not None else None
|
|
261
|
+
return self._extract_text_from_delta(delta)
|
|
262
|
+
|
|
263
|
+
def update_partial_packet_from_stream(
|
|
264
|
+
self,
|
|
265
|
+
partial_packet: LLMConversationPacket,
|
|
266
|
+
event: Any,
|
|
267
|
+
delta_text: str,
|
|
268
|
+
) -> None:
|
|
269
|
+
"""Update a partial packet from one streamed event.
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
partial_packet (LLMConversationPacket): Packet clone to mutate.
|
|
273
|
+
event (Any): Current stream event.
|
|
274
|
+
delta_text (str): Text delta extracted from the event.
|
|
275
|
+
"""
|
|
276
|
+
choice = self._extract_first_choice(event)
|
|
277
|
+
delta = getattr(choice, "delta", None) if choice is not None else None
|
|
278
|
+
|
|
279
|
+
partial_packet.response = delta_text
|
|
280
|
+
partial_packet.reasoning = self._extract_reasoning_from_delta(delta)
|
|
281
|
+
partial_packet.provider_info = LLMProviderInfo(
|
|
282
|
+
provider="openai_compatible_endpoint",
|
|
283
|
+
model_name=getattr(event, "model", None) or self.attributes.init_args.llm_model_name,
|
|
284
|
+
)
|
|
285
|
+
partial_packet.termination = LLMTermination(
|
|
286
|
+
finish_reason=getattr(choice, "finish_reason", None) if choice is not None else None,
|
|
287
|
+
is_partial=getattr(choice, "finish_reason", None) is None if choice is not None else True,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
def finalize_stream_packet(
|
|
291
|
+
self,
|
|
292
|
+
llm_conversation: LLMConversationPacket,
|
|
293
|
+
aggregated_event: dict[str, Any],
|
|
294
|
+
) -> None:
|
|
295
|
+
"""Finalize one packet after the stream completes.
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
llm_conversation (LLMConversationPacket): Conversation packet to update.
|
|
299
|
+
aggregated_event (dict[str, Any]): Aggregated stream state.
|
|
300
|
+
"""
|
|
301
|
+
usage = aggregated_event.get("usage")
|
|
302
|
+
output_tokens = getattr(usage, "completion_tokens", None) if usage is not None else None
|
|
303
|
+
reasoning_tokens = getattr(usage, "reasoning_tokens", None) if usage is not None else None
|
|
304
|
+
completion_token_details = getattr(usage, "completion_tokens_details", None) if usage is not None else None
|
|
305
|
+
if reasoning_tokens is None and completion_token_details is not None:
|
|
306
|
+
reasoning_tokens = getattr(completion_token_details, "reasoning_tokens", None)
|
|
307
|
+
|
|
308
|
+
llm_conversation.response = aggregated_event["response_text"] or None
|
|
309
|
+
llm_conversation.reasoning = aggregated_event["reasoning_text"] or None
|
|
310
|
+
llm_conversation.provider_info = LLMProviderInfo(
|
|
311
|
+
provider="openai_compatible_endpoint",
|
|
312
|
+
model_name=aggregated_event["model_name"] or self.attributes.init_args.llm_model_name,
|
|
313
|
+
)
|
|
314
|
+
llm_conversation.termination = LLMTermination(
|
|
315
|
+
finish_reason=aggregated_event["finish_reason"],
|
|
316
|
+
is_partial=False,
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
if usage is not None:
|
|
320
|
+
llm_conversation.usage = LLMUsage(
|
|
321
|
+
input_tokens=getattr(usage, "prompt_tokens", None),
|
|
322
|
+
output_tokens=output_tokens,
|
|
323
|
+
reasoning_tokens=reasoning_tokens,
|
|
324
|
+
total_tokens=getattr(usage, "total_tokens", None),
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
start_time = llm_conversation.generic_data.pop(_STREAM_START_TIME_KEY, None)
|
|
328
|
+
latency_seconds = perf_counter() - start_time if isinstance(start_time, (int, float)) else None
|
|
329
|
+
llm_conversation.performance = build_client_side_performance(
|
|
330
|
+
llm_conversation.performance,
|
|
331
|
+
latency_seconds=latency_seconds,
|
|
332
|
+
output_tokens=output_tokens,
|
|
333
|
+
)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sinapsis-chatbots-base
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
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> •
|
|
@@ -80,6 +80,8 @@ 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
|
+
- **EndpointLLMStreamingCompletion**: Streams chat-completion chunks from OpenAI-compatible endpoints and emits partial packet updates.
|
|
84
|
+
- **EndpointLLMMultiModal**: Sends text + image user turns to OpenAI-compatible multimodal endpoints.
|
|
83
85
|
|
|
84
86
|
> [!TIP]
|
|
85
87
|
> Use CLI command ``` sinapsis info --all-template-names``` to show a list with all the available Template names installed with Sinapsis Chatbots Base.
|
|
@@ -12,11 +12,14 @@ src/sinapsis_chatbots_base/helpers/__init__.py
|
|
|
12
12
|
src/sinapsis_chatbots_base/helpers/env_vars.py
|
|
13
13
|
src/sinapsis_chatbots_base/helpers/llm_conversation.py
|
|
14
14
|
src/sinapsis_chatbots_base/helpers/llm_keys.py
|
|
15
|
+
src/sinapsis_chatbots_base/helpers/performance.py
|
|
15
16
|
src/sinapsis_chatbots_base/helpers/postprocess_text.py
|
|
16
17
|
src/sinapsis_chatbots_base/helpers/schemas.py
|
|
17
18
|
src/sinapsis_chatbots_base/helpers/tags.py
|
|
18
19
|
src/sinapsis_chatbots_base/templates/__init__.py
|
|
19
20
|
src/sinapsis_chatbots_base/templates/endpoint_llm_completion.py
|
|
21
|
+
src/sinapsis_chatbots_base/templates/endpoint_llm_multimodal.py
|
|
22
|
+
src/sinapsis_chatbots_base/templates/endpoint_llm_streaming_completion.py
|
|
20
23
|
src/sinapsis_chatbots_base/templates/llm_conversation_input.py
|
|
21
24
|
src/sinapsis_chatbots_base/templates/llm_multimodal_base.py
|
|
22
25
|
src/sinapsis_chatbots_base/templates/llm_runtime_base.py
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{sinapsis_chatbots_base-0.2.0 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|