diff --git a/.gitignore b/.gitignore index 04da1b5..d363b0d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,6 @@ +sloppy.json +sloppy.json.tmp .env -.env.* -!.env.example __pycache__/ -*.py[cod] -*.log -.venv/ -venv/ -.pytest_cache/ - screenshots/ -*rewrite* +transcripts/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..bf62d30 --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# 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. + +Settings are saved in `sloppy.json` in the current working directory. Example: + +```json +{ + "models": { + "local": { + "name": "Local Llama", + "base_url": "http://localhost:11434/v1", + "api_key": "ollama", + "model": "llama3", + "system_prompt": "You are a helpful assistant." + } + }, + "selected": {"ai1": "local", "ai2": "local"} +} +``` + +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. + +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. diff --git a/ai_chat.py b/ai_chat.py index fc358b3..be72a19 100644 --- a/ai_chat.py +++ b/ai_chat.py @@ -18,7 +18,7 @@ from rich.console import Group from rich.text import Text from rich.markdown import Markdown from textual.containers import Container, Horizontal, VerticalScroll -from textual.widgets import Header, Footer, Static, Button +from textual.widgets import Header, Footer, Static, Button, Input, Select, Label from textual.binding import Binding from textual.screen import ModalScreen @@ -191,6 +191,7 @@ class ScreenshotOptions(ModalScreen[str | None]): Binding("escape", "dismiss(None)", "Cancel"), Binding("f", "dismiss('full')", "Full conversation"), Binding("v", "dismiss('visible')", "Visible screen"), + Binding("t", "dismiss('text')", "Text transcript"), ] DEFAULT_CSS = """ ScreenshotOptions { align: center middle; } @@ -207,15 +208,133 @@ class ScreenshotOptions(ModalScreen[str | None]): def compose(self) -> ComposeResult: with Container(id="screenshot-options"): - yield Static("[bold]Save screenshot[/bold]\nSVG images are saved in screenshots/.") + yield Static("[bold]Share conversation[/bold]\nSave an SVG image or a Markdown transcript.") yield Button("Full conversation (F)", id="full", variant="primary") yield Button("Visible screen (V)", id="visible") + yield Button("Text transcript (T)", id="text") yield Button("Cancel", id="cancel") def on_button_pressed(self, event: Button.Pressed) -> None: self.dismiss(None if event.button.id == "cancel" else event.button.id) +class ModelSettings(ModalScreen[tuple[AIConfig, AIConfig] | None]): + """Choose the two speakers and maintain saved OpenAI-compatible connections.""" + + BINDINGS = [Binding("escape", "dismiss(None)", "Close")] + DEFAULT_CSS = """ + ModelSettings { align: center middle; } + #model-settings { width: 76; max-width: 95%; height: auto; max-height: 95%; + padding: 1 2; border: round $primary; background: $surface; overflow-y: auto; } + #model-settings Input, #model-settings Select { margin-bottom: 1; } + #model-actions Button { margin-right: 1; } + """ + + def __init__(self, path: Path, initial_ai1: AIConfig, initial_ai2: AIConfig): + super().__init__() + self.path = path + self.initial = (initial_ai1, initial_ai2) + from settings import load_settings + self.settings = load_settings(path) + + def compose(self) -> ComposeResult: + with VerticalScroll(id="model-settings"): + yield Static("[bold]Models and connections[/bold] • saved in sloppy.json") + yield Label("AI 1") + yield Select([], id="ai1-select", allow_blank=True) + yield Label("AI 2") + yield Select([], id="ai2-select", allow_blank=True) + yield Static("[bold]Add or edit a connection[/bold]") + yield Input(placeholder="Connection ID (e.g. local-llama)", id="connection-id") + yield Input(placeholder="Display name", id="model-name") + yield Input(placeholder="Base URL, e.g. http://localhost:11434/v1", id="base-url") + yield Input(placeholder="API key (or env:VARIABLE)", id="api-key", password=True) + yield Input(placeholder="Model ID", id="model-id") + yield Input(placeholder="System prompt", id="system-prompt") + with Horizontal(id="model-actions"): + yield Button("Save connection", id="save-model", variant="primary") + yield Button("Delete connection", id="delete-model") + yield Button("Use selected models", id="use-models", variant="success") + + def on_mount(self) -> None: + self.refresh_choices() + + def refresh_choices(self) -> None: + options = [(f"{key}: {value.get('name', key)} ({value.get('model', '')})", key) + for key, value in self.settings['models'].items()] + for slot, config in zip(('ai1', 'ai2'), self.initial): + if config.base_url and config.api_key: + options.append((f"{slot.upper()} from .env ({config.model})", f"env:{slot}")) + for slot in ('ai1', 'ai2'): + select = self.query_one(f"#{slot}-select", Select) + select.set_options(options) + chosen = self.settings['selected'].get(slot) + if chosen in self.settings['models'] or (chosen == f"env:{slot}" and chosen in [value for _, value in options]): + select.value = chosen + elif f"env:{slot}" in [value for _, value in options]: + select.value = f"env:{slot}" + + def on_select_changed(self, event: Select.Changed) -> None: + if event.select.id not in ('ai1-select', 'ai2-select'): + return + identifier = event.value + if not isinstance(identifier, str) or identifier not in self.settings['models']: + return + from settings import model_from_settings + values = model_from_settings(self.settings, identifier) + for widget_id, value in (('connection-id', identifier), ('model-name', values['name']), + ('base-url', values['base_url']), ('api-key', values['api_key']), + ('model-id', values['model']), ('system-prompt', values['system_prompt'])): + self.query_one(f"#{widget_id}", Input).value = value + + def on_button_pressed(self, event: Button.Pressed) -> None: + from settings import model_from_settings, save_settings, store_model + action = event.button.id + identifier = self.query_one('#connection-id', Input).value.strip() + try: + if action == 'save-model': + config = AIConfig( + self.query_one('#model-name', Input).value.strip(), + self.query_one('#base-url', Input).value.strip(), + self.query_one('#api-key', Input).value.strip(), + self.query_one('#model-id', Input).value.strip(), + self.query_one('#system-prompt', Input).value or 'You are a helpful assistant.', + ) + store_model(self.settings, identifier, config) + save_settings(self.settings, self.path) + self.refresh_choices() + self.notify(f"Saved {identifier}") + elif action == 'delete-model': + if identifier not in self.settings['models']: + raise ValueError('Select or enter an existing connection ID') + del self.settings['models'][identifier] + for slot in ('ai1', 'ai2'): + if self.settings['selected'].get(slot) == identifier: + self.settings['selected'][slot] = '' + save_settings(self.settings, self.path) + self.refresh_choices() + self.notify(f"Deleted {identifier}") + elif action == 'use-models': + identifiers = [self.query_one(f'#{slot}-select', Select).value for slot in ('ai1', 'ai2')] + valid = [set(self.settings['models']) | ({f'env:{slot}'} if config.base_url and config.api_key else set()) + for slot, config in zip(('ai1', 'ai2'), self.initial)] + if any(value not in choices for value, choices in zip(identifiers, valid)): + raise ValueError('Select a connection for each AI') + self.settings['selected'] = dict(zip(('ai1', 'ai2'), identifiers)) + save_settings(self.settings, self.path) + models = [self.initial[index] if value == f'env:ai{index + 1}' + else AIConfig(**model_from_settings(self.settings, value)) + for index, value in enumerate(identifiers)] + for model in models: + if model.api_key.startswith('env:'): + model.api_key = os.getenv(model.api_key[4:], '') + if not model.api_key: + raise ValueError(f'API key missing for {model.name}') + self.dismiss((models[0], models[1])) + except (OSError, ValueError) as error: + self.notify(str(error), severity='error') + + class AIChatApp(App): CSS = """ Screen { @@ -289,6 +408,8 @@ class AIChatApp(App): BINDINGS = [ Binding("ctrl+c", "quit", "Quit"), + Binding("ctrl+p", "command_palette", "Commands"), + Binding("ctrl+m", "model_settings", "Models"), Binding("f1", "controls_help", "Help / Zoom"), Binding("s", "screenshot_options", "Screenshot", priority=True), Binding("f2", "screenshot_options", show=False, priority=True), @@ -306,10 +427,16 @@ class AIChatApp(App): ai2_config: AIConfig, initial_prompt: str, max_turns: int = 20, + settings_path: Path | None = None, + choose_models: bool = False, + env_models: tuple[AIConfig, AIConfig] | None = None, ): super().__init__() if max_turns < 1: raise ValueError("max_turns must be positive") + self.settings_path = settings_path + self.choose_models = choose_models + self.env_models = env_models or (ai1_config, ai2_config) self.ai1 = ai1_config self.ai2 = ai2_config self.initial_prompt = initial_prompt @@ -352,7 +479,29 @@ class AIChatApp(App): self.elapsed_time = self.query_one("#elapsed-time", Static) self.chat_container.focus() self.chat_container.anchor() - self.run_worker(self.start_conversation(), exclusive=True) + if self.choose_models and self.settings_path: + self.action_model_settings() + else: + self.run_worker(self.start_conversation(), exclusive=True) + + def action_model_settings(self) -> None: + if self.settings_path and not isinstance(self.screen, ModelSettings): + try: + self.push_screen(ModelSettings(self.settings_path, *self.env_models), self._models_selected) + except (OSError, ValueError, json.JSONDecodeError) as error: + self.notify(f"Could not load settings: {error}", severity="error") + + def _models_selected(self, models: tuple[AIConfig, AIConfig] | None) -> None: + if models is None: + return + if self._is_running: + self.notify("Saved selection applies to the next conversation") + return + self.ai1, self.ai2 = models + if not self.messages: + self.run_worker(self.start_conversation(), exclusive=True) + else: + self.notify("Saved selection applies to the next conversation") def action_screenshot_options(self) -> None: if not isinstance(self.screen, ScreenshotOptions): @@ -361,7 +510,32 @@ class AIChatApp(App): def _screenshot_selected(self, choice: str | None) -> None: if choice is not None: # Capture after the modal has been removed from the screen. - self.call_after_refresh(self._save_conversation_screenshot, choice) + if choice == "text": + self.call_after_refresh(self._save_conversation_text) + else: + self.call_after_refresh(self._save_conversation_screenshot, choice) + + def export_conversation_text(self) -> str: + """Export the chat as readable Markdown without terminal styling.""" + lines = ["# AI conversation", "", f"AI 1: {self.ai1.name} ({self.ai1.model})", + f"AI 2: {self.ai2.name} ({self.ai2.model})", ""] + for message in self.messages: + if not message.content.strip(): + continue + label = "Initial prompt" if message.role == "user" else message.sender + lines.extend((f"## {label}", "", message.content.rstrip(), "")) + return "\n".join(lines).rstrip() + "\n" + + def _save_conversation_text(self) -> None: + try: + directory = Path("transcripts") + directory.mkdir(exist_ok=True) + path = directory / f"conversation-{datetime.now():%Y%m%d-%H%M%S-%f}.md" + path.write_text(self.export_conversation_text(), encoding="utf-8") + except (OSError, ValueError) as error: + self.notify(f"Could not save transcript: {error}", severity="error") + else: + self.notify(f"Transcript saved: {path.resolve()}", timeout=10) def export_conversation_screenshot(self) -> str: """Render all messages without the viewport's scrolling/clipping.""" @@ -776,34 +950,32 @@ def main(): args = parser.parse_args() - if not args.ai1_url or not args.ai1_key: - parser.error("AI1_BASE_URL and AI1_API_KEY required (set in .env or via --ai1-url/--ai1-key)") - if not args.ai2_url or not args.ai2_key: - parser.error("AI2_BASE_URL and AI2_API_KEY required (set in .env or via --ai2-url/--ai2-key)") if args.turns < 1: parser.error("--turns / MAX_TURNS must be positive") if not args.prompt.strip(): parser.error("INITIAL_PROMPT required (set in .env or via --prompt)") - - ai1 = AIConfig( - name=args.ai1_name, - base_url=args.ai1_url, - api_key=args.ai1_key, - model=args.ai1_model, - system_prompt=args.ai1_prompt, - ) - - ai2 = AIConfig( - name=args.ai2_name, - base_url=args.ai2_url, - api_key=args.ai2_key, - model=args.ai2_model, - system_prompt=args.ai2_prompt, - ) - - app = AIChatApp(ai1, ai2, args.prompt, args.turns) + + ai1 = AIConfig(args.ai1_name, args.ai1_url, args.ai1_key, args.ai1_model, args.ai1_prompt) + ai2 = AIConfig(args.ai2_name, args.ai2_url, args.ai2_key, args.ai2_model, args.ai2_prompt) + from settings import DEFAULT_PATH, load_settings + try: + load_settings(DEFAULT_PATH) + except (OSError, ValueError, json.JSONDecodeError) as error: + parser.error(f"Could not load sloppy.json: {error}") + import sys + explicit_models = any(arg.startswith(("--ai1-", "--ai2-")) for arg in sys.argv[1:]) + if explicit_models: + ai1 = AIConfig(args.ai1_name, args.ai1_url, args.ai1_key, args.ai1_model, args.ai1_prompt) + ai2 = AIConfig(args.ai2_name, args.ai2_url, args.ai2_key, args.ai2_model, args.ai2_prompt) + if not all((ai1.base_url, ai1.api_key, ai2.base_url, ai2.api_key)): + parser.error("Both AI connections need a base URL and API key") + env_ready = all((ai1.base_url, ai1.api_key, ai2.base_url, ai2.api_key)) + app = AIChatApp(ai1, ai2, args.prompt, args.turns, + settings_path=DEFAULT_PATH, + choose_models=not explicit_models and (DEFAULT_PATH.exists() or not env_ready), + env_models=(ai1_env, ai2_env)) app.run() if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/settings.py b/settings.py new file mode 100644 index 0000000..de9cc38 --- /dev/null +++ b/settings.py @@ -0,0 +1,42 @@ +import json +import os +from dataclasses import asdict +from pathlib import Path + + +DEFAULT_PATH = Path('sloppy.json') + + +def load_settings(path=DEFAULT_PATH): + path = Path(path) + if not path.exists(): + return {'models': {}, 'selected': {'ai1': '', 'ai2': ''}} + data = json.loads(path.read_text(encoding='utf-8')) + if not isinstance(data, dict) or not isinstance(data.get('models', {}), dict): + raise ValueError('sloppy.json must contain a models object') + data.setdefault('models', {}) + data.setdefault('selected', {'ai1': '', 'ai2': ''}) + 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) + + +def model_from_settings(data, identifier): + values = data['models'][identifier] + return {key: values.get(key, default) for key, default in ( + ('name', identifier), ('base_url', ''), ('api_key', ''), + ('model', ''), ('system_prompt', 'You are a helpful assistant.'))} + + +def store_model(data, identifier, config): + identifier = identifier.strip() + if not identifier or not all((config.name.strip(), config.base_url.strip(), config.model.strip())): + raise ValueError('ID, name, base URL, and model are required') + data['models'][identifier] = asdict(config) diff --git a/test_ai_chat.py b/test_ai_chat.py index 58a9e05..88fe947 100644 --- a/test_ai_chat.py +++ b/test_ai_chat.py @@ -4,6 +4,8 @@ import unittest import contextlib import io import os +import tempfile +from pathlib import Path from unittest.mock import patch from rich.console import Console @@ -12,6 +14,7 @@ from rich.markdown import Markdown import httpx from ai_chat import AIChatApp, AIConfig, MessageBubble, ChatMessage, ControlsHelp, ScreenshotOptions, main +from settings import load_settings, save_settings, store_model, model_from_settings class ChatTests(unittest.IsolatedAsyncioTestCase): @@ -328,8 +331,54 @@ class ChatTests(unittest.IsolatedAsyncioTestCase): self.assertIsInstance(app.screen, ScreenshotOptions) await pilot.press('escape') + async def test_text_transcript_preserves_message_order_and_markdown(self): + app = await self.make_app(lambda request: httpx.Response(500)) + try: + app.messages = [ + ChatMessage('user', 'Discuss **creativity**', 'System'), + ChatMessage('assistant', 'First point\n\n- detail', 'AI 1'), + ChatMessage('assistant', 'A counterpoint', 'AI 2'), + ] + exported = app.export_conversation_text() + self.assertLess(exported.index('## Initial prompt'), exported.index('## AI 1')) + self.assertLess(exported.index('## AI 1'), exported.index('## AI 2')) + self.assertIn('Discuss **creativity**', exported) + self.assertIn('First point\n\n- detail', exported) + self.assertNotIn('test-key', exported) + finally: + await app.client.aclose() + class CommandLineTests(unittest.TestCase): + def test_env_only_starts_without_picker_or_json_import(self): + variables = { + 'AI1_BASE_URL': 'http://one.test/v1', 'AI1_API_KEY': 'one-key', + 'AI2_BASE_URL': 'http://two.test/v1', 'AI2_API_KEY': 'two-key', + 'INITIAL_PROMPT': 'Discuss this', 'MAX_TURNS': '2', + } + with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, variables), \ + patch('sys.argv', ['ai_chat.py']), patch('ai_chat.AIChatApp.run', autospec=True) as run: + original = os.getcwd() + try: + os.chdir(directory) + main() + self.assertFalse(Path('sloppy.json').exists()) + finally: + os.chdir(original) + self.assertFalse(run.call_args.args[0].choose_models) + + def test_model_settings_round_trip(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'sloppy.json' + settings = load_settings(path) + store_model(settings, 'local', AIConfig('Local', 'http://localhost:11434/v1', + 'env:LOCAL_KEY', 'llama3')) + settings['selected'] = {'ai1': 'local', 'ai2': 'local'} + save_settings(settings, path) + loaded = load_settings(path) + self.assertEqual(loaded['selected']['ai2'], 'local') + self.assertEqual(model_from_settings(loaded, 'local')['api_key'], 'env:LOCAL_KEY') + def test_invalid_environment_turns_reports_usage_error(self): with patch.dict(os.environ, {"MAX_TURNS": "invalid"}), patch('sys.argv', ['ai_chat.py']): with contextlib.redirect_stderr(io.StringIO()) as stderr: