Files

841 lines
32 KiB
Python
Raw Permalink Normal View History

2026-10-06 15:46:37 +02:00
import asyncio
import json
import logging
import os
2026-10-15 01:05:01 +02:00
import io
from datetime import datetime
from pathlib import Path
2026-10-06 16:17:58 +02:00
from time import monotonic
2026-10-06 15:46:37 +02:00
from dataclasses import dataclass
import httpx
from dotenv import load_dotenv
from textual.app import App, ComposeResult
2026-10-15 01:05:01 +02:00
from rich.console import Console
from rich.panel import Panel
2026-11-12 17:11:56 +01:00
from rich.table import Table
from rich.console import Group
2026-10-06 16:17:58 +02:00
from rich.text import Text
from rich.markdown import Markdown
from textual.containers import Container, Horizontal, VerticalScroll
2026-11-13 10:25:43 +01:00
from textual.widgets import Header, Footer, Static, Button
2026-10-06 15:46:37 +02:00
from textual.binding import Binding
2026-10-06 16:17:58 +02:00
from textual.screen import ModalScreen
2026-10-06 15:46:37 +02:00
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
2026-10-06 16:17:58 +02:00
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
2026-10-06 15:46:37 +02:00
class MessageBubble(Static):
"""A chat message bubble that supports streaming updates."""
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
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
2026-10-06 16:17:58 +02:00
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
2026-10-06 15:46:37 +02:00
def compose(self) -> ComposeResult:
yield self._content_widget
2026-10-06 16:17:58 +02:00
yield self._waiting_widget
2026-10-06 15:46:37 +02:00
def set_content(self, content: str) -> None:
"""Set the full content (non-streaming)."""
self.message.content = content
2026-10-06 16:17:58 +02:00
self._render_content()
self.set_waiting(False)
2026-10-06 15:46:37 +02:00
self.refresh()
def append_content(self, delta: str) -> None:
"""Append content for streaming."""
self.message.content += delta
2026-10-06 16:17:58 +02:00
self._render_content()
if self.message.content.strip():
self.set_waiting(False)
2026-10-06 15:46:37 +02:00
self.refresh()
def start_streaming(self) -> None:
"""Mark as streaming."""
self._streaming = True
2026-10-06 16:17:58 +02:00
self.set_waiting(True)
2026-10-06 15:46:37 +02:00
self.refresh()
def end_streaming(self) -> None:
"""Mark streaming as complete."""
self._streaming = False
2026-10-06 16:17:58 +02:00
self.set_waiting(False)
2026-10-06 15:46:37 +02:00
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()
2026-10-06 16:17:58 +02:00
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"
2026-10-15 01:05:01 +02:00
"S / F2: save visible screen or full conversation\n"
2026-10-06 16:17:58 +02:00
"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",
)
2026-10-15 01:05:01 +02:00
class ScreenshotOptions(ModalScreen[str | None]):
BINDINGS = [
Binding("escape", "dismiss(None)", "Cancel"),
Binding("f", "dismiss('full')", "Full conversation"),
Binding("v", "dismiss('visible')", "Visible screen"),
2026-11-13 09:56:58 +01:00
Binding("t", "dismiss('text')", "Text transcript"),
2026-10-15 01:05:01 +02:00
]
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"):
2026-11-13 09:56:58 +01:00
yield Static("[bold]Share conversation[/bold]\nSave an SVG image or a Markdown transcript.")
2026-10-15 01:05:01 +02:00
yield Button("Full conversation (F)", id="full", variant="primary")
yield Button("Visible screen (V)", id="visible")
2026-11-13 09:56:58 +01:00
yield Button("Text transcript (T)", id="text")
2026-10-15 01:05:01 +02:00
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)
2026-10-06 15:46:37 +02:00
class AIChatApp(App):
CSS = """
Screen {
background: $surface;
}
2026-11-13 10:25:43 +01:00
2026-10-15 01:05:01 +02:00
#elapsed-time {
height: 1;
padding: 0 1;
text-align: right;
background: $surface-darken-1;
}
2026-10-06 15:46:37 +02:00
#chat-container {
height: 1fr;
border: solid $primary;
margin: 1;
padding: 1;
}
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
.bubble-content {
padding: 1;
width: 100%;
}
2026-11-13 10:25:43 +01:00
2026-10-06 16:17:58 +02:00
.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;
}
2026-10-06 15:46:37 +02:00
MessageBubble {
margin: 1 0;
width: 100%;
min-height: 3;
}
2026-11-13 10:25:43 +01:00
2026-11-12 17:11:56 +01:00
#conversation-stats {
height: auto;
padding: 0 1;
margin: 0 1;
border-top: solid $primary;
background: $surface-darken-1;
}
2026-10-15 01:05:01 +02:00
#turn-counter {
height: 1;
padding: 0 1;
background: $surface-darken-1;
text-style: bold;
}
2026-10-06 15:46:37 +02:00
#status-bar {
height: 3;
padding: 0 1;
background: $surface-darken-1;
}
"""
BINDINGS = [
Binding("ctrl+c", "quit", "Quit"),
2026-10-06 16:17:58 +02:00
Binding("f1", "controls_help", "Help / Zoom"),
2026-10-15 01:05:01 +02:00
Binding("s", "screenshot_options", "Screenshot", priority=True),
Binding("f2", "screenshot_options", show=False, priority=True),
2026-10-06 16:17:58 +02:00
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),
2026-10-06 15:46:37 +02:00
]
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
2026-11-12 17:11:56 +01:00
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
2026-10-15 01:05:01 +02:00
self._started_at: float | None = None
self._ended_at: float | None = None
2026-10-06 15:46:37 +02:00
self._is_running = False
2026-11-12 17:11:56 +01:00
self.client = httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=10.0))
2026-10-06 15:46:37 +02:00
def compose(self) -> ComposeResult:
yield Header(show_clock=True)
yield Container(
2026-10-15 01:05:01 +02:00
Static("Elapsed: 00:00:00", id="elapsed-time", markup=False),
2026-10-06 15:46:37 +02:00
ChatContainer(id="chat-container"),
2026-10-15 01:05:01 +02:00
Static(f"Turns completed: 0 / {self.max_turns}", id="turn-counter", markup=False),
2026-11-12 17:11:56 +01:00
Static(id="conversation-stats", markup=False),
2026-10-06 15:46:37 +02:00
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)
2026-10-15 01:05:01 +02:00
self.turn_counter = self.query_one("#turn-counter", Static)
self.elapsed_time = self.query_one("#elapsed-time", Static)
2026-10-06 16:17:58 +02:00
self.chat_container.focus()
self.chat_container.anchor()
2026-11-13 10:25:43 +01:00
self.run_worker(self.start_conversation(), exclusive=True)
2026-10-06 15:46:37 +02:00
2026-10-15 01:05:01 +02:00
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.
2026-11-13 09:56:58 +01:00
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)
2026-10-15 01:05:01 +02:00
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)
2026-10-06 16:17:58 +02:00
def action_controls_help(self) -> None:
self.push_screen(ControlsHelp())
def action_chat_scroll(self, direction: str) -> None:
2026-10-15 01:05:01 +02:00
if isinstance(self.screen, (ControlsHelp, ScreenshotOptions)):
2026-10-06 16:17:58 +02:00
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)
2026-10-06 15:46:37 +02:00
async def start_conversation(self) -> None:
self._is_running = True
2026-10-15 01:05:01 +02:00
self._started_at = monotonic()
self._ended_at = None
elapsed_timer = self.set_interval(1, self.update_elapsed_time)
2026-10-06 15:46:37 +02:00
self.update_status(f"Starting conversation... AI 1 ({self.ai1.name}) begins")
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
self.chat_container.messages = self.messages
self.chat_container.add_message(ChatMessage("user", self.initial_prompt, "System"))
2026-10-15 01:05:01 +02:00
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}")
2026-11-12 17:11:56 +01:00
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))
2026-10-06 15:46:37 +02:00
def history_for(self, sender: str) -> list[dict]:
"""Describe each turn from the responding model's perspective."""
2026-11-12 17:11:56 +01:00
history = [
2026-10-06 15:46:37 +02:00
{"role": "assistant" if message.sender == sender else "user",
"content": message.content}
2026-11-12 17:11:56 +01:00
for message in self.messages
if message.role != "system" and message.content.strip()
2026-10-06 15:46:37 +02:00
]
2026-11-12 17:11:56 +01:00
# 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")
2026-11-13 10:02:13 +01:00
bubble.set_content("")
2026-11-12 17:11:56 +01:00
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)
2026-10-06 15:46:37 +02:00
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:
2026-11-12 17:11:56 +01:00
await self.respond(current_ai, history, bubble)
2026-10-06 15:46:37 +02:00
except Exception as error:
2026-11-12 17:11:56 +01:00
error_msg = f"Error: {self.describe_error(error)}"
2026-10-06 15:46:37 +02:00
self.chat_container.add_message(ChatMessage("system", error_msg, "System"))
self.update_status(error_msg)
return
2026-11-12 17:11:56 +01:00
self.update_statistics()
2026-10-06 15:46:37 +02:00
self.current_turn += 1
2026-10-15 01:05:01 +02:00
self.turn_counter.update(
f"Turns completed: {self.current_turn} / {self.max_turns}"
)
2026-10-06 15:46:37 +02:00
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."""
2026-11-12 17:11:56 +01:00
self.begin_response_metrics()
2026-10-06 15:46:37 +02:00
bubble.start_streaming()
full_response = ""
try:
async for chunk in self.stream_ai(ai, history):
2026-11-12 17:11:56 +01:00
self._response_chars += len(chunk)
2026-10-06 15:46:37 +02:00
full_response += chunk
bubble.append_content(chunk)
2026-11-12 17:11:56 +01:00
self.update_statistics()
2026-10-06 15:46:37 +02:00
await asyncio.sleep(0)
if not full_response.strip():
raise ValueError("Empty response from API")
return full_response
finally:
bubble.end_streaming()
2026-11-12 17:11:56 +01:00
self.finish_response_metrics()
2026-10-06 15:46:37 +02:00
async def call_ai(self, ai: AIConfig, history: list[dict]) -> str:
"""Non-streaming fallback."""
messages = [{"role": "system", "content": ai.system_prompt}] + history
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
payload = {
"model": ai.model,
"messages": messages,
"temperature": 0.7,
"max_tokens": 2000,
}
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
headers = {
"Authorization": f"Bearer {ai.api_key}",
"Content-Type": "application/json",
}
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
url = f"{ai.base_url.rstrip('/')}/chat/completions"
2026-11-13 10:25:43 +01:00
2026-11-12 17:11:56 +01:00
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:
2026-10-06 15:46:37 +02:00
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}")
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
data = response.json()
2026-11-12 17:11:56 +01:00
self.record_usage(data.get("usage"))
2026-10-06 15:46:37 +02:00
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")
2026-11-12 17:11:56 +01:00
self._response_chars = len(content)
2026-10-06 15:46:37 +02:00
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
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
payload = {
"model": ai.model,
"messages": messages,
"temperature": 0.7,
"max_tokens": 2000,
"stream": True,
2026-11-12 17:11:56 +01:00
"stream_options": {"include_usage": True},
2026-10-06 15:46:37 +02:00
}
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
headers = {
"Authorization": f"Bearer {ai.api_key}",
"Content-Type": "application/json",
"Accept": "text/event-stream",
}
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
url = f"{ai.base_url.rstrip('/')}/chat/completions"
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
log.debug(f"Streaming request to {url} with model {ai.model}")
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
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')}")
2026-11-13 10:25:43 +01:00
2026-11-13 10:02:13 +01:00
done = False
2026-10-06 15:46:37 +02:00
async for line in response.aiter_lines():
if not line.startswith("data:"):
continue
data = line[5:].lstrip()
if data == "[DONE]":
2026-11-13 10:02:13 +01:00
done = True
2026-10-06 15:46:37 +02:00
break
if not data:
continue
chunk = json.loads(data)
if "error" in chunk:
raise ValueError(f"Stream error: {chunk['error']}")
2026-11-12 17:11:56 +01:00
self.record_usage(chunk.get("usage"))
2026-10-06 15:46:37 +02:00
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
2026-11-13 10:02:13 +01:00
if not done:
raise ValueError("Stream ended before [DONE]")
2026-10-06 15:46:37 +02:00
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()
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
def get_env(key: str, default: str = "") -> str:
return os.getenv(key, default)
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
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."),
)
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
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."),
)
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
prompt = get_env("INITIAL_PROMPT", "")
turns = get_env("MAX_TURNS", "20")
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
return ai1, ai2, prompt, turns
def main():
import argparse
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
# Load from .env first
ai1_env, ai2_env, prompt_env, turns_env = load_config()
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
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")
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
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")
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
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")
2026-11-13 10:25:43 +01:00
2026-10-06 15:46:37 +02:00
args = parser.parse_args()
2026-11-13 10:25:43 +01:00
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)")
2026-10-06 15:46:37 +02:00
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)")
2026-11-13 09:56:58 +01:00
2026-11-13 10:25:43 +01:00
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)
2026-10-06 15:46:37 +02:00
app.run()
if __name__ == "__main__":
2026-11-13 09:56:58 +01:00
main()