Files
sloppy/ai_chat.py
T

842 lines
32 KiB
Python

import asyncio
import json
import logging
import os
import io
from datetime import datetime
from pathlib import Path
from time import monotonic
from dataclasses import dataclass
import httpx
from dotenv import load_dotenv
from textual.app import App, ComposeResult
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
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.binding import Binding
from textual.screen import ModalScreen
log = logging.getLogger(__name__)
@dataclass
class AIConfig:
name: str
base_url: str
api_key: str
model: str
system_prompt: str = "You are a helpful assistant."
@dataclass
class ChatMessage:
role: str
content: str
sender: str
class SquareLoadingIndicator(Static):
"""A hollow three-by-three square with a rotating highlight."""
def on_mount(self) -> None:
self.auto_refresh = 0.15
def render(self) -> Text:
active = int(monotonic() / 0.15) % 8
if self.app.animation_level == "none":
active = 0
color = self.rich_style.color
result = Text(no_wrap=True)
for row, positions in enumerate(((0, 1, 2), (7, -1, 3), (6, 5, 4))):
if row:
result.append("\n")
for column, position in enumerate(positions):
if column:
result.append(" ")
result.append(" " if position == -1 else "\u25cf", style=f"{'bold' if position == active else 'dim'} {color.name if color else 'cyan'}")
return result
class MessageBubble(Static):
"""A chat message bubble that supports streaming updates."""
def __init__(self, message: ChatMessage, **kwargs):
super().__init__(**kwargs)
self.message = message
self.border_title = f"[bold]{message.sender}[/bold]"
if message.sender == "AI 1":
self.styles.border = ("round", "blue")
else:
self.styles.border = ("round", "green")
self._content_widget = Static(message.content, classes="bubble-content", markup=False)
self._streaming = False
self._waiting_widget = Horizontal(
SquareLoadingIndicator(),
Static("Waiting for response...", markup=False, classes="waiting-label"),
classes="response-waiting",
)
self._waiting_widget.display = False
self._render_content()
def _render_content(self) -> None:
# Keep the raw source in message.content for subsequent API requests.
content = self.message.content
self._content_widget.update(
Markdown(content, code_theme="monokai")
if self.message.role == "assistant" else content
)
def set_waiting(self, waiting: bool) -> None:
self._waiting_widget.display = waiting
self._content_widget.display = bool(self.message.content.strip()) or not waiting
def compose(self) -> ComposeResult:
yield self._content_widget
yield self._waiting_widget
def set_content(self, content: str) -> None:
"""Set the full content (non-streaming)."""
self.message.content = content
self._render_content()
self.set_waiting(False)
self.refresh()
def append_content(self, delta: str) -> None:
"""Append content for streaming."""
self.message.content += delta
self._render_content()
if self.message.content.strip():
self.set_waiting(False)
self.refresh()
def start_streaming(self) -> None:
"""Mark as streaming."""
self._streaming = True
self.set_waiting(True)
self.refresh()
def end_streaming(self) -> None:
"""Mark streaming as complete."""
self._streaming = False
self.set_waiting(False)
self.refresh()
class ChatContainer(VerticalScroll):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.messages: list[ChatMessage] = []
def add_message(self, message: ChatMessage) -> MessageBubble:
"""Add a new message and return its bubble for streaming."""
bubble = MessageBubble(message)
self.mount(bubble)
self.messages.append(message)
self.refresh()
return bubble
def update_last_message(self, content: str) -> None:
"""Update the last message's content."""
if self.messages:
self.messages[-1].content = content
bubbles = self.query(MessageBubble)
if bubbles:
bubbles.last().set_content(content)
self.refresh()
class ControlsHelp(ModalScreen):
BINDINGS = [Binding("escape,f1", "dismiss", "Close")]
DEFAULT_CSS = """
ControlsHelp { align: center middle; }
#controls-help {
width: 64;
max-width: 95%;
height: auto;
padding: 1 2;
border: round $primary;
background: $surface;
}
"""
def compose(self) -> ComposeResult:
yield Static(
"[bold]Reading controls[/bold]\n\n"
"Mouse wheel / Up / Down: scroll\n"
"Page Up / Page Down: scroll a page\n"
"S / F2: save visible screen or full conversation\n"
"Home: oldest message\n"
"End: latest message and resume following\n\n"
"Scrolling up pauses automatic following.\n\n"
"[bold]Zoom (Windows Terminal)[/bold]\n"
"Ctrl + Plus: larger text\n"
"Ctrl + Minus: smaller text\n"
"Ctrl + 0: reset font size\n\n"
"Font size is controlled by your terminal.\n"
"Other terminals may use different shortcuts.\n\n"
"Escape / F1: close help",
id="controls-help",
)
class ScreenshotOptions(ModalScreen[str | None]):
BINDINGS = [
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; }
#screenshot-options {
width: 58;
max-width: 95%;
height: auto;
padding: 1 2;
border: round $primary;
background: $surface;
}
#screenshot-options Button { width: 100%; margin-top: 1; }
"""
def compose(self) -> ComposeResult:
with Container(id="screenshot-options"):
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 AIChatApp(App):
CSS = """
Screen {
background: $surface;
}
#elapsed-time {
height: 1;
padding: 0 1;
text-align: right;
background: $surface-darken-1;
}
#chat-container {
height: 1fr;
border: solid $primary;
margin: 1;
padding: 1;
}
.bubble-content {
padding: 1;
width: 100%;
}
.response-waiting {
height: 3;
align-vertical: middle;
}
.response-waiting SquareLoadingIndicator {
width: 5;
height: 3;
margin: 0 2 0 1;
color: $primary;
}
.response-waiting .waiting-label {
width: 1fr;
height: 3;
content-align: left middle;
}
MessageBubble {
margin: 1 0;
width: 100%;
min-height: 3;
}
#conversation-stats {
height: auto;
padding: 0 1;
margin: 0 1;
border-top: solid $primary;
background: $surface-darken-1;
}
#turn-counter {
height: 1;
padding: 0 1;
background: $surface-darken-1;
text-style: bold;
}
#status-bar {
height: 3;
padding: 0 1;
background: $surface-darken-1;
}
"""
BINDINGS = [
Binding("ctrl+c", "quit", "Quit"),
Binding("f1", "controls_help", "Help / Zoom"),
Binding("s", "screenshot_options", "Screenshot", priority=True),
Binding("f2", "screenshot_options", show=False, priority=True),
Binding("pageup", "chat_scroll('page_up')", "Page up", priority=True),
Binding("pagedown", "chat_scroll('page_down')", "Page down", priority=True),
Binding("home", "chat_scroll('home')", "Oldest", priority=True),
Binding("end", "chat_scroll('end')", "Latest", priority=True),
Binding("up", "chat_scroll('up')", show=False, priority=True),
Binding("down", "chat_scroll('down')", show=False, priority=True),
]
def __init__(
self,
ai1_config: AIConfig,
ai2_config: AIConfig,
initial_prompt: str,
max_turns: int = 20,
):
super().__init__()
if max_turns < 1:
raise ValueError("max_turns must be positive")
self.ai1 = ai1_config
self.ai2 = ai2_config
self.initial_prompt = initial_prompt
self.max_turns = max_turns
self.messages: list[ChatMessage] = []
self.current_turn = 0
self.api_input_tokens = 0
self.api_output_tokens = 0
self.usage_reports = 0
self._response_started = None
self._response_chars = 0
self._response_usage = None
self._total_response_tokens = 0
self._total_response_seconds = 0.0
self._average_estimated = False
self._last_speed = 0.0
self._last_speed_exact = False
self._last_response_seconds = 0.0
self._started_at: float | None = None
self._ended_at: float | None = None
self._is_running = False
self.client = httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=10.0))
def compose(self) -> ComposeResult:
yield Header(show_clock=True)
yield Container(
Static("Elapsed: 00:00:00", id="elapsed-time", markup=False),
ChatContainer(id="chat-container"),
Static(f"Turns completed: 0 / {self.max_turns}", id="turn-counter", markup=False),
Static(id="conversation-stats", markup=False),
Static(id="status-bar", markup=False),
id="main-container"
)
yield Footer()
async def on_mount(self) -> None:
self.chat_container = self.query_one(ChatContainer)
self.status_bar = self.query_one("#status-bar", Static)
self.turn_counter = self.query_one("#turn-counter", Static)
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)
def action_screenshot_options(self) -> None:
if not isinstance(self.screen, ScreenshotOptions):
self.push_screen(ScreenshotOptions(), self._screenshot_selected)
def _screenshot_selected(self, choice: str | None) -> None:
if choice is not None:
# Capture after the modal has been removed from the screen.
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."""
console = Console(
width=max(40, self.size.width), file=io.StringIO(),
record=True, force_terminal=True, color_system="truecolor",
)
for message in self.messages:
content = Markdown(message.content, code_theme="monokai") if message.role == "assistant" else Text(message.content)
console.print(Panel(
content, title=Text(message.sender),
border_style="blue" if message.sender == "AI 1" else "green",
padding=(1, 1),
))
return console.export_svg(title="AI conversation")
def _save_conversation_screenshot(self, choice: str) -> None:
try:
directory = Path("screenshots")
directory.mkdir(exist_ok=True)
filename = f"conversation-{choice}-{datetime.now():%Y%m%d-%H%M%S-%f}.svg"
path = directory / filename
if choice == "full":
path.write_text(self.export_conversation_screenshot(), encoding="utf-8")
else:
self.save_screenshot(filename=filename, path=str(directory))
except (OSError, ValueError) as error:
self.notify(f"Could not save screenshot: {error}", severity="error")
else:
self.notify(f"Screenshot saved: {path.resolve()}", timeout=10)
def action_controls_help(self) -> None:
self.push_screen(ControlsHelp())
def action_chat_scroll(self, direction: str) -> None:
if isinstance(self.screen, (ControlsHelp, ScreenshotOptions)):
return
chat = self.chat_container
if direction == "end":
chat.anchor()
elif direction == "home":
chat.scroll_home(animate=False)
elif direction == "page_up":
chat.scroll_page_up(animate=False)
elif direction == "page_down":
chat.scroll_page_down(animate=False)
elif direction == "up":
chat.scroll_up(animate=False)
elif direction == "down":
chat.scroll_down(animate=False)
async def start_conversation(self) -> None:
self._is_running = True
self._started_at = monotonic()
self._ended_at = None
elapsed_timer = self.set_interval(1, self.update_elapsed_time)
self.update_status(f"Starting conversation... AI 1 ({self.ai1.name}) begins")
self.chat_container.messages = self.messages
self.chat_container.add_message(ChatMessage("user", self.initial_prompt, "System"))
try:
await self.run_conversation_loop()
finally:
self._ended_at = monotonic()
elapsed_timer.stop()
self.update_elapsed_time()
def update_elapsed_time(self) -> None:
if self._started_at is None:
return
end = self._ended_at if self._ended_at is not None else monotonic()
seconds = max(0, int(end - self._started_at))
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
self.elapsed_time.update(f"Elapsed: {hours:02d}:{minutes:02d}:{seconds:02d}")
self.update_statistics()
@staticmethod
def estimate_tokens(text: str) -> int:
# Rough text-only estimate, independent of the server's tokenizer.
return (len(text) + 3) // 4
def begin_response_metrics(self) -> None:
self._response_started = monotonic()
self._response_chars = 0
self._response_usage = None
def record_usage(self, usage) -> None:
if isinstance(usage, dict):
self._response_usage = usage
def finish_response_metrics(self) -> None:
if self._response_started is None:
return
self._last_response_seconds = max(0.001, monotonic() - self._response_started)
usage = self._response_usage or {}
for key, attr in (("prompt_tokens", "api_input_tokens"),
("completion_tokens", "api_output_tokens")):
value = usage.get(key)
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
setattr(self, attr, getattr(self, attr) + value)
if usage:
self.usage_reports += 1
count = usage.get("completion_tokens")
self._last_speed_exact = isinstance(count, int) and not isinstance(count, bool) and count >= 0
if not self._last_speed_exact:
count = (self._response_chars + 3) // 4
self._total_response_tokens += count
self._total_response_seconds += self._last_response_seconds
self._average_estimated |= not self._last_speed_exact
self._last_speed = count / self._last_response_seconds
self._response_started = None
self.update_statistics()
def update_statistics(self) -> None:
if not self.is_mounted:
return
transcript = [m.content for m in self.messages if m.role != "system"]
words = sum(len(text.split()) for text in transcript)
chars = sum(len(text) for text in transcript)
tokens = sum(self.estimate_tokens(text) for text in transcript)
replies = sum(m.role == "assistant" and bool(m.content.strip()) for m in self.messages)
speed = self._last_speed
marker = "" if self._last_speed_exact else "~"
timing = f"Last response: {self._last_response_seconds:.1f}s"
if self._response_started is not None:
seconds = max(0.001, monotonic() - self._response_started)
speed = ((self._response_chars + 3) // 4) / seconds
marker = "~"
timing = f"Current request: {seconds:.1f}s"
total_tokens = self._total_response_tokens
total_seconds = self._total_response_seconds
average_estimated = self._average_estimated
if self._response_started is not None:
total_tokens += (self._response_chars + 3) // 4
total_seconds += seconds
average_estimated = True
average = total_tokens / total_seconds if total_seconds else 0.0
average_marker = "~" if average_estimated else ""
grid = Table.grid(expand=True, padding=(0, 1))
for _ in range(5):
grid.add_column(ratio=1)
grid.add_row(
Text(f"~{tokens:,}", style="bold cyan"),
Text(f"{words:,}", style="bold cyan"),
Text(f"{marker}{speed:.1f}", style="bold green"),
Text(f"{average_marker}{average:.1f}", style="bold green"),
Text(timing.split(": ", 1)[1], style="bold yellow"),
)
grid.add_row(
Text("TOKENS | EST.", style="dim"), Text("WORDS", style="dim"),
Text("LIVE TOK/S" if self._response_started is not None else "LAST TOK/S", style="dim"),
Text("AVG TOK/S", style="dim"),
Text("REQUEST TIME" if self._response_started is not None else "LAST RESPONSE", style="dim"),
)
details = Text(f"{replies:,} replies | {chars:,} characters | TPS includes waiting", style="dim")
api = Text("API usage: not reported", style="dim")
if self.usage_reports:
api = Text.assemble(
("API TOKENS ", "dim"),
(f"{self.api_input_tokens:,} input / {self.api_output_tokens:,} output", "cyan"),
(f" | {self.usage_reports:,} reported requests", "dim"),
)
self.query_one("#conversation-stats", Static).update(Group(grid, details, api))
def history_for(self, sender: str) -> list[dict]:
"""Describe each turn from the responding model's perspective."""
history = [
{"role": "assistant" if message.sender == sender else "user",
"content": message.content}
for message in self.messages
if message.role != "system" and message.content.strip()
]
# Conservative character budget: no tokenizer dependency, and room for
# the system prompt and output in a 16K-token server slot. Keep the
# original topic and newest complete messages; UI history stays intact.
budget = 12000
if sum(len(m["content"]) + 64 for m in history) <= budget:
return history
first = dict(history[0])
first["content"] = first["content"][:2000]
remaining = budget - len(first["content"]) - 64
recent = []
for message in reversed(history[1:]):
cost = len(message["content"]) + 64
if cost > remaining:
if not recent:
recent.append({**message, "content": message["content"][-max(1, remaining - 64):]})
break
recent.append(message)
remaining -= cost
return [first] + list(reversed(recent))
@staticmethod
def describe_error(error: Exception) -> str:
return f"{type(error).__name__}: {str(error).strip() or 'Request failed without an error message'}"
async def respond(self, ai: AIConfig, history: list[dict], bubble: MessageBubble) -> None:
for attempt in range(3):
bubble.set_content("")
try:
try:
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))
finally:
bubble.set_waiting(False)
return
except (httpx.TransportError, ValueError) as error:
if attempt == 2:
raise
self.update_status(f"Retry {attempt + 1}/2: {self.describe_error(error)}")
bubble.set_waiting(True)
try:
await asyncio.sleep(2 ** attempt)
finally:
bubble.set_waiting(False)
async def run_conversation_loop(self) -> None:
try:
while self.current_turn < self.max_turns and self._is_running:
current_ai = self.ai1 if self.current_turn % 2 == 0 else self.ai2
sender = "AI 1" if self.current_turn % 2 == 0 else "AI 2"
history = self.history_for(sender)
self.update_status(f"Streaming... ({sender}: {current_ai.name})")
bubble = self.chat_container.add_message(ChatMessage("assistant", "", sender))
try:
await self.respond(current_ai, history, bubble)
except Exception as error:
error_msg = f"Error: {self.describe_error(error)}"
self.chat_container.add_message(ChatMessage("system", error_msg, "System"))
self.update_status(error_msg)
return
self.update_statistics()
self.current_turn += 1
self.turn_counter.update(
f"Turns completed: {self.current_turn} / {self.max_turns}"
)
if self.current_turn < self.max_turns:
await asyncio.sleep(0.5)
self.update_status("Conversation ended. Press Ctrl+C to quit.")
finally:
self._is_running = False
async def _try_streaming(self, ai: AIConfig, history: list[dict], bubble: MessageBubble) -> str:
"""Stream into a single bubble, reused if a fallback is needed."""
self.begin_response_metrics()
bubble.start_streaming()
full_response = ""
try:
async for chunk in self.stream_ai(ai, history):
self._response_chars += len(chunk)
full_response += chunk
bubble.append_content(chunk)
self.update_statistics()
await asyncio.sleep(0)
if not full_response.strip():
raise ValueError("Empty response from API")
return full_response
finally:
bubble.end_streaming()
self.finish_response_metrics()
async def call_ai(self, ai: AIConfig, history: list[dict]) -> str:
"""Non-streaming fallback."""
messages = [{"role": "system", "content": ai.system_prompt}] + history
payload = {
"model": ai.model,
"messages": messages,
"temperature": 0.7,
"max_tokens": 2000,
}
headers = {
"Authorization": f"Bearer {ai.api_key}",
"Content-Type": "application/json",
}
url = f"{ai.base_url.rstrip('/')}/chat/completions"
self.begin_response_metrics()
try:
return await self._call_ai_response(url, payload, headers)
finally:
self.finish_response_metrics()
async def _call_ai_response(self, url: str, payload: dict, headers: dict) -> str:
response = await self.client.post(url, json=payload, headers=headers)
if response.status_code != 200:
raise Exception(f"API Error {response.status_code}: {response.text}")
data = response.json()
self.record_usage(data.get("usage"))
if "error" in data:
raise Exception(f"API Error: {data['error']}")
content = data["choices"][0]["message"].get("content")
if not isinstance(content, str) or not content.strip():
raise ValueError("Empty response from API")
self._response_chars = len(content)
return content
async def stream_ai(self, ai: AIConfig, history: list[dict]):
"""Stream response from AI using SSE."""
messages = [{"role": "system", "content": ai.system_prompt}] + history
payload = {
"model": ai.model,
"messages": messages,
"temperature": 0.7,
"max_tokens": 2000,
"stream": True,
"stream_options": {"include_usage": True},
}
headers = {
"Authorization": f"Bearer {ai.api_key}",
"Content-Type": "application/json",
"Accept": "text/event-stream",
}
url = f"{ai.base_url.rstrip('/')}/chat/completions"
log.debug(f"Streaming request to {url} with model {ai.model}")
async with self.client.stream("POST", url, json=payload, headers=headers) as response:
log.debug(f"Response status: {response.status_code}")
if response.status_code != 200:
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
chunk = json.loads(data)
if "error" in chunk:
raise ValueError(f"Stream error: {chunk['error']}")
self.record_usage(chunk.get("usage"))
choices = chunk.get("choices", [])
if not choices: # Usage-only events have no choices.
continue
delta = choices[0].get("delta", {}).get("content")
if delta is not None:
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}")
async def on_unmount(self) -> None:
await self.client.aclose()
def load_config() -> tuple[AIConfig, AIConfig, str, str]:
load_dotenv()
def get_env(key: str, default: str = "") -> str:
return os.getenv(key, default)
ai1 = AIConfig(
name=get_env("AI1_NAME", "AI 1"),
base_url=get_env("AI1_BASE_URL", ""),
api_key=get_env("AI1_API_KEY", ""),
model=get_env("AI1_MODEL", "gpt-3.5-turbo"),
system_prompt=get_env("AI1_SYSTEM_PROMPT", "You are a helpful assistant."),
)
ai2 = AIConfig(
name=get_env("AI2_NAME", "AI 2"),
base_url=get_env("AI2_BASE_URL", ""),
api_key=get_env("AI2_API_KEY", ""),
model=get_env("AI2_MODEL", "gpt-3.5-turbo"),
system_prompt=get_env("AI2_SYSTEM_PROMPT", "You are a helpful assistant."),
)
prompt = get_env("INITIAL_PROMPT", "")
turns = get_env("MAX_TURNS", "20")
return ai1, ai2, prompt, turns
def main():
import argparse
# Load from .env first
ai1_env, ai2_env, prompt_env, turns_env = load_config()
parser = argparse.ArgumentParser(description="Two AI models conversation TUI with streaming")
parser.add_argument("--ai1-name", default=ai1_env.name, help="Name for AI 1")
parser.add_argument("--ai1-url", default=ai1_env.base_url, help="Base URL for AI 1 (OpenAI-compatible)")
parser.add_argument("--ai1-key", default=ai1_env.api_key, help="API key for AI 1")
parser.add_argument("--ai1-model", default=ai1_env.model, help="Model for AI 1")
parser.add_argument("--ai1-prompt", default=ai1_env.system_prompt, help="System prompt for AI 1")
parser.add_argument("--ai2-name", default=ai2_env.name, help="Name for AI 2")
parser.add_argument("--ai2-url", default=ai2_env.base_url, help="Base URL for AI 2 (OpenAI-compatible)")
parser.add_argument("--ai2-key", default=ai2_env.api_key, help="API key for AI 2")
parser.add_argument("--ai2-model", default=ai2_env.model, help="Model for AI 2")
parser.add_argument("--ai2-prompt", default=ai2_env.system_prompt, help="System prompt for AI 2")
parser.add_argument("--prompt", default=prompt_env, help="Initial prompt for AI 1 to start")
parser.add_argument("--turns", type=int, default=turns_env, help="Maximum conversation turns")
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)
app.run()
if __name__ == "__main__":
main()