diff --git a/.env.example b/.env.example index b861c14..5cc978b 100644 --- a/.env.example +++ b/.env.example @@ -3,14 +3,14 @@ AI1_NAME=Llama 3 AI1_BASE_URL=http://localhost:11434/v1 AI1_API_KEY=ollama AI1_MODEL=llama3 -AI1_SYSTEM_PROMPT=You are a curious philosopher who asks deep questions and explores ideas. +AI1_SYSTEM_PROMPT="You are the Argument Builder in a rigorous discussion with a Critical Examiner. Develop a defensible answer to the original question using clear definitions, explicit premises, and a conclusion. On each turn, address the strongest objection in the latest reply and improve one specific claim. Distinguish logical deductions, empirical evidence, philosophical positions, and speculation. Use a concrete example or counterexample when useful. Admit unsupported premises and revise claims when warranted. Keep each reply under 250 words, organized as Claim, Reasoning, and Open question. Ask one focused question that could change the conclusion. Stay on the original topic. Do not imitate the other speaker, invent evidence or quotations, use mystical or theatrical language, simulate system messages, or repeat slogans and prior conclusions. If no substantive progress remains, say what is agreed, what remains unresolved, and what new evidence or premise would be needed; do not manufacture deeper revelations." # AI 2 Configuration AI2_NAME=Mistral AI2_BASE_URL=http://localhost:11434/v1 AI2_API_KEY=ollama AI2_MODEL=mistral -AI2_SYSTEM_PROMPT=You are a practical engineer who gives concrete, grounded answers. +AI2_SYSTEM_PROMPT="You are the Critical Examiner in a rigorous discussion with an Argument Builder. Test the latest argument rather than automatically agreeing or automatically disagreeing. Identify its strongest defensible claim, then examine one consequential premise, inference, ambiguity, or counterexample. Check especially for circular reasoning, equivocation, category mistakes, and claims about a whole inferred only from its parts. Distinguish what follows logically from what is only plausible or speculative. Offer a concrete correction or alternative and acknowledge when an objection has been answered. Keep each reply under 250 words, organized as Assessment, Challenge, and Next test. Ask one precise question or propose one counterexample that advances the original topic. Do not imitate the other speaker, invent evidence or quotations, use mystical or theatrical language, simulate system messages, or repeat slogans and prior conclusions. If no substantive progress remains, state the remaining disagreement and what would resolve it; do not invent objections merely to prolong the discussion." # Conversation Settings INITIAL_PROMPT=Discuss whether creativity is uniquely human or if AI can be truly creative. diff --git a/ai_chat.py b/ai_chat.py index 24a6c0c..fc358b3 100644 --- a/ai_chat.py +++ b/ai_chat.py @@ -13,6 +13,8 @@ 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 @@ -263,6 +265,14 @@ class AIChatApp(App): 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; @@ -306,10 +316,22 @@ class AIChatApp(App): 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=120.0) + self.client = httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=10.0)) def compose(self) -> ComposeResult: yield Header(show_clock=True) @@ -317,6 +339,7 @@ class AIChatApp(App): 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" ) @@ -414,14 +437,151 @@ class AIChatApp(App): 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.""" - return [ + history = [ {"role": "assistant" if message.sender == sender else "user", "content": message.content} - for message in self.messages if message.role != "system" + 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_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: @@ -432,21 +592,13 @@ class AIChatApp(App): self.update_status(f"Streaming... ({sender}: {current_ai.name})") bubble = self.chat_container.add_message(ChatMessage("assistant", "", sender)) try: - try: - await self._try_streaming(current_ai, history, bubble) - except Exception as stream_error: - self.update_status(f"Streaming failed, trying non-streaming... ({stream_error})") - bubble.set_waiting(True) - try: - full_response = await self.call_ai(current_ai, history) - bubble.set_content(full_response) - finally: - bubble.set_waiting(False) + await self.respond(current_ai, history, bubble) except Exception as error: - error_msg = f"Error: {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}" @@ -459,18 +611,22 @@ class AIChatApp(App): 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.""" @@ -490,16 +646,25 @@ class AIChatApp(App): 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]): @@ -512,6 +677,7 @@ class AIChatApp(App): "temperature": 0.7, "max_tokens": 2000, "stream": True, + "stream_options": {"include_usage": True}, } headers = { @@ -541,6 +707,7 @@ class AIChatApp(App): 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 diff --git a/test_ai_chat.py b/test_ai_chat.py index 977a757..58a9e05 100644 --- a/test_ai_chat.py +++ b/test_ai_chat.py @@ -29,6 +29,120 @@ class ChatTests(unittest.IsolatedAsyncioTestCase): await pilot.pause(0.02) self.fail('Conversation did not finish') + async def test_average_tps_is_weighted_by_request_duration(self): + app = await self.make_app(lambda request: httpx.Response(500)) + try: + app.update_statistics = lambda: None + with patch("ai_chat.monotonic", return_value=12.0): + app._response_started = 10.0 + app.record_usage({"completion_tokens": 20}) + app.finish_response_metrics() + with patch("ai_chat.monotonic", return_value=20.0): + app._response_started = 12.0 + app.record_usage({"completion_tokens": 40}) + app.finish_response_metrics() + self.assertEqual(app._total_response_tokens, 60) + self.assertEqual(app._total_response_seconds, 10) + self.assertEqual(app._total_response_tokens / app._total_response_seconds, 6) + self.assertFalse(app._average_estimated) + finally: + await app.client.aclose() + + async def test_statistics_update_before_stream_finishes(self): + app = await self.make_app(lambda request: httpx.Response(500)) + send_chunk = asyncio.Event() + chunk_consumed = asyncio.Event() + finish = asyncio.Event() + async def stream(ai, history): + await send_chunk.wait() + yield "Immediate words" + chunk_consumed.set() + await finish.wait() + app.stream_ai = stream + async with app.run_test() as pilot: + send_chunk.set() + await asyncio.wait_for(chunk_consumed.wait(), 2) + # No timer tick or completed response is needed to update counts. + rendered = io.StringIO() + Console(file=rendered, width=100, color_system=None).print( + app.query_one("#conversation-stats").content) + self.assertIn("~7", rendered.getvalue()) + self.assertRegex(rendered.getvalue(), r"~7\s+4\s+") + self.assertTrue(app._is_running) + finish.set() + await self.wait_finished(app, pilot) + + async def test_statistics_stream_usage_and_transcript(self): + def handler(request): + self.assertTrue(json.loads(request.content)["stream_options"]["include_usage"]) + return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"Hello world"}}]}\n\ndata: {"choices":[],"usage":{"prompt_tokens":20,"completion_tokens":3}}\n\ndata: [DONE]\n\n') + app = await self.make_app(handler) + async with app.run_test(size=(100, 30)) as pilot: + await self.wait_finished(app, pilot) + stats = app.query_one("#conversation-stats") + rendered = io.StringIO() + Console(file=rendered, width=100, color_system=None).print(stats.content) + self.assertIn("WORDS", rendered.getvalue()) + self.assertEqual(sum(len(m.content.split()) for m in app.messages), 4) + self.assertIn("1 replies", rendered.getvalue()) + self.assertIn("20 input / 3 output", rendered.getvalue()) + self.assertEqual(app.api_input_tokens, 20) + self.assertEqual(app.api_output_tokens, 3) + self.assertTrue(app._last_speed_exact) + self.assertGreater(app._last_speed, 0) + self.assertGreater(stats.size.height, 0) + self.assertLessEqual(stats.region.bottom, app.size.height) + + async def test_statistics_fallback_does_not_count_partial_text(self): + def handler(request): + if json.loads(request.content).get("stream"): + return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"discard this text"}}]}\n\ndata: {"error":"broken"}\n\n') + return httpx.Response(200, json={"choices": [{"message": {"content": "Final answer"}}]}) + app = await self.make_app(handler) + async with app.run_test() as pilot: + await self.wait_finished(app, pilot) + rendered = io.StringIO() + Console(file=rendered, width=100, color_system=None).print(app.query_one("#conversation-stats").content) + stats = rendered.getvalue() + self.assertEqual(sum(len(m.content.split()) for m in app.messages), 4) + self.assertIn("API usage: not reported", stats) + self.assertFalse(app._last_speed_exact) + self.assertEqual(app.api_output_tokens, 0) + + async def test_long_history_is_bounded_without_losing_transcript(self): + app = await self.make_app(lambda request: httpx.Response(500)) + try: + app.messages = [ChatMessage("user", "Original topic", "System")] + app.messages.extend(ChatMessage("assistant", str(i) + "x" * 3000, + "AI 1" if i % 2 == 0 else "AI 2") + for i in range(60)) + history = app.history_for("AI 1") + self.assertLessEqual(sum(len(m["content"]) + 64 for m in history), 12000) + self.assertEqual(history[0]["content"], "Original topic") + self.assertEqual(history[-1]["content"], app.messages[-1].content) + self.assertEqual(len(app.messages), 61) + finally: + await app.client.aclose() + + async def test_empty_response_recovers_on_retry(self): + calls = [] + def handler(request): + calls.append(json.loads(request.content)) + if len(calls) <= 2: + if calls[-1].get("stream"): + return httpx.Response(200, text="data: [DONE]\n\n") + return httpx.Response(200, json={"choices": [{"message": {"content": ""}}]}) + return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"recovered"}}]}\n\ndata: [DONE]\n\n') + app = await self.make_app(handler) + async with app.run_test() as pilot: + await self.wait_finished(app, pilot) + self.assertEqual(app.current_turn, 1) + self.assertEqual(app.messages[-1].content, "recovered") + self.assertEqual(len(app.query(MessageBubble)), 2) + + def test_timeout_error_has_a_name(self): + self.assertIn("ReadTimeout", AIChatApp.describe_error(httpx.ReadTimeout(""))) + async def test_stream_usage_and_speaker_roles(self): requests = [] def handler(request):