stuff
This commit is contained in:
1 parent
e6db824792
commit
ed76261303
5 files changed
+170
-9
No files matched your search
@@ -0,0 +1,31 @@
|
||||
# Development guide
|
||||
|
||||
## Project layout
|
||||
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
| `run_example.py` | Entry point that calls `ai_chat.main()` |
|
||||
| `ai_chat.py` | CLI, Textual UI, conversation loop, API requests, exports, and statistics |
|
||||
| `settings.py` | Load and save `sloppy.json` connections and selections |
|
||||
| `test_ai_chat.py` | Unit and Textual integration tests with mock HTTP responses |
|
||||
| `.env.example` | Example runtime configuration |
|
||||
|
||||
## Conversation and request flow
|
||||
|
||||
`main()` loads `.env`, parses CLI overrides, validates the prompt and turn count, and creates `AIChatApp`. The app optionally opens the connection picker, then starts the conversation. AI 1 and AI 2 alternate for at most `max_turns` replies.
|
||||
|
||||
For each reply, `history_for()` presents the current speaker's earlier replies as `assistant` messages and the other speaker's replies as `user` messages. It keeps the original topic and recent messages within a 12,000-character request-history budget. The full conversation remains in the UI and exports.
|
||||
|
||||
Requests go to `{base_url}/chat/completions` with the speaker's system prompt, model ID, temperature `0.7`, and `max_tokens` of `2000`. Streaming reads server-sent `data:` events and requests usage reporting. If a stream fails or is empty, the app attempts a regular JSON completion. Transport and empty-response failures receive up to two retries. The same message bubble is reused during fallback, replacing partial stream content with the final reply.
|
||||
|
||||
`settings.py` writes JSON through a temporary file and atomic replace. Use an `env:VARIABLE` API-key reference for hosted-provider secrets. `.env`, `sloppy.json`, screenshots, and transcripts are ignored by Git.
|
||||
|
||||
## Tests
|
||||
|
||||
After installing `requirements.txt`, run:
|
||||
|
||||
```powershell
|
||||
python -m unittest discover -v
|
||||
```
|
||||
|
||||
The suite covers CLI and settings behavior, streaming and fallback, speaker roles and bounded history, UI controls, statistics, and transcript export. It uses `httpx.MockTransport` and Textual's test pilot, so no live model server is needed.
|
||||
@@ -1,8 +1,32 @@
|
||||
# Sloppy
|
||||
|
||||
Run `python run_example.py --prompt "Your topic"`. With the original `.env` configuration and no `sloppy.json`, the conversation starts directly as before. Use **Ctrl+M** to add, edit, or delete connections. Once `sloppy.json` exists, the launch picker lets you choose saved models or the current `.env` connections for AI 1 and AI 2. **Ctrl+P** opens the command palette. A selection made during a conversation applies to the next run.
|
||||
Sloppy is a terminal app where two AI models discuss an initial prompt. AI 1 replies first, then AI 2, alternating for a chosen number of replies. It supports OpenAI-compatible chat-completions APIs, including local servers.
|
||||
|
||||
Settings are saved in `sloppy.json` in the current working directory. Example:
|
||||
## Setup
|
||||
|
||||
Use Python 3.10 or newer and configure two reachable models. The same endpoint can serve both.
|
||||
|
||||
```powershell
|
||||
python -m venv .venv
|
||||
.venv\Scripts\Activate.ps1
|
||||
python -m pip install -r requirements.txt
|
||||
Copy-Item .env.example .env
|
||||
```
|
||||
|
||||
Edit `.env` for your endpoints, keys, model IDs, and topic, then run `python run_example.py`. On macOS or Linux, activate with `source .venv/bin/activate` and copy the example with `cp .env.example .env`. `python ai_chat.py` is an equivalent entry point.
|
||||
|
||||
```powershell
|
||||
python run_example.py --prompt "Can AI be creative?" --turns 6
|
||||
python run_example.py --help
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
`.env` accepts `AI1_NAME`, `AI1_BASE_URL`, `AI1_API_KEY`, `AI1_MODEL`, and `AI1_SYSTEM_PROMPT`, plus matching `AI2_*` variables. `INITIAL_PROMPT` is required. `MAX_TURNS` defaults to 20 and must be positive. Set each base URL to an API root such as `http://localhost:11434/v1`; Sloppy appends `/chat/completions`.
|
||||
|
||||
Command-line options `--ai1-name`, `--ai1-url`, `--ai1-key`, `--ai1-model`, `--ai1-prompt` and matching `--ai2-*` options override `.env` values for a run. When any connection option is supplied, both connections need a base URL and API key after applying defaults. Prefer environment variables over command-line arguments for hosted-provider secrets, since command-line values can enter shell history.
|
||||
|
||||
Press **Ctrl+M** to add, edit, delete, and select saved connections. They are stored in `sloppy.json` in the current working directory:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -10,7 +34,7 @@ Settings are saved in `sloppy.json` in the current working directory. Example:
|
||||
"local": {
|
||||
"name": "Local Llama",
|
||||
"base_url": "http://localhost:11434/v1",
|
||||
"api_key": "ollama",
|
||||
"api_key": "env:LOCAL_API_KEY",
|
||||
"model": "llama3",
|
||||
"system_prompt": "You are a helpful assistant."
|
||||
}
|
||||
@@ -19,6 +43,29 @@ Settings are saved in `sloppy.json` in the current working directory. Example:
|
||||
}
|
||||
```
|
||||
|
||||
For a hosted provider, set `api_key` to `env:YOUR_API_KEY_VARIABLE` to keep the secret out of JSON. `.env` values are read fresh on every launch; they are never copied into `sloppy.json`. Existing `--ai1-*` and `--ai2-*` arguments still start directly with the supplied connections.
|
||||
Set `LOCAL_API_KEY` in the process environment when using `env:LOCAL_API_KEY`. The app resolves it when selecting the connection. You can select the current `.env` connection for either speaker. `.env` values are reread on launch and are never copied into `sloppy.json`. With complete `.env` connections and no `sloppy.json`, the conversation starts directly; otherwise a picker opens. Changes to speaker selection during a conversation apply on the next run.
|
||||
|
||||
Press **S** or **F2** during a chat to open the sharing menu. Choose **T** to save a text-only Markdown transcript in `transcripts/`, with the initial prompt and each speaker's replies in order. The SVG screenshot options remain available.
|
||||
## Controls and exports
|
||||
|
||||
| Key | Action |
|
||||
| --- | --- |
|
||||
| Ctrl+M | Connections and speaker selection |
|
||||
| Ctrl+P | Command palette |
|
||||
| F1 | Reading controls |
|
||||
| S or F2 | Sharing menu |
|
||||
| Mouse wheel, Up / Down, Page Up / Page Down | Scroll |
|
||||
| Home / End | Oldest / latest message |
|
||||
| Ctrl+C | Quit |
|
||||
|
||||
Scrolling up pauses automatic following; **End** resumes it. The UI shows elapsed time, reply count, word counts, and token usage when the provider reports it. Token and speed figures may be estimates when usage is unavailable.
|
||||
|
||||
The sharing menu saves the full conversation or visible screen as SVG in `screenshots/`, or a Markdown transcript in `transcripts/`. The transcript includes the initial prompt and replies in order. Both directories are created in the current working directory and ignored by Git.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **No connection in the picker:** Complete the base URL and key in `.env`, or add a saved connection with **Ctrl+M**.
|
||||
- **Missing API key:** Set the environment variable named by a saved `env:NAME` reference before launch.
|
||||
- **API error:** Check the API root, model ID, server availability, and credentials. A failed stream falls back to a non-streaming request; transport and empty-response failures receive up to two retries.
|
||||
- **Invalid settings:** Fix malformed `sloppy.json` in the current working directory. Its top-level `models` value must be an object.
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for code structure and tests.
|
||||
@@ -741,6 +741,7 @@ class AIChatApp(App):
|
||||
await self._try_streaming(ai, history, bubble)
|
||||
except Exception as stream_error:
|
||||
self.update_status(f"Streaming failed ({self.describe_error(stream_error)}); trying non-streaming")
|
||||
bubble.set_content("")
|
||||
bubble.set_waiting(True)
|
||||
try:
|
||||
bubble.set_content(await self.call_ai(ai, history))
|
||||
@@ -870,11 +871,13 @@ class AIChatApp(App):
|
||||
error_body = await response.aread()
|
||||
raise Exception(f"API Error {response.status_code}: {error_body.decode(errors='replace')}")
|
||||
|
||||
done = False
|
||||
async for line in response.aiter_lines():
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
data = line[5:].lstrip()
|
||||
if data == "[DONE]":
|
||||
done = True
|
||||
break
|
||||
if not data:
|
||||
continue
|
||||
@@ -890,6 +893,8 @@ class AIChatApp(App):
|
||||
if not isinstance(delta, str):
|
||||
raise ValueError("Invalid stream content")
|
||||
yield delta
|
||||
if not done:
|
||||
raise ValueError("Stream ended before [DONE]")
|
||||
|
||||
def update_status(self, text: str) -> None:
|
||||
self.status_bar.update(f"Status: {text}")
|
||||
|
||||
+22
-4
@@ -16,16 +16,34 @@ def load_settings(path=DEFAULT_PATH):
|
||||
raise ValueError('sloppy.json must contain a models object')
|
||||
data.setdefault('models', {})
|
||||
data.setdefault('selected', {'ai1': '', 'ai2': ''})
|
||||
if not isinstance(data['selected'], dict):
|
||||
raise ValueError('sloppy.json selected must be an object')
|
||||
for slot, value in data['selected'].items():
|
||||
if not isinstance(slot, str) or not isinstance(value, str):
|
||||
raise ValueError(f'sloppy.json selected.{slot} must be a string')
|
||||
for identifier, values in data['models'].items():
|
||||
if not isinstance(identifier, str) or not isinstance(values, dict):
|
||||
raise ValueError(f'sloppy.json models.{identifier} must be an object')
|
||||
for field in ('name', 'base_url', 'api_key', 'model', 'system_prompt'):
|
||||
if field in values and not isinstance(values[field], str):
|
||||
raise ValueError(f'sloppy.json models.{identifier}.{field} must be a string')
|
||||
return data
|
||||
|
||||
|
||||
def save_settings(data, path=DEFAULT_PATH):
|
||||
path = Path(path)
|
||||
temporary = path.with_name(path.name + '.tmp')
|
||||
temporary.write_text(json.dumps(data, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
|
||||
os.replace(temporary, path)
|
||||
if os.name != 'nt':
|
||||
path.chmod(0o600)
|
||||
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
||||
if hasattr(os, 'O_BINARY'):
|
||||
flags |= os.O_BINARY
|
||||
try:
|
||||
descriptor = os.open(temporary, flags, 0o600)
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as output:
|
||||
output.write(json.dumps(data, indent=2, ensure_ascii=False) + '\n')
|
||||
os.replace(temporary, path)
|
||||
except BaseException:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def model_from_settings(data, identifier):
|
||||
|
||||
@@ -5,6 +5,7 @@ import contextlib
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import stat
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -175,6 +176,29 @@ class ChatTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual(len(app.query(MessageBubble)), 2)
|
||||
self.assertFalse(app.query(MessageBubble).last()._streaming)
|
||||
|
||||
async def test_missing_done_clears_partial_before_fallback_and_history(self):
|
||||
requests = []
|
||||
fallback_started = asyncio.Event()
|
||||
release_fallback = asyncio.Event()
|
||||
async def handler(request):
|
||||
payload = json.loads(request.content)
|
||||
requests.append(payload)
|
||||
if payload.get('stream'):
|
||||
if len(requests) == 1:
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"partial secret"}}]}\n\ndata: {"choices":[],"usage":{"completion_tokens":2}}\n\n')
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"second reply"}}]}\n\ndata: [DONE]\n\n')
|
||||
fallback_started.set()
|
||||
await release_fallback.wait()
|
||||
return httpx.Response(200, json={'choices': [{'message': {'content': 'complete reply'}}]})
|
||||
app = await self.make_app(handler, turns=2)
|
||||
async with app.run_test() as pilot:
|
||||
await asyncio.wait_for(fallback_started.wait(), 2)
|
||||
self.assertEqual(app.query(MessageBubble).last().message.content, '')
|
||||
release_fallback.set()
|
||||
await self.wait_finished(app, pilot)
|
||||
self.assertEqual([m.content for m in app.messages], ['Start here', 'complete reply', 'second reply'])
|
||||
self.assertNotIn('partial secret', json.dumps(requests[2]))
|
||||
|
||||
async def test_empty_stream_uses_fallback(self):
|
||||
calls = []
|
||||
def handler(request):
|
||||
@@ -350,6 +374,42 @@ class ChatTests(unittest.IsolatedAsyncioTestCase):
|
||||
|
||||
|
||||
class CommandLineTests(unittest.TestCase):
|
||||
def test_settings_validation_identifies_invalid_fields(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'sloppy.json'
|
||||
for data, field in [
|
||||
({'models': {}, 'selected': None}, 'selected'),
|
||||
({'models': {'x': None}}, 'models.x'),
|
||||
({'models': {'x': {'api_key': None}}}, 'models.x.api_key'),
|
||||
({'models': {}, 'selected': {'ai1': None}}, 'selected.ai1'),
|
||||
]:
|
||||
path.write_text(json.dumps(data), encoding='utf-8')
|
||||
with self.subTest(field=field), self.assertRaisesRegex(ValueError, field.replace('.', r'\.')):
|
||||
load_settings(path)
|
||||
path.write_text(json.dumps({'models': {'x': {'model': 'm'}}}), encoding='utf-8')
|
||||
self.assertEqual(load_settings(path)['selected'], {'ai1': '', 'ai2': ''})
|
||||
|
||||
@unittest.skipIf(os.name == 'nt', 'Unix file modes only')
|
||||
def test_settings_temp_is_private_and_failure_cleans_up(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'sloppy.json'
|
||||
for existing in (False, True):
|
||||
if existing:
|
||||
path.write_text('old', encoding='utf-8')
|
||||
path.chmod(0o644)
|
||||
original_replace = os.replace
|
||||
def inspect_replace(source, destination):
|
||||
self.assertEqual(stat.S_IMODE(source.stat().st_mode), 0o600)
|
||||
self.assertIn('secret', source.read_text(encoding='utf-8'))
|
||||
original_replace(source, destination)
|
||||
with patch('settings.os.replace', side_effect=inspect_replace):
|
||||
save_settings({'api_key': 'secret'}, path)
|
||||
self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
|
||||
with patch('settings.os.replace', side_effect=OSError('replace failed')):
|
||||
with self.assertRaisesRegex(OSError, 'replace failed'):
|
||||
save_settings({'api_key': 'secret'}, path)
|
||||
self.assertFalse(path.with_name('sloppy.json.tmp').exists())
|
||||
|
||||
def test_env_only_starts_without_picker_or_json_import(self):
|
||||
variables = {
|
||||
'AI1_BASE_URL': 'http://one.test/v1', 'AI1_API_KEY': 'one-key',
|
||||
|
||||
Reference in new issue
Block a user