Add model settings and Markdown chat export
This commit is contained in:
1 parent
12f2a1655f
commit
e6db824792
5 files changed
+317
-36
No files matched your search
+199
-27
@@ -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()
|
||||
main()
|
||||
Reference in new issue
Block a user