k
This commit is contained in:
1 parent
c834ce5e39
commit
1d23e56497
3 files changed
+297
-16
No files matched your search
+181
-14
@@ -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
|
||||
|
||||
Reference in new issue
Block a user