tellm 4.0.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.
@@ -0,0 +1,4 @@
1
+ OPENROUTER_API_KEY=twoj_key
2
+ LLM_MODEL=openrouter/qwen/qwen3-coder-next
3
+ HOST=localhost
4
+ PORT=8000
tellm-4.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ include README.md
2
+ include LICENSE
3
+ include requirements.txt
4
+ include .env.example
5
+ recursive-include tests *.py
6
+ global-exclude __pycache__
7
+ global-exclude *.py[cod]
tellm-4.0.1/PKG-INFO ADDED
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: tellm
3
+ Version: 4.0.1
4
+ Requires-Python: >=3.8
5
+ License-File: LICENSE
6
+ Requires-Dist: litellm>=1.0.0
7
+ Requires-Dist: websockets>=12.0
8
+ Requires-Dist: pyttsx3>=2.90
9
+ Requires-Dist: python-dotenv>=1.0.0
10
+ Requires-Dist: faster-whisper>=0.11.0
11
+ Dynamic: license-file
12
+ Dynamic: requires-dist
13
+ Dynamic: requires-python
tellm-4.0.1/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # tellm v4 - STT+TTS+LLM+SQLite+HTML
2
+
3
+
4
+ ## AI Cost Tracking
5
+
6
+ ![PyPI](https://img.shields.io/badge/pypi-costs-blue) ![Version](https://img.shields.io/badge/version-4.0.1-blue) ![Python](https://img.shields.io/badge/python-3.9+-blue) ![License](https://img.shields.io/badge/license-Apache--2.0-green)
7
+ ![AI Cost](https://img.shields.io/badge/AI%20Cost-$0.15-orange) ![Human Time](https://img.shields.io/badge/Human%20Time-1.0h-blue) ![Model](https://img.shields.io/badge/Model-openrouter%2Fqwen%2Fqwen3--coder--next-lightgrey)
8
+
9
+ - 🤖 **LLM usage:** $0.1500 (1 commits)
10
+ - 👤 **Human dev:** ~$100 (1.0h @ $100/h, 30min dedup)
11
+
12
+ Generated on 2026-06-14 using [openrouter/qwen/qwen3-coder-next](https://openrouter.ai/qwen/qwen3-coder-next)
13
+
14
+ ---
15
+
16
+ ## Instalacja
17
+ ```bash
18
+ tar -xzf tellm-4.0.1.tar.gz
19
+ cd tellm-4.0.1
20
+ pip install -e .
21
+ ```
22
+
23
+ ## Uruchomienie
24
+ ```bash
25
+ cp .env.example .env
26
+ # ustaw OPENROUTER_API_KEY w .env
27
+ tellm-bot --host localhost --port 8008
28
+ ```
29
+
30
+ ## Użycie
31
+ ```python
32
+ from tellm import create_bot
33
+ bot = create_bot(db_path="tellm.db")
34
+ view = bot.generate_view("trans", task, result)
35
+ html = view.to_html()
36
+ ```
37
+
38
+
39
+ ## License
40
+
41
+ Licensed under Apache-2.0.
@@ -0,0 +1,8 @@
1
+ from .bot import TellmBot, Task, TaskType, ViewData
2
+ from .server import TellmServer
3
+ from .config import load_config
4
+ __version__ = "4.0.1"
5
+ def create_bot(db_path="tellm.db"): return TellmBot(db_path=db_path)
6
+ def run_server(host="localhost", port=8000, db_path="tellm.db"):
7
+ server = TellmServer(host, port, db_path)
8
+ server.run()
tellm-4.0.1/bot.py ADDED
@@ -0,0 +1,209 @@
1
+ """tellm v4"""
2
+ import inspect
3
+ import html as html_lib
4
+ import json
5
+ import os
6
+ import sqlite3
7
+ import tempfile
8
+ from typing import Dict, List, Any, Callable, Optional
9
+ from dataclasses import dataclass, field
10
+ from enum import Enum
11
+
12
+ from .config import Config, load_config
13
+
14
+ class TaskType(Enum):
15
+ NOW = "now"
16
+ CRON = "cron"
17
+ EVENT_TRIGGER = "event_trigger"
18
+
19
+ @dataclass
20
+ class Task:
21
+ type: TaskType
22
+ function_name: str
23
+ parameters: Dict[str, Any]
24
+ code: str = ""
25
+ schedule: str = ""
26
+
27
+ @dataclass
28
+ class ViewData:
29
+ transcription: str
30
+ task: Task
31
+ result: Any
32
+ generated_code: str = ""
33
+ performance_score: float = 0.0
34
+ view_elements: List[Dict] = field(default_factory=list)
35
+
36
+ def to_dict(self) -> Dict:
37
+ return {"transcription": self.transcription, "task": {"type": self.task.type.value, "function": self.task.function_name, "parameters": self.task.parameters}, "result": self.result, "generated_code": self.generated_code, "performance_score": self.performance_score, "view_elements": self.view_elements}
38
+
39
+ @staticmethod
40
+ def _safe_json(value: Any) -> str:
41
+ return html_lib.escape(json.dumps(value, ensure_ascii=False, default=str))
42
+
43
+ def to_html(self) -> str:
44
+ transcription = html_lib.escape(self.transcription)
45
+ function_name = html_lib.escape(self.task.function_name)
46
+ generated_code = html_lib.escape(self.generated_code)
47
+
48
+ html = "<html><body>"
49
+ html += "<h1>tellm View</h1>"
50
+ html += "<p><strong>Transkrypcja:</strong> " + transcription + "</p>"
51
+ html += "<p><strong>Zadanie:</strong> " + self.task.type.value + " / " + function_name + "</p>"
52
+ html += "<p><strong>Parametry:</strong> " + self._safe_json(self.task.parameters) + "</p>"
53
+ html += "<p><strong>Wynik:</strong> " + self._safe_json(self.result) + "</p>"
54
+ if self.generated_code:
55
+ html += "<p><strong>Kod:</strong> <pre>" + generated_code + "</pre></p>"
56
+ html += "<p><strong>Score:</strong> " + str(self.performance_score) + "</p>"
57
+ for elem in self.view_elements:
58
+ if elem.get("type") == "answer":
59
+ html += "<p><strong>Odpowiedz:</strong> " + html_lib.escape(str(elem.get("text", ""))) + "</p>"
60
+ html += "</body></html>"
61
+ return html
62
+
63
+ class TellmBot:
64
+ def __init__(self, config: Optional[Config] = None, db_path: str = "tellm.db"):
65
+ self.config = config or load_config()
66
+ self.db_path = db_path
67
+ self.functions_db: Dict[str, Callable] = {}
68
+ self.evolution_history: Dict[str, List[Dict]] = {}
69
+ self.current_version: Dict[str, int] = {}
70
+ self.performance_scores: Dict[str, float] = {}
71
+ self.stt_model = None
72
+ self.tts = None
73
+ self._init_db()
74
+
75
+ def _init_db(self):
76
+ conn = sqlite3.connect(self.db_path)
77
+ c = conn.cursor()
78
+ c.execute("CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, transcription TEXT, type TEXT, function_name TEXT, parameters TEXT, code TEXT, result TEXT)")
79
+ c.execute("CREATE TABLE IF NOT EXISTS evolution (id INTEGER PRIMARY KEY, function_name TEXT, version INTEGER, code TEXT, score REAL)")
80
+ c.execute("CREATE TABLE IF NOT EXISTS views (id INTEGER PRIMARY KEY, transcription TEXT, task_data TEXT, result_data TEXT, html TEXT)")
81
+ conn.commit()
82
+ conn.close()
83
+
84
+ def save_task(self, task: Task, result: Any, transcription: str):
85
+ conn = sqlite3.connect(self.db_path)
86
+ c = conn.cursor()
87
+ c.execute("INSERT INTO tasks (transcription, type, function_name, parameters, code, result) VALUES (?, ?, ?, ?, ?, ?)", (transcription, task.type.value, task.function_name, json.dumps(task.parameters), task.code, json.dumps(result)))
88
+ conn.commit()
89
+ conn.close()
90
+
91
+ def save_evolution(self, function_name: str, step: Dict):
92
+ conn = sqlite3.connect(self.db_path)
93
+ c = conn.cursor()
94
+ c.execute("INSERT INTO evolution (function_name, version, code, score) VALUES (?, ?, ?, ?)", (function_name, step["version"], step["code"], step["score"]))
95
+ conn.commit()
96
+ conn.close()
97
+
98
+ def save_view(self, view: ViewData) -> str:
99
+ html = view.to_html()
100
+ conn = sqlite3.connect(self.db_path)
101
+ c = conn.cursor()
102
+ c.execute("INSERT INTO views (transcription, task_data, result_data, html) VALUES (?, ?, ?, ?)", (view.transcription, json.dumps(view.to_dict()["task"]), json.dumps(view.result), html))
103
+ conn.commit()
104
+ conn.close()
105
+ return html
106
+
107
+ def get_tasks(self, limit: int = 10) -> List[Dict]:
108
+ conn = sqlite3.connect(self.db_path)
109
+ c = conn.cursor()
110
+ c.execute("SELECT id, transcription, type, function_name, parameters, result FROM tasks ORDER BY id DESC LIMIT ?", (limit,))
111
+ rows = c.fetchall()
112
+ conn.close()
113
+ return [{"id": r[0], "transcription": r[1], "type": r[2], "function": r[3], "parameters": json.loads(r[4]), "result": json.loads(r[5])} for r in rows]
114
+
115
+ def register_function(self, name: str, func: Callable):
116
+ self.functions_db[name] = func
117
+ self.current_version[name] = 0
118
+ self.evolution_history[name] = []
119
+ self.performance_scores[name] = 0.0
120
+
121
+ def _completion(self, messages: List[Dict[str, str]]):
122
+ from litellm import completion
123
+
124
+ return completion(
125
+ model=self.config.llm_model,
126
+ messages=messages,
127
+ api_key=self.config.openrouter_api_key,
128
+ base_url="https://openrouter.ai/api/v1",
129
+ )
130
+
131
+ def _get_stt_model(self):
132
+ if self.stt_model is None:
133
+ from faster_whisper import WhisperModel
134
+
135
+ self.stt_model = WhisperModel("base", device="cpu", compute_type="int8")
136
+ return self.stt_model
137
+
138
+ def _get_tts(self):
139
+ if self.tts is None:
140
+ import pyttsx3
141
+
142
+ self.tts = pyttsx3.init()
143
+ self.tts.setProperty("rate", 150)
144
+ return self.tts
145
+
146
+ async def analyze_query(self, query: str) -> Task:
147
+ prompt = "Analizuj: " + query + ". JSON: type,function_name,parameters,code,schedule"
148
+ response = self._completion([{"role": "user", "content": prompt}])
149
+ result = json.loads(response.choices[0].message.content)
150
+ return Task(TaskType(result["type"]), result["function_name"], result["parameters"], result.get("code",""), result.get("schedule",""))
151
+
152
+ async def evolve_function(self, task: Task) -> Dict:
153
+ func_name = task.function_name
154
+ version = self.current_version[func_name]
155
+ prev_code = self.evolution_history[func_name][-1]["code"] if version > 0 else ""
156
+ prompt = "Generuj funkcji: " + func_name + ". Zadanie: " + str(task.parameters) + ". Kod:"
157
+ response = self._completion([{"role": "user", "content": prompt}])
158
+ new_code = response.choices[0].message.content
159
+ score = self.performance_scores[func_name] + 0.1
160
+ step = {"version": version + 1, "previous_code": prev_code, "code": new_code, "improvement": "LLM", "score": score}
161
+ self.evolution_history[func_name].append(step)
162
+ self.current_version[func_name] += 1
163
+ self.performance_scores[func_name] = score
164
+ self.save_evolution(func_name, step)
165
+ if new_code:
166
+ try:
167
+ exec(new_code, globals())
168
+ except Exception as e:
169
+ print("Blad:", e)
170
+ return step
171
+
172
+ async def execute_task(self, task: Task) -> Any:
173
+ if task.type == TaskType.NOW:
174
+ if task.function_name in self.functions_db:
175
+ result = self.functions_db[task.function_name](task.parameters)
176
+ if inspect.isawaitable(result):
177
+ return await result
178
+ return result
179
+ return await self.evolve_function(task)
180
+ elif task.type == TaskType.CRON: return {"status": "cron_set", "schedule": task.schedule}
181
+ elif task.type == TaskType.EVENT_TRIGGER: return {"status": "event_set", "function": task.function_name}
182
+
183
+ def transcribe(self, audio_data: bytes) -> str:
184
+ temp_path = None
185
+ try:
186
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
187
+ f.write(audio_data)
188
+ temp_path = f.name
189
+ segments, _ = self._get_stt_model().transcribe(temp_path, language="pl")
190
+ return " ".join(segment.text.strip() for segment in segments).strip()
191
+ except Exception as e:
192
+ print("STT blad:", e)
193
+ return ""
194
+ finally:
195
+ if temp_path and os.path.exists(temp_path):
196
+ os.unlink(temp_path)
197
+
198
+ def speak(self, text: str):
199
+ tts = self._get_tts()
200
+ tts.say(text)
201
+ tts.runAndWait()
202
+
203
+ def generate_view(self, transcription: str, task: Task, result: Any) -> ViewData:
204
+ view_elements = [{"type": "transcription", "text": transcription}, {"type": "task", "data": {"type": task.type.value, "function": task.function_name, "parameters": task.parameters}}, {"type": "result", "data": result}, {"type": "code", "code": task.code}]
205
+ score = self.performance_scores.get(task.function_name, 0.0)
206
+ view = ViewData(transcription=transcription, task=task, result=result, generated_code=task.code, performance_score=score, view_elements=view_elements)
207
+ html = self.save_view(view)
208
+ view.view_elements.append({"type": "html", "html": html})
209
+ return view
tellm-4.0.1/config.py ADDED
@@ -0,0 +1,12 @@
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from dataclasses import dataclass
4
+ load_dotenv()
5
+ @dataclass
6
+ class Config:
7
+ openrouter_api_key: str
8
+ llm_model: str
9
+ host: str
10
+ port: int
11
+ def load_config() -> Config:
12
+ return Config(openrouter_api_key=os.getenv("OPENROUTER_API_KEY", ""), llm_model=os.getenv("LLM_MODEL", "openrouter/qwen/qwen3-coder-next"), host=os.getenv("HOST", "localhost"), port=int(os.getenv("PORT", "8000")))
tellm-4.0.1/main.py ADDED
@@ -0,0 +1,16 @@
1
+ import argparse
2
+ from tellm.server import TellmServer
3
+ from tellm.config import load_config
4
+ def main():
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("--host", default=None)
7
+ parser.add_argument("--port", type=int, default=None)
8
+ parser.add_argument("--db", default="tellm.db")
9
+ args = parser.parse_args()
10
+ config = load_config()
11
+ server = TellmServer(host=args.host or config.host, port=args.port or config.port, db_path=args.db)
12
+ server.register_function("now", lambda p: print("Now:", p))
13
+ server.register_function("cron", lambda p: print("Cron:", p))
14
+ server.register_function("event", lambda p: print("Event:", p))
15
+ server.run()
16
+ if __name__ == "__main__": main()
@@ -0,0 +1,5 @@
1
+ litellm>=1.0.0
2
+ websockets>=12.0
3
+ python-dotenv>=1.0.0
4
+ pyttsx3>=2.90
5
+ faster-whisper>=0.11.0
tellm-4.0.1/server.py ADDED
@@ -0,0 +1,53 @@
1
+ """tellm v4 server"""
2
+ import asyncio
3
+ import json
4
+
5
+ import websockets
6
+
7
+ from .bot import TellmBot
8
+ from .config import load_config
9
+ from litellm import completion
10
+
11
+ class TellmServer:
12
+ def __init__(self, host: str = "localhost", port: int = 8000, db_path: str = "tellm.db"):
13
+ self.host = host
14
+ self.port = port
15
+ self.bot = TellmBot(db_path=db_path)
16
+
17
+ def register_function(self, name: str, func):
18
+ self.bot.register_function(name, func)
19
+
20
+ async def handle(self, websocket, path=None):
21
+ async for message in websocket:
22
+ try:
23
+ data = json.loads(message)
24
+ audio = data.get("audio")
25
+ if not audio: continue
26
+ transcription = self.bot.transcribe(audio)
27
+ if not transcription: continue
28
+ print("STT:", transcription)
29
+ await websocket.send(json.dumps({"type": "view", "data": {"transcription": transcription, "status": "analyzing"}}))
30
+ task = await self.bot.analyze_query(transcription)
31
+ result = await self.bot.execute_task(task)
32
+ view = self.bot.generate_view(transcription, task, result)
33
+ config = load_config()
34
+ resp = completion(model=config.llm_model, messages=[{"role": "user", "content": "Odpowiedz: " + transcription + ". Wynik: " + str(result)}], api_key=config.openrouter_api_key, base_url="https://openrouter.ai/api/v1")
35
+ answer = resp.choices[0].message.content
36
+ view.view_elements.append({"type": "answer", "text": answer})
37
+ html = view.to_html()
38
+ await websocket.send(json.dumps({"type": "view", "data": view.to_dict(), "html": html}))
39
+ self.bot.speak(answer)
40
+ except Exception as e:
41
+ print("Bqd:", e)
42
+ await websocket.send(json.dumps({"type": "error", "message": str(e)}))
43
+
44
+ async def serve_forever(self):
45
+ print("tellm v4 na " + self.host + ":" + str(self.port))
46
+ async with websockets.serve(self.handle, self.host, self.port):
47
+ await asyncio.Future()
48
+
49
+ def run(self):
50
+ try:
51
+ asyncio.run(self.serve_forever())
52
+ except KeyboardInterrupt:
53
+ print("\ntellm stopped")
tellm-4.0.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
tellm-4.0.1/setup.py ADDED
@@ -0,0 +1,17 @@
1
+ from setuptools import setup
2
+
3
+ setup(
4
+ name="tellm",
5
+ version="4.0.1",
6
+ packages=["tellm"],
7
+ package_dir={"tellm": "."},
8
+ install_requires=[
9
+ "litellm>=1.0.0",
10
+ "websockets>=12.0",
11
+ "pyttsx3>=2.90",
12
+ "python-dotenv>=1.0.0",
13
+ "faster-whisper>=0.11.0",
14
+ ],
15
+ entry_points={"console_scripts": ["tellm-bot=tellm.main:main"]},
16
+ python_requires=">=3.8",
17
+ )
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: tellm
3
+ Version: 4.0.1
4
+ Requires-Python: >=3.8
5
+ License-File: LICENSE
6
+ Requires-Dist: litellm>=1.0.0
7
+ Requires-Dist: websockets>=12.0
8
+ Requires-Dist: pyttsx3>=2.90
9
+ Requires-Dist: python-dotenv>=1.0.0
10
+ Requires-Dist: faster-whisper>=0.11.0
11
+ Dynamic: license-file
12
+ Dynamic: requires-dist
13
+ Dynamic: requires-python
@@ -0,0 +1,18 @@
1
+ .env.example
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ requirements.txt
6
+ setup.py
7
+ ./__init__.py
8
+ ./bot.py
9
+ ./config.py
10
+ ./main.py
11
+ ./server.py
12
+ tellm.egg-info/PKG-INFO
13
+ tellm.egg-info/SOURCES.txt
14
+ tellm.egg-info/dependency_links.txt
15
+ tellm.egg-info/entry_points.txt
16
+ tellm.egg-info/requires.txt
17
+ tellm.egg-info/top_level.txt
18
+ tests/test_tellm.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tellm-bot = tellm.main:main
@@ -0,0 +1,5 @@
1
+ litellm>=1.0.0
2
+ websockets>=12.0
3
+ pyttsx3>=2.90
4
+ python-dotenv>=1.0.0
5
+ faster-whisper>=0.11.0
@@ -0,0 +1 @@
1
+ tellm
@@ -0,0 +1,97 @@
1
+ import asyncio
2
+ import sqlite3
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ import pytest
6
+
7
+
8
+ def test_import():
9
+ import tellm
10
+
11
+ try:
12
+ package_version = version("tellm")
13
+ except PackageNotFoundError:
14
+ package_version = tellm.__version__
15
+
16
+ assert tellm.__version__ == package_version
17
+
18
+
19
+ def test_sqlite_save_and_get_tasks(tmp_path):
20
+ from tellm import Task, TaskType, create_bot
21
+
22
+ bot = create_bot(db_path=str(tmp_path / "tellm.db"))
23
+ task = Task(TaskType.NOW, "echo", {"text": "czesc"})
24
+
25
+ bot.save_task(task, {"ok": True}, "powiedz czesc")
26
+
27
+ rows = bot.get_tasks()
28
+ assert rows == [
29
+ {
30
+ "id": 1,
31
+ "transcription": "powiedz czesc",
32
+ "type": "now",
33
+ "function": "echo",
34
+ "parameters": {"text": "czesc"},
35
+ "result": {"ok": True},
36
+ }
37
+ ]
38
+
39
+ with sqlite3.connect(tmp_path / "tellm.db") as conn:
40
+ tables = {
41
+ row[0]
42
+ for row in conn.execute(
43
+ "SELECT name FROM sqlite_master WHERE type = 'table'"
44
+ )
45
+ }
46
+ assert {"tasks", "evolution", "views"} <= tables
47
+
48
+
49
+ def test_view_html_escapes_user_content():
50
+ from tellm import Task, TaskType, ViewData
51
+
52
+ task = Task(
53
+ TaskType.NOW,
54
+ "<script>fn()</script>",
55
+ {"payload": "<img src=x onerror=alert(1)>"},
56
+ code="<script>alert(1)</script>",
57
+ )
58
+ view = ViewData(
59
+ transcription="<b>atak</b>",
60
+ task=task,
61
+ result={"html": "<script>x</script>"},
62
+ generated_code=task.code,
63
+ view_elements=[{"type": "answer", "text": "<script>answer</script>"}],
64
+ )
65
+
66
+ html = view.to_html()
67
+
68
+ assert "<script>" not in html
69
+ assert "&lt;script&gt;" in html
70
+ assert "&lt;b&gt;atak&lt;/b&gt;" in html
71
+ assert "&lt;img src=x onerror=alert(1)&gt;" in html
72
+
73
+
74
+ def test_execute_task_supports_sync_functions(tmp_path):
75
+ from tellm import Task, TaskType, create_bot
76
+
77
+ bot = create_bot(db_path=str(tmp_path / "tellm.db"))
78
+ bot.register_function("echo", lambda params: {"echo": params["text"]})
79
+
80
+ result = asyncio.run(bot.execute_task(Task(TaskType.NOW, "echo", {"text": "ok"})))
81
+
82
+ assert result == {"echo": "ok"}
83
+
84
+
85
+ def test_server_starts_inside_running_event_loop(tmp_path):
86
+ from tellm.server import TellmServer
87
+
88
+ async def start_and_cancel():
89
+ server = TellmServer(
90
+ host="127.0.0.1",
91
+ port=0,
92
+ db_path=str(tmp_path / "tellm.db"),
93
+ )
94
+ with pytest.raises(asyncio.TimeoutError):
95
+ await asyncio.wait_for(server.serve_forever(), timeout=0.05)
96
+
97
+ asyncio.run(start_and_cancel())