sinapsis-chatbots-base 0.1.13__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.1/PKG-INFO +134 -0
- sinapsis_chatbots_base-0.2.1/README.md +112 -0
- sinapsis_chatbots_base-0.2.1/pyproject.toml +48 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/env_vars.py +4 -4
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/helpers/llm_conversation.py +169 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/llm_keys.py +3 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/helpers/performance.py +92 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/helpers/postprocess_text.py +20 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/helpers/schemas.py +185 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/templates/__init__.py +3 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/endpoint_llm_completion.py +236 -0
- 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.1/src/sinapsis_chatbots_base/templates/llm_conversation_input.py +111 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/llm_multimodal_base.py +62 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/llm_runtime_base.py +37 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/llm_streaming_base.py +119 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/llm_template_base.py +441 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/query_contextualize.py +119 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base/templates/query_contextualize_from_file.py +121 -0
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base.egg-info/PKG-INFO +134 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base.egg-info/SOURCES.txt +10 -1
- sinapsis_chatbots_base-0.2.1/src/sinapsis_chatbots_base.egg-info/requires.txt +11 -0
- sinapsis_chatbots_base-0.1.13/PKG-INFO +0 -220
- sinapsis_chatbots_base-0.1.13/README.md +0 -190
- sinapsis_chatbots_base-0.1.13/pyproject.toml +0 -94
- sinapsis_chatbots_base-0.1.13/src/sinapsis_chatbots_base/helpers/postprocess_text.py +0 -29
- sinapsis_chatbots_base-0.1.13/src/sinapsis_chatbots_base/templates/endpoint_llm_completion.py +0 -304
- sinapsis_chatbots_base-0.1.13/src/sinapsis_chatbots_base/templates/llm_text_completion_base.py +0 -319
- sinapsis_chatbots_base-0.1.13/src/sinapsis_chatbots_base/templates/query_contextualize.py +0 -103
- sinapsis_chatbots_base-0.1.13/src/sinapsis_chatbots_base/templates/query_contextualize_from_file.py +0 -82
- sinapsis_chatbots_base-0.1.13/src/sinapsis_chatbots_base.egg-info/PKG-INFO +0 -220
- sinapsis_chatbots_base-0.1.13/src/sinapsis_chatbots_base.egg-info/requires.txt +0 -19
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/LICENSE +0 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/setup.cfg +0 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/__init__.py +0 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/__init__.py +0 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/__init__.py +0 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base/helpers/tags.py +0 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base.egg-info/dependency_links.txt +0 -0
- {sinapsis_chatbots_base-0.1.13 → sinapsis_chatbots_base-0.2.1}/src/sinapsis_chatbots_base.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sinapsis-chatbots-base
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Sinapsis templates for shared chatbot foundations.
|
|
5
|
+
Author-email: SinapsisAI <dev@sinapsis.tech>
|
|
6
|
+
Project-URL: Homepage, https://sinapsis.tech
|
|
7
|
+
Project-URL: Documentation, https://docs.sinapsis.tech/docs
|
|
8
|
+
Project-URL: Tutorials, https://docs.sinapsis.tech/tutorials
|
|
9
|
+
Project-URL: Repository, https://github.com/Sinapsis-AI/sinapsis-chatbots.git
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: sinapsis>=0.2.10
|
|
14
|
+
Provides-Extra: torch
|
|
15
|
+
Requires-Dist: torch>=2.6.0; extra == "torch"
|
|
16
|
+
Provides-Extra: endpoint
|
|
17
|
+
Requires-Dist: openai>=1.109.1; extra == "endpoint"
|
|
18
|
+
Provides-Extra: all
|
|
19
|
+
Requires-Dist: sinapsis-chatbots-base[torch]; extra == "all"
|
|
20
|
+
Requires-Dist: sinapsis-chatbots-base[endpoint]; extra == "all"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
<h1 align="center">
|
|
24
|
+
<br>
|
|
25
|
+
<a href="https://sinapsis.tech/">
|
|
26
|
+
<img
|
|
27
|
+
src="https://github.com/Sinapsis-AI/brand-resources/blob/main/sinapsis_logo/4x/logo.png?raw=true"
|
|
28
|
+
alt="" width="300">
|
|
29
|
+
</a>
|
|
30
|
+
<br>
|
|
31
|
+
Sinapsis Chatbots Base
|
|
32
|
+
<br>
|
|
33
|
+
</h1>
|
|
34
|
+
|
|
35
|
+
<h4 align="center">Sinapsis templates for chatbot inputs, contextualization, and endpoint-backed completions.</h4>
|
|
36
|
+
|
|
37
|
+
<p align="center">
|
|
38
|
+
<a href="#installation">🐍 Installation</a> •
|
|
39
|
+
<a href="#features">🚀 Features</a> •
|
|
40
|
+
<a href="#example">📚 Usage example</a> •
|
|
41
|
+
<a href="#documentation">📙 Documentation</a> •
|
|
42
|
+
<a href="#license">🔍 License</a>
|
|
43
|
+
</p>
|
|
44
|
+
|
|
45
|
+
The `sinapsis-chatbots-base` package provides the shared chatbot foundation. It includes the base abstractions for LLM templates together with the core templates for building `LLMConversationPacket` inputs, adding document context from preloaded data, and sending chat requests to OpenAI-compatible HTTP endpoints.
|
|
46
|
+
|
|
47
|
+
<h2 id="installation">🐍 Installation</h2>
|
|
48
|
+
|
|
49
|
+
Install using your preferred package manager. We strongly recommend using <code>uv</code>.
|
|
50
|
+
|
|
51
|
+
Install the base package:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
uv pip install sinapsis-chatbots-base --extra-index-url https://pypi.sinapsis.tech
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Or with raw <code>pip</code>:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install sinapsis-chatbots-base --extra-index-url https://pypi.sinapsis.tech
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
> [!IMPORTANT]
|
|
64
|
+
> `EndpointLLMCompletion` requires the optional `endpoint` extra:
|
|
65
|
+
>
|
|
66
|
+
> ```bash
|
|
67
|
+
> uv pip install sinapsis-chatbots-base[endpoint] --extra-index-url https://pypi.sinapsis.tech
|
|
68
|
+
> ```
|
|
69
|
+
>
|
|
70
|
+
> `all` installs every optional dependency exposed by the package:
|
|
71
|
+
>
|
|
72
|
+
> ```bash
|
|
73
|
+
> uv pip install sinapsis-chatbots-base[all] --extra-index-url https://pypi.sinapsis.tech
|
|
74
|
+
> ```
|
|
75
|
+
|
|
76
|
+
<h2 id="features">🚀 Features</h2>
|
|
77
|
+
|
|
78
|
+
<h3>Templates Supported</h3>
|
|
79
|
+
|
|
80
|
+
- **LLMConversationInput**: Creates an `LLMConversationPacket` from a prompt, system prompt, and packet metadata.
|
|
81
|
+
- **QueryContextualizeFromFile**: Builds packet contexts from files or documents already loaded into the container.
|
|
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.
|
|
85
|
+
|
|
86
|
+
> [!TIP]
|
|
87
|
+
> Use CLI command ``` sinapsis info --all-template-names``` to show a list with all the available Template names installed with Sinapsis Chatbots Base.
|
|
88
|
+
|
|
89
|
+
<h2 id="example">📚 Usage example</h2>
|
|
90
|
+
|
|
91
|
+
The following agent builds an `LLMConversationPacket` and sends it to an OpenAI-compatible endpoint.
|
|
92
|
+
|
|
93
|
+
<details id='usage'><summary><strong><span style="font-size: 1.0em;"> Config</span></strong></summary>
|
|
94
|
+
|
|
95
|
+
```yaml
|
|
96
|
+
agent:
|
|
97
|
+
name: openai_api_agent
|
|
98
|
+
|
|
99
|
+
templates:
|
|
100
|
+
- template_name: InputTemplate
|
|
101
|
+
class_name: InputTemplate
|
|
102
|
+
attributes: {}
|
|
103
|
+
|
|
104
|
+
- template_name: LLMConversationInput
|
|
105
|
+
class_name: LLMConversationInput
|
|
106
|
+
template_input: InputTemplate
|
|
107
|
+
attributes:
|
|
108
|
+
prompt: Give three short tips for staying organized during a busy week.
|
|
109
|
+
system_prompt: You are a helpful assistant.
|
|
110
|
+
|
|
111
|
+
- template_name: EndpointLLMCompletion
|
|
112
|
+
class_name: EndpointLLMCompletion
|
|
113
|
+
template_input: LLMConversationInput
|
|
114
|
+
attributes:
|
|
115
|
+
init_args:
|
|
116
|
+
base_url: "https://api.openai.com/v1"
|
|
117
|
+
llm_model_name: "gpt-4o-mini"
|
|
118
|
+
completion_args:
|
|
119
|
+
max_tokens: 2048
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
</details>
|
|
123
|
+
|
|
124
|
+
<h2 id="documentation">📙 Documentation</h2>
|
|
125
|
+
|
|
126
|
+
Documentation for this and other sinapsis packages is available on the [sinapsis website](https://docs.sinapsis.tech/docs)
|
|
127
|
+
|
|
128
|
+
Tutorials for different projects within sinapsis are available at [sinapsis tutorials page](https://docs.sinapsis.tech/tutorials)
|
|
129
|
+
|
|
130
|
+
<h2 id="license">🔍 License</h2>
|
|
131
|
+
|
|
132
|
+
This project is licensed under the AGPLv3 license, which encourages open collaboration and sharing. For more details, please refer to the [LICENSE](LICENSE) file.
|
|
133
|
+
|
|
134
|
+
For commercial use, please refer to our [official Sinapsis website](https://sinapsis.tech) for information on obtaining a commercial license.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
<h1 align="center">
|
|
2
|
+
<br>
|
|
3
|
+
<a href="https://sinapsis.tech/">
|
|
4
|
+
<img
|
|
5
|
+
src="https://github.com/Sinapsis-AI/brand-resources/blob/main/sinapsis_logo/4x/logo.png?raw=true"
|
|
6
|
+
alt="" width="300">
|
|
7
|
+
</a>
|
|
8
|
+
<br>
|
|
9
|
+
Sinapsis Chatbots Base
|
|
10
|
+
<br>
|
|
11
|
+
</h1>
|
|
12
|
+
|
|
13
|
+
<h4 align="center">Sinapsis templates for chatbot inputs, contextualization, and endpoint-backed completions.</h4>
|
|
14
|
+
|
|
15
|
+
<p align="center">
|
|
16
|
+
<a href="#installation">🐍 Installation</a> •
|
|
17
|
+
<a href="#features">🚀 Features</a> •
|
|
18
|
+
<a href="#example">📚 Usage example</a> •
|
|
19
|
+
<a href="#documentation">📙 Documentation</a> •
|
|
20
|
+
<a href="#license">🔍 License</a>
|
|
21
|
+
</p>
|
|
22
|
+
|
|
23
|
+
The `sinapsis-chatbots-base` package provides the shared chatbot foundation. It includes the base abstractions for LLM templates together with the core templates for building `LLMConversationPacket` inputs, adding document context from preloaded data, and sending chat requests to OpenAI-compatible HTTP endpoints.
|
|
24
|
+
|
|
25
|
+
<h2 id="installation">🐍 Installation</h2>
|
|
26
|
+
|
|
27
|
+
Install using your preferred package manager. We strongly recommend using <code>uv</code>.
|
|
28
|
+
|
|
29
|
+
Install the base package:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
uv pip install sinapsis-chatbots-base --extra-index-url https://pypi.sinapsis.tech
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Or with raw <code>pip</code>:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install sinapsis-chatbots-base --extra-index-url https://pypi.sinapsis.tech
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
> [!IMPORTANT]
|
|
42
|
+
> `EndpointLLMCompletion` requires the optional `endpoint` extra:
|
|
43
|
+
>
|
|
44
|
+
> ```bash
|
|
45
|
+
> uv pip install sinapsis-chatbots-base[endpoint] --extra-index-url https://pypi.sinapsis.tech
|
|
46
|
+
> ```
|
|
47
|
+
>
|
|
48
|
+
> `all` installs every optional dependency exposed by the package:
|
|
49
|
+
>
|
|
50
|
+
> ```bash
|
|
51
|
+
> uv pip install sinapsis-chatbots-base[all] --extra-index-url https://pypi.sinapsis.tech
|
|
52
|
+
> ```
|
|
53
|
+
|
|
54
|
+
<h2 id="features">🚀 Features</h2>
|
|
55
|
+
|
|
56
|
+
<h3>Templates Supported</h3>
|
|
57
|
+
|
|
58
|
+
- **LLMConversationInput**: Creates an `LLMConversationPacket` from a prompt, system prompt, and packet metadata.
|
|
59
|
+
- **QueryContextualizeFromFile**: Builds packet contexts from files or documents already loaded into the container.
|
|
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.
|
|
63
|
+
|
|
64
|
+
> [!TIP]
|
|
65
|
+
> Use CLI command ``` sinapsis info --all-template-names``` to show a list with all the available Template names installed with Sinapsis Chatbots Base.
|
|
66
|
+
|
|
67
|
+
<h2 id="example">📚 Usage example</h2>
|
|
68
|
+
|
|
69
|
+
The following agent builds an `LLMConversationPacket` and sends it to an OpenAI-compatible endpoint.
|
|
70
|
+
|
|
71
|
+
<details id='usage'><summary><strong><span style="font-size: 1.0em;"> Config</span></strong></summary>
|
|
72
|
+
|
|
73
|
+
```yaml
|
|
74
|
+
agent:
|
|
75
|
+
name: openai_api_agent
|
|
76
|
+
|
|
77
|
+
templates:
|
|
78
|
+
- template_name: InputTemplate
|
|
79
|
+
class_name: InputTemplate
|
|
80
|
+
attributes: {}
|
|
81
|
+
|
|
82
|
+
- template_name: LLMConversationInput
|
|
83
|
+
class_name: LLMConversationInput
|
|
84
|
+
template_input: InputTemplate
|
|
85
|
+
attributes:
|
|
86
|
+
prompt: Give three short tips for staying organized during a busy week.
|
|
87
|
+
system_prompt: You are a helpful assistant.
|
|
88
|
+
|
|
89
|
+
- template_name: EndpointLLMCompletion
|
|
90
|
+
class_name: EndpointLLMCompletion
|
|
91
|
+
template_input: LLMConversationInput
|
|
92
|
+
attributes:
|
|
93
|
+
init_args:
|
|
94
|
+
base_url: "https://api.openai.com/v1"
|
|
95
|
+
llm_model_name: "gpt-4o-mini"
|
|
96
|
+
completion_args:
|
|
97
|
+
max_tokens: 2048
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
</details>
|
|
101
|
+
|
|
102
|
+
<h2 id="documentation">📙 Documentation</h2>
|
|
103
|
+
|
|
104
|
+
Documentation for this and other sinapsis packages is available on the [sinapsis website](https://docs.sinapsis.tech/docs)
|
|
105
|
+
|
|
106
|
+
Tutorials for different projects within sinapsis are available at [sinapsis tutorials page](https://docs.sinapsis.tech/tutorials)
|
|
107
|
+
|
|
108
|
+
<h2 id="license">🔍 License</h2>
|
|
109
|
+
|
|
110
|
+
This project is licensed under the AGPLv3 license, which encourages open collaboration and sharing. For more details, please refer to the [LICENSE](LICENSE) file.
|
|
111
|
+
|
|
112
|
+
For commercial use, please refer to our [official Sinapsis website](https://sinapsis.tech) for information on obtaining a commercial license.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sinapsis-chatbots-base"
|
|
3
|
+
version = "0.2.1"
|
|
4
|
+
description = "Sinapsis templates for shared chatbot foundations."
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "SinapsisAI", email = "dev@sinapsis.tech"},
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
dependencies = [
|
|
12
|
+
"sinapsis>=0.2.10",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
|
|
17
|
+
torch = [
|
|
18
|
+
"torch>=2.6.0",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
endpoint = [
|
|
22
|
+
"openai>=1.109.1",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
all = [
|
|
26
|
+
"sinapsis-chatbots-base[torch]",
|
|
27
|
+
"sinapsis-chatbots-base[endpoint]",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[dependency-groups]
|
|
31
|
+
dev = [
|
|
32
|
+
"ruff>=0.8.3",
|
|
33
|
+
"pre-commit>=4.0.1",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[[tool.uv.index]]
|
|
37
|
+
name = "sinapsis"
|
|
38
|
+
url = "https://pypi.sinapsis.tech/"
|
|
39
|
+
|
|
40
|
+
[build-system]
|
|
41
|
+
requires = ["setuptools"]
|
|
42
|
+
build-backend = "setuptools.build_meta"
|
|
43
|
+
|
|
44
|
+
[project.urls]
|
|
45
|
+
Homepage = "https://sinapsis.tech"
|
|
46
|
+
Documentation = "https://docs.sinapsis.tech/docs"
|
|
47
|
+
Tutorials = "https://docs.sinapsis.tech/tutorials"
|
|
48
|
+
Repository = "https://github.com/Sinapsis-AI/sinapsis-chatbots.git"
|
|
@@ -9,7 +9,7 @@ class _ChatbotsBaseEnvVars(BaseModel):
|
|
|
9
9
|
|
|
10
10
|
HF_TOKEN: EnvVarEntry = EnvVarEntry(
|
|
11
11
|
var_name="HF_TOKEN",
|
|
12
|
-
default_value="
|
|
12
|
+
default_value="",
|
|
13
13
|
allowed_values=None,
|
|
14
14
|
description="Set API key for HuggingFace API",
|
|
15
15
|
)
|
|
@@ -36,12 +36,12 @@ def __getattr__(name: str) -> Any:
|
|
|
36
36
|
Args:
|
|
37
37
|
name (str): The name of the environment variable.
|
|
38
38
|
|
|
39
|
+
Returns:
|
|
40
|
+
Any: The default value of the requested environment variable.
|
|
41
|
+
|
|
39
42
|
Raises:
|
|
40
43
|
AttributeError: If the requested attribute `name` is not a defined
|
|
41
44
|
environment variable.
|
|
42
|
-
|
|
43
|
-
Returns:
|
|
44
|
-
Any: The default value of the requested environment variable.
|
|
45
45
|
"""
|
|
46
46
|
if name in ChatbotsBaseEnvVars.model_fields:
|
|
47
47
|
return ChatbotsBaseEnvVars.model_fields[name].default.value
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
from dataclasses import asdict, is_dataclass
|
|
3
|
+
from io import BytesIO
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from PIL import Image
|
|
7
|
+
from sinapsis_chatbots_base.helpers.llm_keys import LLMChatKeys, MCPKeys
|
|
8
|
+
from sinapsis_core.data_containers.data_packet import LLMConversationPacket
|
|
9
|
+
from sinapsis_core.data_containers.model_types import LLMMessage
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def extract_packet_identity(llm_conversation: LLMConversationPacket, exclude: set[str] | None = None) -> dict[str, Any]:
|
|
13
|
+
"""Extract identity values from a conversation packet.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
llm_conversation (LLMConversationPacket): Conversation packet.
|
|
17
|
+
exclude (set[str] | None): Identity keys to exclude.
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
dict[str, Any]: Packet identity values excluding `None` entries.
|
|
21
|
+
"""
|
|
22
|
+
if llm_conversation.identity is None:
|
|
23
|
+
return {}
|
|
24
|
+
|
|
25
|
+
excluded = exclude or set()
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
key: value
|
|
29
|
+
for key, value in asdict(llm_conversation.identity).items()
|
|
30
|
+
if key not in excluded and value is not None
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def build_chat_message(role: str, msg_content: Any) -> dict[str, Any]:
|
|
35
|
+
"""Build a provider-compatible chat message payload.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
role (str): Message role.
|
|
39
|
+
msg_content (Any): Message content.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
dict[str, Any]: Normalized chat message dictionary.
|
|
43
|
+
"""
|
|
44
|
+
return {LLMChatKeys.role: role, LLMChatKeys.content: msg_content}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def build_current_turn_messages(llm_conversation: LLMConversationPacket) -> list[dict[str, Any]]:
|
|
48
|
+
"""Build the current user and assistant turn from a packet.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
llm_conversation (LLMConversationPacket): Conversation packet.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
list[dict[str, Any]]: Available user and assistant messages.
|
|
55
|
+
"""
|
|
56
|
+
messages: list[dict[str, Any]] = []
|
|
57
|
+
if llm_conversation.content is not None:
|
|
58
|
+
messages.append(build_chat_message(role=LLMChatKeys.user_value, msg_content=llm_conversation.content))
|
|
59
|
+
if llm_conversation.response is not None:
|
|
60
|
+
messages.append(build_chat_message(role=LLMChatKeys.assistant_value, msg_content=llm_conversation.response))
|
|
61
|
+
return messages
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def normalize_tool_definition(tool: Any) -> dict[str, Any]:
|
|
65
|
+
"""Normalize one tool definition into a dictionary.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
tool (Any): Tool definition as a dict, dataclass instance, or object with tool attributes.
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
dict[str, Any]: Normalized tool definition dictionary.
|
|
72
|
+
"""
|
|
73
|
+
if isinstance(tool, dict):
|
|
74
|
+
return tool
|
|
75
|
+
|
|
76
|
+
if not isinstance(tool, type) and is_dataclass(tool):
|
|
77
|
+
return asdict(tool)
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
MCPKeys.name: getattr(tool, MCPKeys.name),
|
|
81
|
+
MCPKeys.description: getattr(tool, MCPKeys.description, ""),
|
|
82
|
+
MCPKeys.input_schema: getattr(tool, MCPKeys.input_schema, {}),
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def build_packet_message(
|
|
87
|
+
role: str,
|
|
88
|
+
content: Any,
|
|
89
|
+
name: str | None = None,
|
|
90
|
+
metadata: dict[str, Any] | None = None,
|
|
91
|
+
) -> LLMMessage | None:
|
|
92
|
+
"""Build an `LLMMessage` suitable for packet history persistence.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
role (str): Message role.
|
|
96
|
+
content (Any): Message content.
|
|
97
|
+
name (str | None): Optional speaker name.
|
|
98
|
+
metadata (dict[str, Any] | None): Optional auxiliary metadata.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
LLMMessage | None: Persistable packet message when content is present.
|
|
102
|
+
"""
|
|
103
|
+
if content is None:
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
return LLMMessage(role=role, content=content, name=name, metadata=metadata or {})
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def is_partial_llm_turn(llm_conversation: LLMConversationPacket) -> bool:
|
|
110
|
+
"""Return whether a packet represents an in-progress assistant turn.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
llm_conversation (LLMConversationPacket): Conversation packet to inspect.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
bool: `True` when the packet termination state is marked partial.
|
|
117
|
+
"""
|
|
118
|
+
return bool(llm_conversation.termination and llm_conversation.termination.is_partial)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def combine_assistant_responses(previous_response: str | None, current_response: str | None) -> str | None:
|
|
122
|
+
"""Combine partial and current assistant text into one response string.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
previous_response (str | None): Previously accumulated assistant text.
|
|
126
|
+
current_response (str | None): Current assistant text.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
str | None: Combined assistant text.
|
|
130
|
+
"""
|
|
131
|
+
if previous_response and current_response:
|
|
132
|
+
return f"{previous_response}\n{current_response}"
|
|
133
|
+
if previous_response:
|
|
134
|
+
return previous_response
|
|
135
|
+
return current_response
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def image_array_to_base64(image_array: Any, fmt: str = "JPEG") -> str:
|
|
139
|
+
"""Convert an image array into a base64 string.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
image_array (Any): Image packet content, typically a numpy array.
|
|
143
|
+
fmt (str): Output image format for encoding.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
str: Base64-encoded image bytes.
|
|
147
|
+
"""
|
|
148
|
+
image = Image.fromarray(image_array)
|
|
149
|
+
if fmt.upper() == "JPEG" and image.mode not in {"RGB", "L"}:
|
|
150
|
+
image = image.convert("RGB")
|
|
151
|
+
|
|
152
|
+
buffer = BytesIO()
|
|
153
|
+
image.save(buffer, format=fmt)
|
|
154
|
+
return base64.b64encode(buffer.getvalue()).decode("utf-8")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def image_array_to_data_uri(image_array: Any, fmt: str = "JPEG") -> str:
|
|
158
|
+
"""Convert an image array into a base64 data URI.
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
image_array (Any): Image packet content, typically a numpy array.
|
|
162
|
+
fmt (str): Output image format for encoding.
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
str: Base64 data URI.
|
|
166
|
+
"""
|
|
167
|
+
mime = f"image/{fmt.lower()}"
|
|
168
|
+
encoded = image_array_to_base64(image_array, fmt=fmt)
|
|
169
|
+
return f"data:{mime};base64,{encoded}"
|
|
@@ -17,9 +17,12 @@ class LLMChatKeys:
|
|
|
17
17
|
choices: Literal["choices"] = "choices"
|
|
18
18
|
message: Literal["message"] = "message"
|
|
19
19
|
llm_responses: Literal["llm_responses"] = "llm_responses"
|
|
20
|
+
name: Literal["name"] = "name"
|
|
21
|
+
tool_call_id: Literal["tool_call_id"] = "tool_call_id"
|
|
20
22
|
system_value: Literal["system"] = "system"
|
|
21
23
|
user_value: Literal["user"] = "user"
|
|
22
24
|
assistant_value: Literal["assistant"] = "assistant"
|
|
25
|
+
tool_value: Literal["tool"] = "tool"
|
|
23
26
|
|
|
24
27
|
|
|
25
28
|
@dataclass
|
|
@@ -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
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
COMMON_CONTROL_MARKERS_PATTERN = re.compile(
|
|
4
|
+
r"(<\|[^|>]+?\|>|<\uFF5C[^\uFF5C>]+?\uFF5C>|</?s>|\[/?INST\]|<<SYS>>|<</SYS>>)"
|
|
5
|
+
)
|
|
6
|
+
EXCESSIVE_NEWLINES_PATTERN = re.compile(r"\n{3,}")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def postprocess_text(input_text: str) -> str:
|
|
10
|
+
"""Remove common control markers from generated text.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
input_text (str): Raw model text to normalize.
|
|
14
|
+
|
|
15
|
+
Returns:
|
|
16
|
+
str: Cleaned response text.
|
|
17
|
+
"""
|
|
18
|
+
cleaned_text = COMMON_CONTROL_MARKERS_PATTERN.sub("", input_text)
|
|
19
|
+
cleaned_text = EXCESSIVE_NEWLINES_PATTERN.sub("\n\n", cleaned_text)
|
|
20
|
+
return cleaned_text.strip()
|