From 209446617bb0f20fa5660fc23c3a076d0f8ce022 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sat, 6 Jun 2026 10:21:01 +0100 Subject: [PATCH] refac --- cptr/utils/ai.py | 87 ++++++++++++- cptr/utils/chat_task.py | 81 +++++++++++++ cptr/utils/json_parser.py | 249 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 415 insertions(+), 2 deletions(-) create mode 100644 cptr/utils/json_parser.py diff --git a/cptr/utils/ai.py b/cptr/utils/ai.py index 41cee3c..2ab61f7 100644 --- a/cptr/utils/ai.py +++ b/cptr/utils/ai.py @@ -1,7 +1,10 @@ -"""Provider streaming functions: raw httpx SSE. +"""Provider streaming and completion functions: raw httpx. -Each function takes a ChatCompletionForm + url + key. +Each streaming function takes a ChatCompletionForm + url + key. All yield normalized events: text_delta, tool_call, usage, done. + +chat_completion() provides a simple non-streaming call for lightweight tasks +(title generation, summarization, etc.). """ from __future__ import annotations @@ -25,6 +28,86 @@ class ChatCompletionForm(BaseModel): tools: List[Dict] = [] +# ── Non-streaming completion ──────────────────────────────── + + +async def chat_completion( + provider: str, + base_url: str, + api_key: str, + model: str, + messages: list[dict], + system: str = "", + max_tokens: int = 100, + api_type: str = "chat_completions", +) -> str: + """Simple non-streaming chat completion. Returns the text content. + + Works with Anthropic, OpenAI Chat Completions, and OpenAI Responses API. + Useful for lightweight tasks like title/summary generation. + """ + async with httpx.AsyncClient(timeout=httpx.Timeout(15)) as client: + if provider == "anthropic": + body: dict = { + "model": model, + "messages": messages, + "max_tokens": max_tokens, + } + if system: + body["system"] = system + resp = await client.post( + f"{base_url}/messages", + json=body, + headers={ + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + }, + ) + elif api_type == "responses": + # OpenAI Responses API + body_r: dict = { + "model": model, + "input": messages, + "max_output_tokens": max_tokens, + } + if system: + body_r["instructions"] = system + resp = await client.post( + f"{base_url}/responses", + json=body_r, + headers={"Authorization": f"Bearer {api_key}"}, + ) + else: + # OpenAI Chat Completions (default) + all_messages = messages[:] + if system: + all_messages.insert(0, {"role": "system", "content": system}) + resp = await client.post( + f"{base_url}/chat/completions", + json={ + "model": model, + "messages": all_messages, + "max_completion_tokens": max_tokens, + }, + headers={"Authorization": f"Bearer {api_key}"}, + ) + if resp.status_code >= 400: + logger.debug("[chat_completion] %s %s → %s: %s", provider, model, resp.status_code, resp.text[:500]) + resp.raise_for_status() + data = resp.json() + + if provider == "anthropic": + return data.get("content", [{}])[0].get("text", "") + if api_type == "responses": + # Responses API: output is a list of items + for item in data.get("output", []): + if item.get("type") == "message": + for c in item.get("content", []): + if c.get("type") == "output_text": + return c.get("text", "") + return "" + return data.get("choices", [{}])[0].get("message", {}).get("content", "") + # ── Anthropic ──────────────────────────────────────────────── diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 4d92878..fd440ea 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -16,6 +16,7 @@ from cptr.models import Chat, ChatMessage, Config from cptr.socket.main import emit_to_user from cptr.utils.ai import ( ChatCompletionForm, + chat_completion, stream_anthropic, stream_openai_completions, stream_openai_responses, @@ -24,6 +25,7 @@ from cptr.utils.config import _get_jwt_secret, now_ms from cptr.utils.crypto import decrypt_key from cptr.utils.tools import TOOLS, execute_tool, get_tool_list from cptr.utils.chat_export import export_chat_to_file +from cptr.utils.json_parser import extract_json logger = logging.getLogger(__name__) @@ -271,6 +273,66 @@ def _load_system_prompt(workspace: str) -> str: +# ── Title generation ──────────────────────────────────────── + + +TITLE_PROMPT = ( + "Generate a concise title (max 8 words) for this conversation based on the user's message. " + "Respond with ONLY a JSON object: {\"title\": \"Your Title Here\"}. " + "Do not include quotes around the JSON. Do not explain." +) + + +async def generate_chat_title( + chat_id: str, + user_id: str, + connection: dict, + model: str, + user_message: str, +): + """Generate a proper title for a new chat via a lightweight LLM call. + + Uses the shared chat_completion() helper from ai.py. + On success, updates the DB and emits a socket event so the frontend + updates the tab label in real time. + """ + provider = connection["provider"] + api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret()) + base_url = connection.get("base_url") or _default_base_url(provider) + api_type = connection.get("api_type", "chat_completions") + + # Truncate very long messages to keep the prompt small + truncated = user_message[:200].strip() + if len(user_message) > 200: + truncated += "..." + + try: + text = await chat_completion( + provider=provider, + base_url=base_url, + api_key=api_key, + model=model, + messages=[{"role": "user", "content": truncated}], + system=TITLE_PROMPT, + max_tokens=50, + api_type=api_type, + ) + + # Parse the JSON title + parsed = extract_json(text) + title = (parsed.get("title", "") if isinstance(parsed, dict) else "").strip() + if not title: + return + + # Persist and notify + await Chat.update_title(chat_id, title, now_ms()) + await emit_to_user(user_id, {"chat_id": chat_id, "title": title}) + logger.info("[title] Generated title for chat %s: %s", chat_id[:8], title) + + except Exception: + logger.debug("[title] Failed to generate title for chat %s", chat_id[:8], exc_info=True) + + # ── Message history ───────────────────────────────────────── @@ -624,6 +686,25 @@ async def run_chat_task( await export_chat_to_file(chat_id) except Exception: logger.exception(f"Failed to export chat {chat_id}") + # Generate a proper title if the chat still has the auto-truncated fallback + try: + chat_obj = await Chat.get_by_id(chat_id) + if chat_obj: + all_msgs = await ChatMessage.get_all_by_chat(chat_id) + first_user = next( + (m for m in all_msgs if m.role == "user" and not (m.meta and m.meta.get("queued"))), + None, + ) + if first_user: + # The router sets title = content[:50] on creation. + # Only generate if the title still matches that fallback. + fallback = first_user.content[:50].strip() or "New Chat" + if chat_obj.title == fallback: + await generate_chat_title( + chat_id, user_id, connection, model, first_user.content + ) + except Exception: + logger.debug("[title] Error in title generation for chat %s", chat_id[:8], exc_info=True) # Process any queued follow-up messages try: await _process_queue(chat_id, user_id, workspace) diff --git a/cptr/utils/json_parser.py b/cptr/utils/json_parser.py new file mode 100644 index 0000000..3f6b3fe --- /dev/null +++ b/cptr/utils/json_parser.py @@ -0,0 +1,249 @@ +"""Generous JSON parser for LLM output. + +LLMs frequently return JSON wrapped in markdown fences, with trailing +commas, single quotes, or truncated output. This module provides a +best-effort parser that extracts and parses the last JSON object or +array from arbitrary text. + +Usage: + from cptr.utils.json_parser import extract_json + + result = extract_json('Here is your answer: {"title": "Hello World"}') + # → {"title": "Hello World"} + + result = extract_json("no json here") + # → None +""" + +from __future__ import annotations + +import json +import re +from typing import Any + + +def extract_json(text: str) -> Any | None: + """Extract and parse the last JSON object or array from text. + + Tries increasingly aggressive strategies: + 1. Strip markdown code fences, then json.loads the whole thing + 2. Find the last {...} or [...] block via brace matching + 3. Fix common LLM mistakes (trailing commas, single quotes, etc.) + 4. Attempt to close truncated JSON + + Returns the parsed Python object, or None if nothing could be parsed. + """ + if not text or not text.strip(): + return None + + text = text.strip() + + # Strip markdown code fences + text = _strip_fences(text) + + # 1. Try parsing the whole thing directly + parsed = _try_parse(text) + if parsed is not None: + return parsed + + # 2. Find the last JSON block via brace/bracket matching + block = _find_last_json_block(text) + if block: + parsed = _try_parse(block) + if parsed is not None: + return parsed + + # 3. Try fixing common issues + fixed = _fix_json(block) + parsed = _try_parse(fixed) + if parsed is not None: + return parsed + + # 4. Try closing truncated JSON + closed = _close_json(fixed) + parsed = _try_parse(closed) + if parsed is not None: + return parsed + + # 5. Last resort: try fixing the whole text + fixed = _fix_json(text) + parsed = _try_parse(fixed) + if parsed is not None: + return parsed + + closed = _close_json(fixed) + return _try_parse(closed) + + +def _strip_fences(text: str) -> str: + """Remove markdown code fences (```json ... ``` etc.).""" + text = text.strip() + # Match opening fence with optional language tag + if text.startswith("```"): + # Remove opening fence line + text = text.split("\n", 1)[-1] if "\n" in text else text[3:] + # Remove closing fence + if text.rstrip().endswith("```"): + text = text.rstrip()[:-3] + return text.strip() + + +def _try_parse(text: str) -> Any | None: + """Try json.loads, return None on failure.""" + try: + return json.loads(text) + except (json.JSONDecodeError, ValueError): + return None + + +def _find_last_json_block(text: str) -> str | None: + """Find the last top-level {...} or [...] block using brace matching. + + Respects string quoting so braces inside strings are ignored. + """ + # Find the last opening brace/bracket + for opener, closer in [('{', '}'), ('[', ']')]: + # Search backwards for the last opener + start = _find_last_opener(text, opener, closer) + if start is not None: + end = _find_matching_close(text, start, opener, closer) + if end is not None: + return text[start:end + 1] + return None + + +def _find_last_opener(text: str, opener: str, closer: str) -> int | None: + """Find the position of the last top-level opener.""" + last = None + i = len(text) - 1 + depth = 0 + in_string = False + escape = False + + while i >= 0: + ch = text[i] + if escape: + escape = False + i -= 1 + continue + # Check for escape (looking backwards is tricky, just do forward scan) + # Fall back to simpler approach: find all openers via rfind + break + + # Simpler: scan forward, track the last top-level opener + in_string = False + escape = False + depth = 0 + for i, ch in enumerate(text): + if escape: + escape = False + continue + if ch == '\\' and in_string: + escape = True + continue + if ch == '"' and not escape: + in_string = not in_string + continue + if in_string: + continue + if ch == opener: + if depth == 0: + last = i + depth += 1 + elif ch == closer: + depth -= 1 + return last + + +def _find_matching_close(text: str, start: int, opener: str, closer: str) -> int | None: + """From position `start`, find the matching closing brace/bracket.""" + depth = 0 + in_string = False + escape = False + + for i in range(start, len(text)): + ch = text[i] + if escape: + escape = False + continue + if ch == '\\' and in_string: + escape = True + continue + if ch == '"' and not escape: + in_string = not in_string + continue + if in_string: + continue + if ch == opener: + depth += 1 + elif ch == closer: + depth -= 1 + if depth == 0: + return i + # Unmatched — return the last position (for truncated JSON) + return None + + +def _fix_json(text: str) -> str: + """Fix common LLM JSON mistakes.""" + s = text.strip() + + # Replace single quotes with double quotes (but not within double-quoted strings) + # Only do this if there are no double quotes (pure single-quote JSON) + if "'" in s and '"' not in s: + s = s.replace("'", '"') + + # Remove trailing commas before } or ] + s = re.sub(r',\s*([}\]])', r'\1', s) + + # Fix unquoted keys: word: → "word": + s = re.sub(r'(?<=[{,])\s*(\w+)\s*:', r' "\1":', s) + + # Remove JavaScript-style comments + s = re.sub(r'//[^\n]*', '', s) + + return s + + +def _close_json(text: str) -> str: + """Try to close truncated JSON by adding missing brackets/braces.""" + s = text.strip() + if not s: + return s + + # Count unmatched openers + stack: list[str] = [] + in_string = False + escape = False + + for ch in s: + if escape: + escape = False + continue + if ch == '\\' and in_string: + escape = True + continue + if ch == '"': + in_string = not in_string + continue + if in_string: + continue + if ch == '{': + stack.append('}') + elif ch == '[': + stack.append(']') + elif ch in ('}', ']') and stack and stack[-1] == ch: + stack.pop() + + # Close any open string + if in_string: + s += '"' + + # Remove any trailing comma before we close + s = re.sub(r',\s*$', '', s) + + # Append missing closers in reverse order + while stack: + s += stack.pop() + + return s