lobsta 0.3.0__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.
- lobsta-0.3.0/LICENSE +21 -0
- lobsta-0.3.0/PKG-INFO +118 -0
- lobsta-0.3.0/README.md +96 -0
- lobsta-0.3.0/lobsta/__init__.py +3 -0
- lobsta-0.3.0/lobsta/__main__.py +3 -0
- lobsta-0.3.0/lobsta/access.py +66 -0
- lobsta-0.3.0/lobsta/agent.py +285 -0
- lobsta-0.3.0/lobsta/bot.py +350 -0
- lobsta-0.3.0/lobsta/cli.py +531 -0
- lobsta-0.3.0/lobsta/config.py +150 -0
- lobsta-0.3.0/lobsta/data/Dockerfile +13 -0
- lobsta-0.3.0/lobsta/data/config.example.toml +49 -0
- lobsta-0.3.0/lobsta/data/evals.toml +96 -0
- lobsta-0.3.0/lobsta/evals.py +99 -0
- lobsta-0.3.0/lobsta/llm.py +99 -0
- lobsta-0.3.0/lobsta/store.py +132 -0
- lobsta-0.3.0/lobsta/telegram.py +139 -0
- lobsta-0.3.0/lobsta/tools/__init__.py +69 -0
- lobsta-0.3.0/lobsta/tools/calc.py +56 -0
- lobsta-0.3.0/lobsta/tools/sandbox.py +190 -0
- lobsta-0.3.0/lobsta/tools/web.py +210 -0
- lobsta-0.3.0/lobsta.egg-info/PKG-INFO +118 -0
- lobsta-0.3.0/lobsta.egg-info/SOURCES.txt +29 -0
- lobsta-0.3.0/lobsta.egg-info/dependency_links.txt +1 -0
- lobsta-0.3.0/lobsta.egg-info/entry_points.txt +2 -0
- lobsta-0.3.0/lobsta.egg-info/top_level.txt +1 -0
- lobsta-0.3.0/pyproject.toml +38 -0
- lobsta-0.3.0/setup.cfg +4 -0
- lobsta-0.3.0/tests/test_agent_loop.py +232 -0
- lobsta-0.3.0/tests/test_bot.py +178 -0
- lobsta-0.3.0/tests/test_units.py +367 -0
lobsta-0.3.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nochinsky
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
lobsta-0.3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lobsta
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Your own AI assistant on Telegram, with any OpenAI-compatible model: web search and a Python sandbox per conversation.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/nochinsky/lobsta
|
|
7
|
+
Project-URL: Documentation, https://github.com/nochinsky/lobsta#readme
|
|
8
|
+
Project-URL: Issues, https://github.com/nochinsky/lobsta/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/nochinsky/lobsta/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: telegram,llm,assistant,local-llm,llama.cpp,ollama,openai,self-hosted
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
14
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Communications :: Chat
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# lobsta
|
|
24
|
+
|
|
25
|
+
A private AI assistant on Telegram, running on your own model.
|
|
26
|
+
|
|
27
|
+
lobsta connects a Telegram bot to a model on your computer (llama.cpp, vLLM, SGLang, LM Studio,
|
|
28
|
+
Ollama) or to an OpenAI-compatible cloud API. Message it from anywhere: it answers with your
|
|
29
|
+
model, searches the web, reads pages, and runs Python for exact calculations, files and charts.
|
|
30
|
+
|
|
31
|
+
- **Private.** Your model on your machine. Nothing is opened to the internet, and only your
|
|
32
|
+
Telegram account can use the bot.
|
|
33
|
+
- **Simple.** One command runs it; Ctrl+C stops it. Settings and conversations are plain files.
|
|
34
|
+
- **Checked.** `lobsta eval` shows that your model works with it, in a few minutes.
|
|
35
|
+
|
|
36
|
+
## Requirements
|
|
37
|
+
|
|
38
|
+
- Linux, or Windows with WSL2 ([guide](https://github.com/nochinsky/lobsta/blob/main/docs/windows.md))
|
|
39
|
+
- Python 3.11 or newer, and [pipx](https://pipx.pypa.io) (Ubuntu: `sudo apt install pipx && pipx ensurepath`)
|
|
40
|
+
- A model server ([how to start and connect one](https://github.com/nochinsky/lobsta/blob/main/docs/models.md))
|
|
41
|
+
- Docker, to run Python (optional: without it, lobsta uses a simple calculator)
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
pipx install lobsta
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Then run `lobsta`. The first time, it walks you through setup:
|
|
50
|
+
|
|
51
|
+
1. **Telegram bot.** Create one with [@BotFather](https://t.me/BotFather) (command `/newbot`) and
|
|
52
|
+
paste its token.
|
|
53
|
+
2. **Model.** lobsta finds the model servers running on your computer, or you type the address
|
|
54
|
+
of one ([details](https://github.com/nochinsky/lobsta/blob/main/docs/models.md)).
|
|
55
|
+
3. **Web search** and the **Python sandbox**: the defaults work without accounts or keys.
|
|
56
|
+
|
|
57
|
+
When lobsta starts, it shows a pairing code: send `/pair CODE` to your bot to connect your
|
|
58
|
+
Telegram account.
|
|
59
|
+
|
|
60
|
+
lobsta runs while its terminal window is open. To keep it running after closing the window,
|
|
61
|
+
start it in `tmux`.
|
|
62
|
+
|
|
63
|
+
## Use
|
|
64
|
+
|
|
65
|
+
Write to the bot as you would to any assistant. You can send photos and files too. Research
|
|
66
|
+
questions ("compare…", "find out…") take a minute or two: it searches several sources and
|
|
67
|
+
cites them.
|
|
68
|
+
|
|
69
|
+
| In Telegram | |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `/new` | Start a new conversation |
|
|
72
|
+
| `/sessions` | Continue an earlier conversation |
|
|
73
|
+
| `/model` | Switch model |
|
|
74
|
+
| `/stop` | Stop the current answer |
|
|
75
|
+
| `/status` | Model, server and conversation |
|
|
76
|
+
|
|
77
|
+
| On your computer | |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `lobsta` | Run the bot |
|
|
80
|
+
| `lobsta setup` | Add a model, or start over |
|
|
81
|
+
| `lobsta doctor` | Check everything and explain how to fix problems |
|
|
82
|
+
| `lobsta eval` | Check that a model works with lobsta |
|
|
83
|
+
| `lobsta config` | Edit the settings |
|
|
84
|
+
|
|
85
|
+
## Update
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
pipx upgrade lobsta
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Then stop lobsta (Ctrl+C) and start it again. Your settings and conversations are kept. If
|
|
92
|
+
lobsta then says the sandbox image is missing, run `lobsta sandbox build`. What changed is in
|
|
93
|
+
the [changelog](https://github.com/nochinsky/lobsta/blob/main/CHANGELOG.md).
|
|
94
|
+
|
|
95
|
+
## Uninstall
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
lobsta sandbox clean # remove the sandbox containers
|
|
99
|
+
docker rmi lobsta-sandbox:1 # remove the sandbox image (~1 GB)
|
|
100
|
+
pipx uninstall lobsta
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Settings and conversations stay in `~/.lobsta`; delete that folder to remove them too.
|
|
104
|
+
|
|
105
|
+
## Documentation
|
|
106
|
+
|
|
107
|
+
- [Models and servers](https://github.com/nochinsky/lobsta/blob/main/docs/models.md): start a
|
|
108
|
+
server, connect it, check it
|
|
109
|
+
- [Configuration](https://github.com/nochinsky/lobsta/blob/main/docs/configuration.md): every setting
|
|
110
|
+
- [Windows (WSL2)](https://github.com/nochinsky/lobsta/blob/main/docs/windows.md)
|
|
111
|
+
- [Privacy and security](https://github.com/nochinsky/lobsta/blob/main/docs/privacy.md)
|
|
112
|
+
- [How it works](https://github.com/nochinsky/lobsta/blob/main/docs/architecture.md), for developers
|
|
113
|
+
- [Changelog](https://github.com/nochinsky/lobsta/blob/main/CHANGELOG.md)
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT. Inspired by [Hermes Agent](https://github.com/NousResearch/hermes-agent) and
|
|
118
|
+
[Pi](https://pi.dev); no code copied.
|
lobsta-0.3.0/README.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# lobsta
|
|
2
|
+
|
|
3
|
+
A private AI assistant on Telegram, running on your own model.
|
|
4
|
+
|
|
5
|
+
lobsta connects a Telegram bot to a model on your computer (llama.cpp, vLLM, SGLang, LM Studio,
|
|
6
|
+
Ollama) or to an OpenAI-compatible cloud API. Message it from anywhere: it answers with your
|
|
7
|
+
model, searches the web, reads pages, and runs Python for exact calculations, files and charts.
|
|
8
|
+
|
|
9
|
+
- **Private.** Your model on your machine. Nothing is opened to the internet, and only your
|
|
10
|
+
Telegram account can use the bot.
|
|
11
|
+
- **Simple.** One command runs it; Ctrl+C stops it. Settings and conversations are plain files.
|
|
12
|
+
- **Checked.** `lobsta eval` shows that your model works with it, in a few minutes.
|
|
13
|
+
|
|
14
|
+
## Requirements
|
|
15
|
+
|
|
16
|
+
- Linux, or Windows with WSL2 ([guide](https://github.com/nochinsky/lobsta/blob/main/docs/windows.md))
|
|
17
|
+
- Python 3.11 or newer, and [pipx](https://pipx.pypa.io) (Ubuntu: `sudo apt install pipx && pipx ensurepath`)
|
|
18
|
+
- A model server ([how to start and connect one](https://github.com/nochinsky/lobsta/blob/main/docs/models.md))
|
|
19
|
+
- Docker, to run Python (optional: without it, lobsta uses a simple calculator)
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
pipx install lobsta
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Then run `lobsta`. The first time, it walks you through setup:
|
|
28
|
+
|
|
29
|
+
1. **Telegram bot.** Create one with [@BotFather](https://t.me/BotFather) (command `/newbot`) and
|
|
30
|
+
paste its token.
|
|
31
|
+
2. **Model.** lobsta finds the model servers running on your computer, or you type the address
|
|
32
|
+
of one ([details](https://github.com/nochinsky/lobsta/blob/main/docs/models.md)).
|
|
33
|
+
3. **Web search** and the **Python sandbox**: the defaults work without accounts or keys.
|
|
34
|
+
|
|
35
|
+
When lobsta starts, it shows a pairing code: send `/pair CODE` to your bot to connect your
|
|
36
|
+
Telegram account.
|
|
37
|
+
|
|
38
|
+
lobsta runs while its terminal window is open. To keep it running after closing the window,
|
|
39
|
+
start it in `tmux`.
|
|
40
|
+
|
|
41
|
+
## Use
|
|
42
|
+
|
|
43
|
+
Write to the bot as you would to any assistant. You can send photos and files too. Research
|
|
44
|
+
questions ("compare…", "find out…") take a minute or two: it searches several sources and
|
|
45
|
+
cites them.
|
|
46
|
+
|
|
47
|
+
| In Telegram | |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `/new` | Start a new conversation |
|
|
50
|
+
| `/sessions` | Continue an earlier conversation |
|
|
51
|
+
| `/model` | Switch model |
|
|
52
|
+
| `/stop` | Stop the current answer |
|
|
53
|
+
| `/status` | Model, server and conversation |
|
|
54
|
+
|
|
55
|
+
| On your computer | |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `lobsta` | Run the bot |
|
|
58
|
+
| `lobsta setup` | Add a model, or start over |
|
|
59
|
+
| `lobsta doctor` | Check everything and explain how to fix problems |
|
|
60
|
+
| `lobsta eval` | Check that a model works with lobsta |
|
|
61
|
+
| `lobsta config` | Edit the settings |
|
|
62
|
+
|
|
63
|
+
## Update
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
pipx upgrade lobsta
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Then stop lobsta (Ctrl+C) and start it again. Your settings and conversations are kept. If
|
|
70
|
+
lobsta then says the sandbox image is missing, run `lobsta sandbox build`. What changed is in
|
|
71
|
+
the [changelog](https://github.com/nochinsky/lobsta/blob/main/CHANGELOG.md).
|
|
72
|
+
|
|
73
|
+
## Uninstall
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
lobsta sandbox clean # remove the sandbox containers
|
|
77
|
+
docker rmi lobsta-sandbox:1 # remove the sandbox image (~1 GB)
|
|
78
|
+
pipx uninstall lobsta
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Settings and conversations stay in `~/.lobsta`; delete that folder to remove them too.
|
|
82
|
+
|
|
83
|
+
## Documentation
|
|
84
|
+
|
|
85
|
+
- [Models and servers](https://github.com/nochinsky/lobsta/blob/main/docs/models.md): start a
|
|
86
|
+
server, connect it, check it
|
|
87
|
+
- [Configuration](https://github.com/nochinsky/lobsta/blob/main/docs/configuration.md): every setting
|
|
88
|
+
- [Windows (WSL2)](https://github.com/nochinsky/lobsta/blob/main/docs/windows.md)
|
|
89
|
+
- [Privacy and security](https://github.com/nochinsky/lobsta/blob/main/docs/privacy.md)
|
|
90
|
+
- [How it works](https://github.com/nochinsky/lobsta/blob/main/docs/architecture.md), for developers
|
|
91
|
+
- [Changelog](https://github.com/nochinsky/lobsta/blob/main/CHANGELOG.md)
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT. Inspired by [Hermes Agent](https://github.com/NousResearch/hermes-agent) and
|
|
96
|
+
[Pi](https://pi.dev); no code copied.
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Who may use the bot: Telegram user IDs in <home>/allowed-users, added by pairing.
|
|
2
|
+
|
|
3
|
+
While nobody is allowed, a one-time code is kept in <home>/pairing-code (shown when lobsta
|
|
4
|
+
starts and by `lobsta doctor`). Sending "/pair CODE" from Telegram adds that account and
|
|
5
|
+
deletes the code. A paired user can create a new code with "/pair new". Five wrong attempts
|
|
6
|
+
replace the code.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import secrets
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # no 0/O, 1/I
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Access:
|
|
17
|
+
def __init__(self, home: Path):
|
|
18
|
+
self.allowed_file = home / "allowed-users"
|
|
19
|
+
self.code_file = home / "pairing-code"
|
|
20
|
+
self.failures = 0
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
def _lines(path: Path) -> list[str]:
|
|
24
|
+
try:
|
|
25
|
+
return [s.strip() for s in path.read_text(encoding="utf-8").splitlines() if s.strip() and not s.startswith("#")]
|
|
26
|
+
except FileNotFoundError:
|
|
27
|
+
return []
|
|
28
|
+
|
|
29
|
+
def allowed(self) -> set[str]:
|
|
30
|
+
return set(self._lines(self.allowed_file))
|
|
31
|
+
|
|
32
|
+
def code(self) -> str | None:
|
|
33
|
+
return next(iter(self._lines(self.code_file)), None)
|
|
34
|
+
|
|
35
|
+
def new_code(self) -> str:
|
|
36
|
+
code = "".join(secrets.choice(ALPHABET) for _ in range(8))
|
|
37
|
+
self.code_file.write_text(f'# One-time pairing code: send "/pair {code}" to the bot. Deleted after use.\n{code}\n',
|
|
38
|
+
encoding="utf-8")
|
|
39
|
+
self.failures = 0
|
|
40
|
+
return code
|
|
41
|
+
|
|
42
|
+
def ensure_code(self) -> str | None:
|
|
43
|
+
"""A pairing code if nobody is allowed yet."""
|
|
44
|
+
if self.allowed():
|
|
45
|
+
return None
|
|
46
|
+
return self.code() or self.new_code()
|
|
47
|
+
|
|
48
|
+
def pair(self, user_id: int | str, attempt: str | None) -> str:
|
|
49
|
+
"""'paired' | 'already' | 'wrong' | 'none'"""
|
|
50
|
+
uid = str(user_id)
|
|
51
|
+
if uid in self.allowed():
|
|
52
|
+
return "already"
|
|
53
|
+
code = self.code()
|
|
54
|
+
if not code:
|
|
55
|
+
return "none"
|
|
56
|
+
if (attempt or "").strip().upper() != code:
|
|
57
|
+
self.failures += 1
|
|
58
|
+
if self.failures >= 5:
|
|
59
|
+
self.new_code()
|
|
60
|
+
return "wrong"
|
|
61
|
+
existing = self.allowed_file.read_text(encoding="utf-8") if self.allowed_file.exists() else \
|
|
62
|
+
"# Telegram user IDs allowed to use the bot, one per line (added by /pair).\n"
|
|
63
|
+
self.allowed_file.write_text(existing.rstrip("\n") + f"\n{uid}\n", encoding="utf-8")
|
|
64
|
+
self.code_file.unlink(missing_ok=True)
|
|
65
|
+
self.failures = 0
|
|
66
|
+
return "paired"
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""The agent loop: send the conversation to the model, run the tools it asks for, repeat
|
|
2
|
+
until it answers in plain text (or max_steps is reached)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import mimetypes
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Callable
|
|
11
|
+
|
|
12
|
+
from lobsta import llm, tools as toolbox
|
|
13
|
+
from lobsta.config import Config, Model
|
|
14
|
+
from lobsta.store import Conversation
|
|
15
|
+
|
|
16
|
+
# Deliberately short: small models follow ~100-word prompts better than long ones, and every
|
|
17
|
+
# rule here competes with the conversation for attention. Override with <home>/system.md.
|
|
18
|
+
SYSTEM_PROMPT = """You are lobsta, a personal assistant chatting with the user on Telegram. Today is {date}. You run on the model {model}.
|
|
19
|
+
|
|
20
|
+
{tool_notes}
|
|
21
|
+
- If you are unsure or a source fails, say so. Never invent facts, numbers or links.
|
|
22
|
+
- Be helpful, direct and concise; go into depth when asked. Reply in the user's language.
|
|
23
|
+
- Formatting: Telegram shows **bold**, *italic*, `code`, code blocks and [links](https://example.com). No tables or # headings."""
|
|
24
|
+
|
|
25
|
+
TOOL_NOTES = {
|
|
26
|
+
"web_search": "- Search the web for anything current or checkable, and cite sources as links. fetch reads a page in full.",
|
|
27
|
+
"calc": "- Calculate with calc, never in your head: percentages, interest, conversions, anything beyond single-digit arithmetic.",
|
|
28
|
+
"python": "- Calculate with python, never in your head: percentages, interest, conversions, anything beyond "
|
|
29
|
+
"single-digit arithmetic. Also use it "
|
|
30
|
+
"for data, files and charts: /workspace keeps this conversation's files, including ones the user sends. "
|
|
31
|
+
"send_file shares a file with the user.",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
OLD_TOOL_RESULT = 2000 # characters kept from tool results of earlier turns
|
|
35
|
+
IMAGE_SIZE = 3000 # an image costs the model ~1,000 tokens, whatever its file size
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def system_prompt(config: Config, model: Model, tools: dict) -> str:
|
|
39
|
+
custom = config.home / "system.md"
|
|
40
|
+
template = custom.read_text(encoding="utf-8") if custom.exists() else SYSTEM_PROMPT
|
|
41
|
+
notes = "\n".join(note for name, note in TOOL_NOTES.items() if name in tools)
|
|
42
|
+
return template.replace("{date}", time.strftime("%A, %d %B %Y")).replace("{model}", model.name).replace("{tool_notes}", notes)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _image_part(conv: Conversation, part: dict, current: bool, vision: bool):
|
|
46
|
+
rel = part["path"]
|
|
47
|
+
if current and vision:
|
|
48
|
+
path = conv.dir / rel
|
|
49
|
+
kind = mimetypes.guess_type(path.name)[0] or "image/jpeg"
|
|
50
|
+
data = base64.b64encode(path.read_bytes()).decode()
|
|
51
|
+
return {"type": "image_url", "image_url": {"url": f"data:{kind};base64,{data}"}}
|
|
52
|
+
where = rel.removeprefix("workspace/")
|
|
53
|
+
note = "" if vision else " This model cannot see images; say so if the user asks about it."
|
|
54
|
+
return {"type": "text", "text": f"[image: /workspace/{where}]{note}"}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _close_interrupted(msgs: list[dict]) -> list[dict]:
|
|
58
|
+
"""Every tool call needs a result before the next non-tool message (a /stop or crash can
|
|
59
|
+
leave calls unanswered; servers reject such histories)."""
|
|
60
|
+
out, pending = [], []
|
|
61
|
+
for m in msgs:
|
|
62
|
+
if m["role"] == "tool":
|
|
63
|
+
pending = [p for p in pending if p != m.get("tool_call_id")]
|
|
64
|
+
elif pending:
|
|
65
|
+
out += [{"role": "tool", "tool_call_id": p, "content": "[interrupted]"} for p in pending]
|
|
66
|
+
pending = []
|
|
67
|
+
out.append(m)
|
|
68
|
+
if m["role"] == "assistant":
|
|
69
|
+
pending = [c["id"] for c in m.get("tool_calls") or []]
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _size(m: dict) -> int:
|
|
74
|
+
"""Roughly how much of the context a message takes, in characters (~3 per token). Text is
|
|
75
|
+
counted as written (not JSON-escaped, which inflates non-Latin scripts) and an image at a
|
|
76
|
+
fixed cost (its base64 data says nothing about its token count)."""
|
|
77
|
+
content = m.get("content") or ""
|
|
78
|
+
if isinstance(content, list):
|
|
79
|
+
n = sum(len(p.get("text", "")) if p.get("type") == "text" else IMAGE_SIZE for p in content)
|
|
80
|
+
else:
|
|
81
|
+
n = len(str(content))
|
|
82
|
+
n += len(m.get("reasoning_content") or "")
|
|
83
|
+
for call in m.get("tool_calls") or []:
|
|
84
|
+
fn = call.get("function") or {}
|
|
85
|
+
n += len(fn.get("name") or "") + len(fn.get("arguments") or "")
|
|
86
|
+
return n + 20
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _budget(model: Model) -> int:
|
|
90
|
+
"""How much of the conversation the model gets, in characters: ~60% of its context (~3
|
|
91
|
+
characters per token), leaving room for tools, thinking and the answer."""
|
|
92
|
+
return int(model.context * 0.6 * 3)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _summary(conv: Conversation) -> tuple[str, int]:
|
|
96
|
+
"""The latest summary of earlier messages, and the index of the first message it doesn't cover."""
|
|
97
|
+
for m in reversed(conv.messages):
|
|
98
|
+
if m["role"] == "summary":
|
|
99
|
+
return m["content"], m["from"]
|
|
100
|
+
return "", 0
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _prepared(conv: Conversation, model: Model) -> list[dict]:
|
|
104
|
+
"""The messages since the latest summary as the model sees them: the current turn's images
|
|
105
|
+
resolved, old tool output shortened, old reasoning dropped, interrupted tool calls closed."""
|
|
106
|
+
msgs = [m for m in conv.messages[_summary(conv)[1]:] if m["role"] != "summary"]
|
|
107
|
+
last_user = max((i for i, m in enumerate(msgs) if m["role"] == "user"), default=0)
|
|
108
|
+
out = []
|
|
109
|
+
for i, m in enumerate(msgs):
|
|
110
|
+
m = dict(m)
|
|
111
|
+
if m["role"] == "user" and isinstance(m.get("content"), list):
|
|
112
|
+
m["content"] = [_image_part(conv, p, i == last_user, model.vision) if p.get("type") == "image_file" else p
|
|
113
|
+
for p in m["content"]]
|
|
114
|
+
if i < last_user:
|
|
115
|
+
m.pop("reasoning_content", None)
|
|
116
|
+
if m["role"] == "tool" and len(m.get("content", "")) > OLD_TOOL_RESULT:
|
|
117
|
+
m["content"] = m["content"][:OLD_TOOL_RESULT] + "\n[... shortened ...]"
|
|
118
|
+
out.append(m)
|
|
119
|
+
return _close_interrupted(out)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def window(conv: Conversation, model: Model) -> list[dict]:
|
|
123
|
+
"""The conversation as sent to the model. Compaction normally keeps it within the budget;
|
|
124
|
+
if it doesn't (a failed summary, one very long turn), the oldest turns are dropped and then
|
|
125
|
+
the current turn's oldest tool results shortened."""
|
|
126
|
+
out = _prepared(conv, model)
|
|
127
|
+
budget = _budget(model)
|
|
128
|
+
sizes = [_size(m) for m in out]
|
|
129
|
+
total, start = sum(sizes), 0
|
|
130
|
+
while total > budget:
|
|
131
|
+
nxt = next((j for j in range(start + 1, len(out)) if out[j]["role"] == "user"), None)
|
|
132
|
+
if nxt is None:
|
|
133
|
+
break
|
|
134
|
+
total -= sum(sizes[start:nxt])
|
|
135
|
+
start = nxt
|
|
136
|
+
out = out[start:]
|
|
137
|
+
for m in out:
|
|
138
|
+
if total <= budget:
|
|
139
|
+
break
|
|
140
|
+
if m["role"] == "tool" and len(m.get("content", "")) > OLD_TOOL_RESULT:
|
|
141
|
+
total -= len(m["content"]) - OLD_TOOL_RESULT
|
|
142
|
+
m["content"] = m["content"][:OLD_TOOL_RESULT] + "\n[... shortened ...]"
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def messages(config: Config, model: Model, conv: Conversation, tools: dict) -> list[dict]:
|
|
147
|
+
"""The request's messages: system prompt (with the summary of earlier messages, if any) and
|
|
148
|
+
the conversation window."""
|
|
149
|
+
system = system_prompt(config, model, tools)
|
|
150
|
+
summary = _summary(conv)[0]
|
|
151
|
+
if summary:
|
|
152
|
+
system += f"\n\nSummary of the earlier part of this conversation:\n{summary}"
|
|
153
|
+
return [{"role": "system", "content": system}, *window(conv, model)]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
SUMMARY_PROMPT = """Below is the earlier part of your conversation with the user. Write the summary you will continue the conversation from: who the user is and what they prefer, what they asked, what you found or decided (with the numbers, names and source links that matter), files in /workspace, and anything still open. Long messages are abbreviated in this transcript, marked "[rest omitted here]"; they were complete, so don't note them as cut off. Plain text, at most 400 words, in the conversation's language."""
|
|
157
|
+
KEEP_RECENT = 0.25 # share of the budget kept word for word when compacting: the latest turns
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _transcript(msgs: list[dict], limit: int) -> str:
|
|
161
|
+
"""Messages as plain text for the summary request. If that is longer than limit, the
|
|
162
|
+
assistant's answers and tool results are shortened, never dropped: the user's own messages
|
|
163
|
+
carry what must be remembered."""
|
|
164
|
+
def short(s: str, n: int) -> str:
|
|
165
|
+
return s if len(s) <= n else s[:n] + " [rest omitted here]"
|
|
166
|
+
|
|
167
|
+
def text(m: dict, cap: int) -> str:
|
|
168
|
+
content = m.get("content") or ""
|
|
169
|
+
if isinstance(content, list):
|
|
170
|
+
content = " ".join(p.get("text", "") if p.get("type") == "text" else f"[image {p.get('path', '')}]"
|
|
171
|
+
for p in content)
|
|
172
|
+
if m["role"] == "user":
|
|
173
|
+
return f"User: {short(content, 4000)}"
|
|
174
|
+
if m["role"] == "tool":
|
|
175
|
+
return f"[tool result] {short(content, cap // 4)}"
|
|
176
|
+
calls = ", ".join(f"{c['function']['name']} {c['function'].get('arguments') or ''}"[:200]
|
|
177
|
+
for c in m.get("tool_calls") or [])
|
|
178
|
+
return f"Assistant: {short(content, cap)}" + (f" [used {calls}]" if calls else "")
|
|
179
|
+
|
|
180
|
+
for cap in (4000, 1500, 600, 200):
|
|
181
|
+
out = "\n\n".join(t for m in msgs if (t := text(m, cap)).strip() not in ("User:", "Assistant:", "[tool result]"))
|
|
182
|
+
if len(out) <= limit:
|
|
183
|
+
break
|
|
184
|
+
return out[-limit:] # only if the user's messages alone don't fit
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def compact(model: Model, conv: Conversation, request_box: list, status: Callable[[str], None]) -> bool:
|
|
188
|
+
"""When the conversation since the latest summary no longer fits the budget, summarize all
|
|
189
|
+
but its latest turns with the model; the summary is stored in the history (nothing is
|
|
190
|
+
deleted). A small context keeps a local model accurate and fast, and since this happens
|
|
191
|
+
once per budget's worth of conversation, the server can reuse its cache in between."""
|
|
192
|
+
budget = _budget(model)
|
|
193
|
+
if sum(_size(m) for m in _prepared(conv, model)) <= budget:
|
|
194
|
+
return False
|
|
195
|
+
old_summary, start = _summary(conv)
|
|
196
|
+
msgs = conv.messages
|
|
197
|
+
users = [i for i in range(start, len(msgs)) if msgs[i]["role"] == "user"]
|
|
198
|
+
if len(users) < 2:
|
|
199
|
+
return False # only the current turn: nothing earlier to summarize
|
|
200
|
+
keep, tail = users[-1], sum(_size(m) for m in msgs[users[-1]:] if m["role"] != "summary")
|
|
201
|
+
for a, b in zip(reversed(users[:-1]), reversed(users[1:])):
|
|
202
|
+
tail += sum(_size(m) for m in msgs[a:b] if m["role"] != "summary")
|
|
203
|
+
if tail > budget * KEEP_RECENT:
|
|
204
|
+
break
|
|
205
|
+
keep = a
|
|
206
|
+
older = [m for m in msgs[start:keep] if m["role"] != "summary"]
|
|
207
|
+
if not older:
|
|
208
|
+
return False
|
|
209
|
+
status("🗜 Summarizing the earlier conversation")
|
|
210
|
+
prompt = SUMMARY_PROMPT + (f"\n\nSummary of what came before:\n{old_summary}" if old_summary else "")
|
|
211
|
+
# no tools and a short answer: this request may use ~75% of the context (the rest: thinking)
|
|
212
|
+
prompt += "\n\nConversation:\n" + _transcript(older, int(model.context * 0.75 * 3))
|
|
213
|
+
request = llm.Request()
|
|
214
|
+
request_box[:] = [request]
|
|
215
|
+
try:
|
|
216
|
+
reply = llm.chat(model, [{"role": "user", "content": prompt}], [], request)
|
|
217
|
+
except llm.Cancelled:
|
|
218
|
+
raise
|
|
219
|
+
except llm.LLMError:
|
|
220
|
+
return False # the window's trimming still keeps the request within the context
|
|
221
|
+
text = (reply.get("content") or "").strip()
|
|
222
|
+
if not text:
|
|
223
|
+
return False
|
|
224
|
+
conv.append({"role": "summary", "content": text, "from": keep})
|
|
225
|
+
return True
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def run(config: Config, model: Model, conv: Conversation, tools: dict, turn: toolbox.Turn,
|
|
229
|
+
request_box: list, status: Callable[[str], None]) -> str:
|
|
230
|
+
"""Process the conversation's latest user message; returns the final answer text."""
|
|
231
|
+
schemas = [t.schema() for t in tools.values()]
|
|
232
|
+
compact(model, conv, request_box, status)
|
|
233
|
+
seen: dict[str, int] = {} # identical calls in this turn: small models can loop on them
|
|
234
|
+
for step in range(config.max_steps):
|
|
235
|
+
if turn.cancelled.is_set():
|
|
236
|
+
raise llm.Cancelled()
|
|
237
|
+
request = llm.Request()
|
|
238
|
+
request_box[:] = [request]
|
|
239
|
+
reply = llm.chat(model, messages(config, model, conv, tools), schemas, request)
|
|
240
|
+
calls = reply.get("tool_calls") or []
|
|
241
|
+
message = {"role": "assistant", "content": reply.get("content") or ""}
|
|
242
|
+
if reply.get("reasoning_content"):
|
|
243
|
+
message["reasoning_content"] = reply["reasoning_content"]
|
|
244
|
+
if calls:
|
|
245
|
+
message["tool_calls"] = [{"id": c.get("id") or f"call_{step}_{n}", "type": "function",
|
|
246
|
+
"function": {"name": c["function"]["name"], "arguments": c["function"].get("arguments") or "{}"}}
|
|
247
|
+
for n, c in enumerate(calls)]
|
|
248
|
+
conv.append(message)
|
|
249
|
+
if not calls:
|
|
250
|
+
return message["content"].strip()
|
|
251
|
+
for call in message["tool_calls"]:
|
|
252
|
+
if turn.cancelled.is_set():
|
|
253
|
+
raise llm.Cancelled()
|
|
254
|
+
name, raw = call["function"]["name"], call["function"]["arguments"]
|
|
255
|
+
tool = tools.get(name)
|
|
256
|
+
try:
|
|
257
|
+
label = tool.label(json.loads(raw)) if tool else ""
|
|
258
|
+
except Exception:
|
|
259
|
+
label = ""
|
|
260
|
+
key = f"{name}:{raw}"
|
|
261
|
+
seen[key] = seen.get(key, 0) + 1
|
|
262
|
+
if seen[key] > 1:
|
|
263
|
+
result = "Error: you already made this exact call in this turn; use its result, try something different, or answer."
|
|
264
|
+
else:
|
|
265
|
+
status(label or f"🔧 {name}")
|
|
266
|
+
result = toolbox.call(tools, name, raw, turn)
|
|
267
|
+
conv.append({"role": "tool", "tool_call_id": call["id"], "content": result})
|
|
268
|
+
conv.append({"role": "user", "content": "[system: step limit reached; summarize what you found so far]"})
|
|
269
|
+
request = llm.Request()
|
|
270
|
+
request_box[:] = [request]
|
|
271
|
+
reply = llm.chat(model, messages(config, model, conv, tools), [], request)
|
|
272
|
+
conv.append({"role": "assistant", "content": reply.get("content") or ""})
|
|
273
|
+
return (reply.get("content") or "").strip()
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def save_upload(conv: Conversation, name: str, data: bytes) -> Path:
|
|
277
|
+
"""Store a file the user sent in the workspace without overwriting; returns the path."""
|
|
278
|
+
safe = "".join(c if c.isalnum() or c in "._- " else "_" for c in Path(name).name).strip() or "file"
|
|
279
|
+
path = conv.workspace / safe
|
|
280
|
+
n = 1
|
|
281
|
+
while path.exists():
|
|
282
|
+
path = conv.workspace / f"{Path(safe).stem}-{n}{Path(safe).suffix}"
|
|
283
|
+
n += 1
|
|
284
|
+
path.write_bytes(data)
|
|
285
|
+
return path
|