mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
refac
This commit is contained in:
1 parent
0bbf9a44c9
commit
1b7bea00a4
17 files changed
+816
-238
No files matched your search
+134
-16
@@ -3,8 +3,9 @@
|
||||
Each streaming function takes a ChatCompletionForm + url + key.
|
||||
All yield normalized events: text_delta, output, tool_call, usage, done.
|
||||
|
||||
chat_completion() provides a simple non-streaming call for lightweight tasks
|
||||
(title generation, summarization, etc.).
|
||||
chat_completion() is the low-level non-streaming provider call.
|
||||
generate_text()/generate_json() add model-id resolution and inheritance for
|
||||
small internal calls.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -223,6 +224,109 @@ async def chat_completion(
|
||||
return data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||
|
||||
|
||||
async def generate_text(
|
||||
request=None,
|
||||
*,
|
||||
model_id: str | None,
|
||||
messages: list[dict],
|
||||
system: str = "",
|
||||
max_tokens: int = 100,
|
||||
active_connection: dict | None = None,
|
||||
active_model: str = "",
|
||||
request_params: dict | None = None,
|
||||
timeout_seconds: float = 20,
|
||||
) -> str | None:
|
||||
"""Generate text; model_id None inherits active/default."""
|
||||
from cptr.models import Config
|
||||
from cptr.utils.config import _get_jwt_secret
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.model_targets import first_api_model_target, resolve_api_model_target
|
||||
|
||||
app_state = getattr(getattr(request, "app", None), "state", None)
|
||||
connection = active_connection
|
||||
runtime_model = active_model
|
||||
selected = model_id.strip() if isinstance(model_id, str) else ""
|
||||
if selected:
|
||||
try:
|
||||
target = await resolve_api_model_target(selected, app_state)
|
||||
connection = target.connection
|
||||
runtime_model = target.runtime_model
|
||||
except Exception:
|
||||
logger.debug("[generate_text] model not available: %s", selected, exc_info=True)
|
||||
|
||||
if not connection or not runtime_model:
|
||||
default_model = await Config.get("chat.default_model")
|
||||
target = None
|
||||
if isinstance(default_model, str) and default_model.strip():
|
||||
try:
|
||||
target = await resolve_api_model_target(default_model.strip(), app_state)
|
||||
except Exception:
|
||||
logger.debug("[generate_text] default model not available", exc_info=True)
|
||||
if target is None:
|
||||
try:
|
||||
target = await first_api_model_target(app_state)
|
||||
except Exception:
|
||||
logger.debug("[generate_text] no fallback API model available", exc_info=True)
|
||||
return None
|
||||
connection = target.connection
|
||||
runtime_model = target.runtime_model
|
||||
|
||||
provider = connection["provider"]
|
||||
base_url = connection.get("base_url") or {
|
||||
"anthropic": "https://api.anthropic.com/v1",
|
||||
"openai": "https://api.openai.com/v1",
|
||||
}.get(provider, "https://api.openai.com/v1")
|
||||
try:
|
||||
return await asyncio.wait_for(
|
||||
chat_completion(
|
||||
provider=provider,
|
||||
base_url=base_url,
|
||||
api_key=decrypt_key(connection.get("api_key", ""), _get_jwt_secret()),
|
||||
model=runtime_model,
|
||||
messages=messages,
|
||||
system=system,
|
||||
max_tokens=max_tokens,
|
||||
api_type=connection.get("api_type", "chat_completions"),
|
||||
request_params=request_params,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("[generate_text] generation failed", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
async def generate_json(
|
||||
request=None,
|
||||
*,
|
||||
model_id: str | None,
|
||||
messages: list[dict],
|
||||
system: str = "",
|
||||
max_tokens: int = 100,
|
||||
active_connection: dict | None = None,
|
||||
active_model: str = "",
|
||||
request_params: dict | None = None,
|
||||
timeout_seconds: float = 20,
|
||||
) -> dict | None:
|
||||
from cptr.utils.json_parser import extract_json
|
||||
|
||||
text = await generate_text(
|
||||
request,
|
||||
model_id=model_id,
|
||||
messages=messages,
|
||||
system=system,
|
||||
max_tokens=max_tokens,
|
||||
active_connection=active_connection,
|
||||
active_model=active_model,
|
||||
request_params=request_params,
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
if not text:
|
||||
return None
|
||||
parsed = extract_json(text)
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
|
||||
|
||||
# ── Anthropic ────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -409,7 +513,11 @@ async def stream_anthropic(
|
||||
yield {"type": "done"}
|
||||
return
|
||||
except _STREAM_RETRY_ERRORS as exc:
|
||||
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1 or not _is_retryable_stream_error(exc):
|
||||
if (
|
||||
emitted
|
||||
or attempt == _STREAM_RETRY_ATTEMPTS - 1
|
||||
or not _is_retryable_stream_error(exc)
|
||||
):
|
||||
raise
|
||||
logger.warning(
|
||||
"[stream] anthropic transient stream failure before first event; retrying (%s/%s)",
|
||||
@@ -482,8 +590,7 @@ def _to_openai_messages(
|
||||
new_m.pop("reasoning_items", None)
|
||||
if new_m.get("tool_calls"):
|
||||
new_m["tool_calls"] = [
|
||||
{k: v for k, v in tc.items() if k != "fc_id"}
|
||||
for tc in new_m["tool_calls"]
|
||||
{k: v for k, v in tc.items() if k != "fc_id"} for tc in new_m["tool_calls"]
|
||||
]
|
||||
new_m["content"] = formatted_content
|
||||
ri = m.get("reasoning_items")
|
||||
@@ -689,7 +796,11 @@ async def stream_openai_completions(
|
||||
yield {"type": "done"}
|
||||
return
|
||||
except _STREAM_RETRY_ERRORS as exc:
|
||||
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1 or not _is_retryable_stream_error(exc):
|
||||
if (
|
||||
emitted
|
||||
or attempt == _STREAM_RETRY_ATTEMPTS - 1
|
||||
or not _is_retryable_stream_error(exc)
|
||||
):
|
||||
raise
|
||||
logger.warning(
|
||||
"[stream] openai completions transient stream failure before first event; retrying (%s/%s)",
|
||||
@@ -942,7 +1053,9 @@ async def stream_openai_responses(
|
||||
elif etype == "response.reasoning_summary_text.delta":
|
||||
item = get_reasoning_item(event)
|
||||
delta = event.get("delta", "")
|
||||
summary = item.setdefault("summary", [{"type": "summary_text", "text": ""}])
|
||||
summary = item.setdefault(
|
||||
"summary", [{"type": "summary_text", "text": ""}]
|
||||
)
|
||||
if not summary:
|
||||
summary.append({"type": "summary_text", "text": ""})
|
||||
if isinstance(summary[0], dict):
|
||||
@@ -974,10 +1087,9 @@ async def stream_openai_responses(
|
||||
}
|
||||
elif item["type"] == "reasoning":
|
||||
# Reasoning items must be round-tripped for reasoning models
|
||||
if (
|
||||
active_reasoning_item is not None
|
||||
and active_reasoning_item.get("id") == item.get("id")
|
||||
):
|
||||
if active_reasoning_item is not None and active_reasoning_item.get(
|
||||
"id"
|
||||
) == item.get("id"):
|
||||
active_reasoning_item = None
|
||||
emitted = True
|
||||
yield {
|
||||
@@ -991,13 +1103,15 @@ async def stream_openai_responses(
|
||||
raise RuntimeError(f"Responses API error: {msg}")
|
||||
|
||||
elif etype == "response.completed":
|
||||
if (
|
||||
active_reasoning_item is not None
|
||||
and _reasoning_items_to_content([active_reasoning_item])
|
||||
if active_reasoning_item is not None and _reasoning_items_to_content(
|
||||
[active_reasoning_item]
|
||||
):
|
||||
active_reasoning_item["status"] = "completed"
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(active_reasoning_item)}
|
||||
yield {
|
||||
"type": "output",
|
||||
"item": copy.deepcopy(active_reasoning_item),
|
||||
}
|
||||
usage = event.get("response", {}).get("usage", {})
|
||||
if usage:
|
||||
emitted = True
|
||||
@@ -1006,7 +1120,11 @@ async def stream_openai_responses(
|
||||
yield {"type": "done"}
|
||||
return
|
||||
except _STREAM_RETRY_ERRORS as exc:
|
||||
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1 or not _is_retryable_stream_error(exc):
|
||||
if (
|
||||
emitted
|
||||
or attempt == _STREAM_RETRY_ATTEMPTS - 1
|
||||
or not _is_retryable_stream_error(exc)
|
||||
):
|
||||
raise
|
||||
logger.warning(
|
||||
"[stream] openai responses transient stream failure before first event; retrying (%s/%s)",
|
||||
|
||||
+82
-23
@@ -42,7 +42,7 @@ from cptr.models import (
|
||||
from cptr.socket.main import emit_to_user
|
||||
from cptr.utils.ai import (
|
||||
ChatCompletionForm,
|
||||
chat_completion,
|
||||
generate_json,
|
||||
stream_anthropic,
|
||||
stream_openai_completions,
|
||||
stream_openai_responses,
|
||||
@@ -59,7 +59,6 @@ from cptr.utils.tools import (
|
||||
_fn_to_schema,
|
||||
)
|
||||
from cptr.utils.chat_export import export_chat_to_file
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.utils.prompt_templates import load_system_prompt as _load_system_prompt
|
||||
from cptr.utils.agents.events import (
|
||||
AgentDone,
|
||||
@@ -725,6 +724,54 @@ TITLE_PROMPT = (
|
||||
"Do not include quotes around the JSON. Do not explain."
|
||||
)
|
||||
|
||||
TOOL_APPROVAL_REVIEW_PROMPT = (
|
||||
"Decide whether Computer may run the proposed tool call without asking the user. "
|
||||
'Return ONLY JSON: {"decision":"approve" or "deny","reason":"short reason"}. '
|
||||
"Approve only when the call is a reasonable next step for the user's request and the "
|
||||
"arguments do not appear destructive, surprising, credential-seeking, or unrelated. "
|
||||
"Deny when uncertain."
|
||||
)
|
||||
|
||||
|
||||
async def review_tool_approval(
|
||||
*,
|
||||
messages: list[dict],
|
||||
assistant_text: str,
|
||||
connection: dict,
|
||||
model: str,
|
||||
tool_name: str,
|
||||
arguments: dict,
|
||||
) -> bool:
|
||||
"""Return True when Auto mode can run a pending tool without prompting."""
|
||||
latest_user = ""
|
||||
for message in reversed(messages):
|
||||
if message.get("role") == "user":
|
||||
latest_user = _plain_message_text(message.get("content"))
|
||||
break
|
||||
args_text = json.dumps(arguments, ensure_ascii=False, default=str)
|
||||
if len(args_text) > 4000:
|
||||
args_text = args_text[:3500] + "\n...(truncated)"
|
||||
parsed = await generate_json(
|
||||
model_id=await Config.get("tool_approval.review.model"),
|
||||
active_connection=connection,
|
||||
active_model=model,
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
f"Latest user request:\n{latest_user[:2000]}\n\n"
|
||||
f"Assistant text before tool call:\n{assistant_text[-2000:]}\n\n"
|
||||
f"Tool: {tool_name}\nArguments:\n{args_text}"
|
||||
),
|
||||
}
|
||||
],
|
||||
system=TOOL_APPROVAL_REVIEW_PROMPT,
|
||||
max_tokens=150,
|
||||
request_params={"temperature": 0},
|
||||
timeout_seconds=20,
|
||||
)
|
||||
return str((parsed or {}).get("decision") or "").strip().lower() == "approve"
|
||||
|
||||
|
||||
async def generate_chat_title(
|
||||
chat_id: str,
|
||||
@@ -735,14 +782,13 @@ async def generate_chat_title(
|
||||
):
|
||||
"""Generate a proper title for a new chat via a lightweight LLM call.
|
||||
|
||||
Uses the shared chat_completion() helper from ai.py.
|
||||
Uses the configured title model, inheriting the active/default model when unset.
|
||||
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")
|
||||
title_generation_enabled = await Config.get("chat.title_generation.enabled")
|
||||
if title_generation_enabled is False or title_generation_enabled == "false":
|
||||
return
|
||||
|
||||
# Truncate very long messages to keep the prompt small
|
||||
truncated = user_message[:200].strip()
|
||||
@@ -750,19 +796,14 @@ async def generate_chat_title(
|
||||
truncated += "..."
|
||||
|
||||
try:
|
||||
text = await chat_completion(
|
||||
provider=provider,
|
||||
base_url=base_url,
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
parsed = await generate_json(
|
||||
model_id=await Config.get("chat.title_generation.model"),
|
||||
active_connection=connection,
|
||||
active_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
|
||||
@@ -1924,9 +1965,26 @@ async def run_chat_task(
|
||||
|
||||
name = item.get("name", "")
|
||||
tool = ALL_TOOLS.get(name)
|
||||
needs_approval = not (
|
||||
approval_mode == "full" or (approval_mode == "auto" and tool and tool["auto"])
|
||||
should_auto = approval_mode == "full" or (
|
||||
approval_mode == "auto" and tool and tool["auto"]
|
||||
)
|
||||
if (
|
||||
not should_auto
|
||||
and approval_mode == "auto"
|
||||
and not item.get("approved")
|
||||
and tool
|
||||
and await review_tool_approval(
|
||||
messages=messages,
|
||||
assistant_text=content,
|
||||
connection=connection,
|
||||
model=model,
|
||||
tool_name=name,
|
||||
arguments=item.get("arguments") or {},
|
||||
)
|
||||
):
|
||||
item["approved"] = True
|
||||
should_auto = True
|
||||
needs_approval = not should_auto
|
||||
if needs_approval and not item.get("approved"):
|
||||
item["status"] = "pending"
|
||||
await _save_message(
|
||||
@@ -2056,11 +2114,8 @@ async def run_chat_task(
|
||||
summary = await summarize_messages(
|
||||
drop_zone,
|
||||
loaded_summary,
|
||||
provider,
|
||||
base_url,
|
||||
api_key,
|
||||
connection,
|
||||
model,
|
||||
api_type=api_type,
|
||||
)
|
||||
|
||||
checkpoint_message_id = _summary_checkpoint_message_id(
|
||||
@@ -2747,7 +2802,11 @@ async def run_chat_task(
|
||||
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
|
||||
chat_id,
|
||||
user_id,
|
||||
connection,
|
||||
model,
|
||||
first_user.content,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug(
|
||||
|
||||
+142
-53
@@ -24,6 +24,7 @@ DEFAULT_MEMORY_SETTINGS: dict[str, Any] = {
|
||||
"enabled": True,
|
||||
"tool_enabled": True,
|
||||
"background_review_enabled": True,
|
||||
"background_review.model": None,
|
||||
"review_interval_turns": 10,
|
||||
"user_char_limit": 2000,
|
||||
"workspace_char_limit": 3000,
|
||||
@@ -279,15 +280,19 @@ def _split_markdown_sections(text: str, fallback_heading: str = "") -> list[dict
|
||||
headings.append((index, len(match.group(1)), match.group(2).strip()))
|
||||
if not headings:
|
||||
content = "\n".join(lines).strip()
|
||||
return [
|
||||
{
|
||||
"heading": fallback_heading,
|
||||
"memory_id": _extract_memory_id(content),
|
||||
"content": content,
|
||||
"start": 0,
|
||||
"end": len(lines),
|
||||
}
|
||||
] if content else []
|
||||
return (
|
||||
[
|
||||
{
|
||||
"heading": fallback_heading,
|
||||
"memory_id": _extract_memory_id(content),
|
||||
"content": content,
|
||||
"start": 0,
|
||||
"end": len(lines),
|
||||
}
|
||||
]
|
||||
if content
|
||||
else []
|
||||
)
|
||||
|
||||
sections: list[dict[str, Any]] = []
|
||||
for pos, (start, level, heading) in enumerate(headings):
|
||||
@@ -720,7 +725,9 @@ def _operation_uses_markdown(operation: dict[str, Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _find_section_bounds(text: str, *, memory_id: str = "", heading: str = "") -> tuple[int, int] | None:
|
||||
def _find_section_bounds(
|
||||
text: str, *, memory_id: str = "", heading: str = ""
|
||||
) -> tuple[int, int] | None:
|
||||
sections = _split_markdown_sections(text)
|
||||
for section in sections:
|
||||
if memory_id and section.get("memory_id") == memory_id:
|
||||
@@ -751,7 +758,11 @@ def _write_if_unchanged(
|
||||
current_hash = _file_hash(path)
|
||||
if current_hash != original_hash:
|
||||
backup = _backup_to_trash(path, "conflict", root)
|
||||
return False, f"refusing to overwrite changed memory file; backup saved to {backup}", str(backup)
|
||||
return (
|
||||
False,
|
||||
f"refusing to overwrite changed memory file; backup saved to {backup}",
|
||||
str(backup),
|
||||
)
|
||||
_atomic_write_text(path, content)
|
||||
return True, "written", ""
|
||||
|
||||
@@ -785,7 +796,9 @@ def _add_related_link(section_text: str, link: str) -> str:
|
||||
return section_text.rstrip() + f"\n\nRelated: {rendered}\n"
|
||||
|
||||
|
||||
def apply_markdown_memory_batch(root: MemoryRoot, operations: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
def apply_markdown_memory_batch(
|
||||
root: MemoryRoot, operations: list[dict[str, Any]]
|
||||
) -> dict[str, Any]:
|
||||
if not operations:
|
||||
return {"success": False, "error": "operations list is empty"}
|
||||
|
||||
@@ -798,7 +811,10 @@ def apply_markdown_memory_batch(root: MemoryRoot, operations: list[dict[str, Any
|
||||
|
||||
def load(path: Path) -> str:
|
||||
if path not in touched:
|
||||
touched[path] = (_file_hash(path), path.read_text(errors="replace") if path.exists() else "")
|
||||
touched[path] = (
|
||||
_file_hash(path),
|
||||
path.read_text(errors="replace") if path.exists() else "",
|
||||
)
|
||||
return touched[path][1]
|
||||
|
||||
def store(path: Path, content: str) -> None:
|
||||
@@ -849,7 +865,9 @@ def apply_markdown_memory_batch(root: MemoryRoot, operations: list[dict[str, Any
|
||||
start, end = bounds
|
||||
heading = str(operation.get("heading") or operation.get("title") or "Memory")
|
||||
marker = str(operation.get("memory_id") or "").strip()
|
||||
replacement = _append_memory_section("", {**operation, "heading": heading, "memory_id": marker}, heading)
|
||||
replacement = _append_memory_section(
|
||||
"", {**operation, "heading": heading, "memory_id": marker}, heading
|
||||
)
|
||||
store(target, _replace_lines(existing, start, end, replacement))
|
||||
elif old_text and old_text in existing:
|
||||
store(target, existing.replace(old_text, content, 1))
|
||||
@@ -877,7 +895,9 @@ def apply_markdown_memory_batch(root: MemoryRoot, operations: list[dict[str, Any
|
||||
messages.append(f"removed memory from {_relative_to_root(target, root.root)}")
|
||||
|
||||
elif action == "link":
|
||||
link = str(operation.get("link") or operation.get("target") or operation.get("content") or "").strip()
|
||||
link = str(
|
||||
operation.get("link") or operation.get("target") or operation.get("content") or ""
|
||||
).strip()
|
||||
if not link:
|
||||
return {"success": False, "error": f"{operation_name}: link is required"}
|
||||
target = read_target(operation)
|
||||
@@ -891,7 +911,10 @@ def apply_markdown_memory_batch(root: MemoryRoot, operations: list[dict[str, Any
|
||||
start, end = bounds
|
||||
lines = existing.splitlines()
|
||||
section_text = "\n".join(lines[start:end])
|
||||
store(target, _replace_lines(existing, start, end, _add_related_link(section_text, link)))
|
||||
store(
|
||||
target,
|
||||
_replace_lines(existing, start, end, _add_related_link(section_text, link)),
|
||||
)
|
||||
else:
|
||||
store(target, _add_related_link(existing, link))
|
||||
messages.append(f"linked memory in {_relative_to_root(target, root.root)}")
|
||||
@@ -905,14 +928,23 @@ def apply_markdown_memory_batch(root: MemoryRoot, operations: list[dict[str, Any
|
||||
return {"success": False, "error": f"{operation_name}: destination already exists"}
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(source), str(destination))
|
||||
messages.append(f"moved {_relative_to_root(source, root.root)} to {_relative_to_root(destination, root.root)}")
|
||||
messages.append(
|
||||
f"moved {_relative_to_root(source, root.root)} to {_relative_to_root(destination, root.root)}"
|
||||
)
|
||||
|
||||
elif action == "split":
|
||||
target = read_target(operation)
|
||||
existing = load(target)
|
||||
sections = [section for section in _split_markdown_sections(existing, target.stem) if section.get("content")]
|
||||
sections = [
|
||||
section
|
||||
for section in _split_markdown_sections(existing, target.stem)
|
||||
if section.get("content")
|
||||
]
|
||||
if len(sections) < 2:
|
||||
return {"success": False, "error": f"{operation_name}: file does not have multiple sections"}
|
||||
return {
|
||||
"success": False,
|
||||
"error": f"{operation_name}: file does not have multiple sections",
|
||||
}
|
||||
folder = target.with_suffix("")
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
_backup_to_trash(target, "split", root.root)
|
||||
@@ -925,19 +957,28 @@ def apply_markdown_memory_batch(root: MemoryRoot, operations: list[dict[str, Any
|
||||
_atomic_write_text(child, child_text)
|
||||
map_lines.append(f"- [[{heading}]]")
|
||||
store(target, "\n".join(map_lines).rstrip() + "\n")
|
||||
messages.append(f"split {_relative_to_root(target, root.root)} into {len(sections)} files")
|
||||
messages.append(
|
||||
f"split {_relative_to_root(target, root.root)} into {len(sections)} files"
|
||||
)
|
||||
|
||||
elif action == "merge":
|
||||
source = _safe_relative_path(root.root, str(operation.get("source_path") or operation.get("path") or ""))
|
||||
source = _safe_relative_path(
|
||||
root.root, str(operation.get("source_path") or operation.get("path") or "")
|
||||
)
|
||||
target = _safe_relative_path(root.root, str(operation.get("target_path") or ""))
|
||||
if not source.exists() or not target.exists():
|
||||
return {"success": False, "error": f"{operation_name}: source and target must exist"}
|
||||
return {
|
||||
"success": False,
|
||||
"error": f"{operation_name}: source and target must exist",
|
||||
}
|
||||
source_text = source.read_text(errors="replace")
|
||||
target_text = load(target)
|
||||
_backup_to_trash(source, "merge", root.root)
|
||||
store(target, target_text.rstrip() + "\n\n" + source_text.strip() + "\n")
|
||||
source.unlink()
|
||||
messages.append(f"merged {_relative_to_root(source, root.root)} into {_relative_to_root(target, root.root)}")
|
||||
messages.append(
|
||||
f"merged {_relative_to_root(source, root.root)} into {_relative_to_root(target, root.root)}"
|
||||
)
|
||||
|
||||
else:
|
||||
return {
|
||||
@@ -950,7 +991,11 @@ def apply_markdown_memory_batch(root: MemoryRoot, operations: list[dict[str, Any
|
||||
if not success:
|
||||
return {"success": False, "error": message, "backup": backup, "path": str(path)}
|
||||
|
||||
return {"success": True, "message": "; ".join(messages) or "No changes.", "path": str(root.root)}
|
||||
return {
|
||||
"success": True,
|
||||
"message": "; ".join(messages) or "No changes.",
|
||||
"path": str(root.root),
|
||||
}
|
||||
|
||||
|
||||
async def get_memory_settings() -> dict[str, Any]:
|
||||
@@ -999,7 +1044,12 @@ def apply_memory_batch(
|
||||
next_entries = list(current_entries)
|
||||
for index, operation in enumerate(operations):
|
||||
if not isinstance(operation, dict):
|
||||
return False, f"Operation {index + 1}: must be an object", current_entries, current_usage
|
||||
return (
|
||||
False,
|
||||
f"Operation {index + 1}: must be an object",
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
action = operation.get("action")
|
||||
content = normalize_memory_text(str(operation.get("content") or ""))
|
||||
old_text = normalize_memory_text(str(operation.get("old_text") or ""))
|
||||
@@ -1008,21 +1058,46 @@ def apply_memory_batch(
|
||||
if action in {"add", "replace"}:
|
||||
validation_error = memory_text_error(content)
|
||||
if validation_error:
|
||||
return False, f"{operation_name}: {validation_error}", current_entries, current_usage
|
||||
return (
|
||||
False,
|
||||
f"{operation_name}: {validation_error}",
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
|
||||
if action == "add":
|
||||
if not content:
|
||||
return False, f"{operation_name}: content is required", current_entries, current_usage
|
||||
return (
|
||||
False,
|
||||
f"{operation_name}: content is required",
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
if content not in next_entries:
|
||||
next_entries.append(content)
|
||||
elif action == "replace":
|
||||
if not old_text:
|
||||
return False, f"{operation_name}: old_text is required", current_entries, current_usage
|
||||
return (
|
||||
False,
|
||||
f"{operation_name}: old_text is required",
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
if not content:
|
||||
return False, f"{operation_name}: content is required", current_entries, current_usage
|
||||
return (
|
||||
False,
|
||||
f"{operation_name}: content is required",
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
matches = [i for i, entry in enumerate(next_entries) if old_text in entry]
|
||||
if not matches:
|
||||
return False, f"{operation_name}: no entry matched '{old_text}'", current_entries, current_usage
|
||||
return (
|
||||
False,
|
||||
f"{operation_name}: no entry matched '{old_text}'",
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
if len({next_entries[i] for i in matches}) > 1:
|
||||
return (
|
||||
False,
|
||||
@@ -1033,10 +1108,20 @@ def apply_memory_batch(
|
||||
next_entries[matches[0]] = content
|
||||
elif action == "remove":
|
||||
if not old_text:
|
||||
return False, f"{operation_name}: old_text is required", current_entries, current_usage
|
||||
return (
|
||||
False,
|
||||
f"{operation_name}: old_text is required",
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
matches = [i for i, entry in enumerate(next_entries) if old_text in entry]
|
||||
if not matches:
|
||||
return False, f"{operation_name}: no entry matched '{old_text}'", current_entries, current_usage
|
||||
return (
|
||||
False,
|
||||
f"{operation_name}: no entry matched '{old_text}'",
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
if len({next_entries[i] for i in matches}) > 1:
|
||||
return (
|
||||
False,
|
||||
@@ -1061,7 +1146,12 @@ def apply_memory_batch(
|
||||
current_entries,
|
||||
current_usage,
|
||||
)
|
||||
return True, f"Applied {len(operations)} operation(s).", next_entries, f"{next_usage_count}/{character_limit}"
|
||||
return (
|
||||
True,
|
||||
f"Applied {len(operations)} operation(s).",
|
||||
next_entries,
|
||||
f"{next_usage_count}/{character_limit}",
|
||||
)
|
||||
|
||||
|
||||
async def write_memory(
|
||||
@@ -1138,7 +1228,9 @@ async def read_memory_state(user_id: str, workspace: str) -> dict[str, Any]:
|
||||
if workspace:
|
||||
workspace_memory = await resolve_memory_file(user_id, workspace, "workspace")
|
||||
workspace_entries = await asyncio.to_thread(read_memory_entries, workspace_memory.path)
|
||||
workspace_usage = f"{measure_memory_entries(workspace_entries)}/{workspace_memory.character_limit}"
|
||||
workspace_usage = (
|
||||
f"{measure_memory_entries(workspace_entries)}/{workspace_memory.character_limit}"
|
||||
)
|
||||
workspace_path_value = str(workspace_memory.path)
|
||||
return {
|
||||
"settings": settings,
|
||||
@@ -1175,7 +1267,9 @@ async def recall_memory_context(
|
||||
snippets_by_scope: dict[str, list[MemorySnippet]] = {"user": [], "workspace": []}
|
||||
|
||||
for root in roots:
|
||||
baseline_text = root.baseline_path.read_text(errors="replace") if root.baseline_path.is_file() else ""
|
||||
baseline_text = (
|
||||
root.baseline_path.read_text(errors="replace") if root.baseline_path.is_file() else ""
|
||||
)
|
||||
contextual_query = query
|
||||
if baseline_text:
|
||||
baseline_links = _extract_baseline_links(baseline_text)
|
||||
@@ -1192,7 +1286,8 @@ async def recall_memory_context(
|
||||
snippets_by_scope[root.scope].extend(
|
||||
snippet
|
||||
for snippet in snippets
|
||||
if snippet.path != root.baseline_path.name and not PROMPT_THREAT_RE.search(snippet.snippet)
|
||||
if snippet.path != root.baseline_path.name
|
||||
and not PROMPT_THREAT_RE.search(snippet.snippet)
|
||||
)
|
||||
return MemoryContext(
|
||||
user=snippets_by_scope["user"],
|
||||
@@ -1317,7 +1412,9 @@ async def list_memory_files_state(
|
||||
"path": rel,
|
||||
"size": stat.st_size,
|
||||
"modified_at": stat.st_mtime,
|
||||
"headings": [section["heading"] for section in sections if section.get("heading")][:12],
|
||||
"headings": [
|
||||
section["heading"] for section in sections if section.get("heading")
|
||||
][:12],
|
||||
"baseline": path == root.baseline_path,
|
||||
"trash": _is_trash_path(_relative_to_root(path, root.root)),
|
||||
}
|
||||
@@ -1423,7 +1520,9 @@ def summarize_recent_conversation(messages: list[dict[str, Any]], assistant_repl
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def build_memory_review_prompt(memory_state: dict[str, Any], workspace: str, transcript: str) -> str:
|
||||
def build_memory_review_prompt(
|
||||
memory_state: dict[str, Any], workspace: str, transcript: str
|
||||
) -> str:
|
||||
return (
|
||||
"Review the completed conversation and decide whether cptr should remember "
|
||||
"stable facts. Return ONLY JSON with this shape:\n"
|
||||
@@ -1494,29 +1593,19 @@ async def run_memory_review(
|
||||
model: str,
|
||||
) -> None:
|
||||
try:
|
||||
from cptr.utils.ai import chat_completion
|
||||
from cptr.utils.chat_task import _default_base_url
|
||||
from cptr.utils.config import _get_jwt_secret
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.utils.ai import generate_json
|
||||
|
||||
memory_state = await read_memory_state(user_id, workspace)
|
||||
transcript = summarize_recent_conversation(conversation_messages, assistant_reply)
|
||||
prompt = build_memory_review_prompt(memory_state, workspace, transcript)
|
||||
provider = model_connection["provider"]
|
||||
api_key = decrypt_key(model_connection.get("api_key", ""), _get_jwt_secret())
|
||||
base_url = model_connection.get("base_url") or _default_base_url(provider)
|
||||
text = await chat_completion(
|
||||
provider=provider,
|
||||
base_url=base_url,
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
parsed = await generate_json(
|
||||
model_id=await Config.get("memory.background_review.model"),
|
||||
active_connection=model_connection,
|
||||
active_model=model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
system="You are cptr's private memory reviewer. Return only valid JSON.",
|
||||
max_tokens=700,
|
||||
api_type=model_connection.get("api_type", "chat_completions"),
|
||||
)
|
||||
parsed = extract_json(text)
|
||||
if not isinstance(parsed, dict):
|
||||
return
|
||||
for scope in ("user", "workspace"):
|
||||
|
||||
+29
-23
@@ -192,11 +192,15 @@ def write_usage(workspace: str, source: str, data: dict[str, Any]) -> None:
|
||||
path = _usage_path(workspace, source)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_name(f".{path.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
tmp.write_text(
|
||||
json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
||||
)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def bump_skill_view(workspace: str, name: str, source: str = "workspace", *, used: bool = True) -> None:
|
||||
def bump_skill_view(
|
||||
workspace: str, name: str, source: str = "workspace", *, used: bool = True
|
||||
) -> None:
|
||||
try:
|
||||
data = read_usage(workspace, source)
|
||||
skills = data.setdefault("skills", {})
|
||||
@@ -595,7 +599,11 @@ def update_managed_skill(workspace: str, name: str, content: str) -> dict:
|
||||
content = _with_skill_metadata(content, preserve_created=old_fm)
|
||||
_validate_skill_content(name, content)
|
||||
_write_text_atomic(skill_md, content.strip() + "\n")
|
||||
source = "global" if skill_dir.is_relative_to(MANAGED_GLOBAL_SKILL_DIR.expanduser().resolve()) else "workspace"
|
||||
source = (
|
||||
"global"
|
||||
if skill_dir.is_relative_to(MANAGED_GLOBAL_SKILL_DIR.expanduser().resolve())
|
||||
else "workspace"
|
||||
)
|
||||
bump_skill_update(workspace, name, source)
|
||||
return {"success": True, "name": name, "location": str(skill_md.resolve())}
|
||||
|
||||
@@ -635,7 +643,11 @@ def write_managed_skill_file(
|
||||
if not target.is_relative_to(skill_dir):
|
||||
raise ValueError("file_path escapes the skill")
|
||||
_write_text_atomic(target, file_content)
|
||||
source = "global" if skill_dir.is_relative_to(MANAGED_GLOBAL_SKILL_DIR.expanduser().resolve()) else "workspace"
|
||||
source = (
|
||||
"global"
|
||||
if skill_dir.is_relative_to(MANAGED_GLOBAL_SKILL_DIR.expanduser().resolve())
|
||||
else "workspace"
|
||||
)
|
||||
bump_skill_update(workspace, name, source)
|
||||
return {"success": True, "name": name, "location": str(target)}
|
||||
|
||||
@@ -787,19 +799,19 @@ async def run_skill_review(
|
||||
skill_create_requested: bool,
|
||||
) -> None:
|
||||
try:
|
||||
from cptr.utils.ai import chat_completion
|
||||
from cptr.utils.chat_task import _default_base_url
|
||||
from cptr.utils.config import _get_jwt_secret
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.models import Config
|
||||
from cptr.utils.ai import generate_json
|
||||
from cptr.utils.memory import summarize_recent_conversation
|
||||
|
||||
skills = discover_skills(workspace)
|
||||
transcript = summarize_recent_conversation(conversation_messages, assistant_reply)
|
||||
catalog = "\n".join(
|
||||
f"- {skill.name} ({skill.source}, {'managed' if skill.managed else 'read-only'}): {skill.description}"
|
||||
for skill in skills[:80]
|
||||
) or "- none"
|
||||
catalog = (
|
||||
"\n".join(
|
||||
f"- {skill.name} ({skill.source}, {'managed' if skill.managed else 'read-only'}): {skill.description}"
|
||||
for skill in skills[:80]
|
||||
)
|
||||
or "- none"
|
||||
)
|
||||
loaded_blocks = []
|
||||
for name in sorted(loaded_skill_names):
|
||||
skill = load_skill(workspace, name)
|
||||
@@ -830,20 +842,14 @@ async def run_skill_review(
|
||||
f"Loaded managed skill contents:\n{loaded_context}\n\n"
|
||||
f"Conversation:\n{transcript}"
|
||||
)
|
||||
provider = model_connection["provider"]
|
||||
api_key = decrypt_key(model_connection.get("api_key", ""), _get_jwt_secret())
|
||||
base_url = model_connection.get("base_url") or _default_base_url(provider)
|
||||
text = await chat_completion(
|
||||
provider=provider,
|
||||
base_url=base_url,
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
parsed = await generate_json(
|
||||
model_id=await Config.get("skills.background_review.model"),
|
||||
active_connection=model_connection,
|
||||
active_model=model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
system="You are Computer's private skill reviewer. Return only valid JSON.",
|
||||
max_tokens=1800,
|
||||
api_type=model_connection.get("api_type", "chat_completions"),
|
||||
)
|
||||
parsed = extract_json(text)
|
||||
if not isinstance(parsed, dict):
|
||||
return
|
||||
actions = parsed.get("actions")
|
||||
|
||||
+12
-18
@@ -27,9 +27,7 @@ def _get_summarize_prompt() -> str:
|
||||
from cptr.utils.config import load_config
|
||||
|
||||
config = load_config()
|
||||
return config.get("chat", {}).get(
|
||||
"compact_summary_prompt", DEFAULT_SUMMARIZE_PROMPT
|
||||
)
|
||||
return config.get("chat", {}).get("compact_summary_prompt", DEFAULT_SUMMARIZE_PROMPT)
|
||||
except Exception:
|
||||
return DEFAULT_SUMMARIZE_PROMPT
|
||||
|
||||
@@ -37,19 +35,14 @@ def _get_summarize_prompt() -> str:
|
||||
async def summarize_messages(
|
||||
messages: list[dict],
|
||||
existing_summary: str | None,
|
||||
provider: str,
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
connection: dict,
|
||||
model: str,
|
||||
api_type: str = "chat_completions",
|
||||
) -> str:
|
||||
"""Summarize messages into a compact rolling summary.
|
||||
|
||||
If existing_summary is provided, it's included so the new summary
|
||||
incorporates everything before it.
|
||||
"""
|
||||
from cptr.utils.ai import chat_completion
|
||||
|
||||
parts: list[str] = []
|
||||
if existing_summary:
|
||||
parts.append(f"[Previous summary]\n{existing_summary}\n")
|
||||
@@ -58,9 +51,7 @@ async def summarize_messages(
|
||||
role = m.get("role", "unknown")
|
||||
content = m.get("content", "")
|
||||
if isinstance(content, list):
|
||||
content = " ".join(
|
||||
b.get("text", "") for b in content if b.get("type") == "text"
|
||||
)
|
||||
content = " ".join(b.get("text", "") for b in content if b.get("type") == "text")
|
||||
# Truncate very long messages (e.g. tool outputs)
|
||||
if len(content) > 2000:
|
||||
content = content[:1000] + "\n...(truncated)...\n" + content[-500:]
|
||||
@@ -72,16 +63,19 @@ async def summarize_messages(
|
||||
text = text[:15_000] + "\n...\n" + text[-10_000:]
|
||||
|
||||
try:
|
||||
result = await chat_completion(
|
||||
provider=provider,
|
||||
base_url=base_url,
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
from cptr.models import Config
|
||||
from cptr.utils.ai import generate_text
|
||||
|
||||
result = await generate_text(
|
||||
model_id=await Config.get("chat.context_compaction.model"),
|
||||
active_connection=connection,
|
||||
active_model=model,
|
||||
messages=[{"role": "user", "content": text}],
|
||||
system=_get_summarize_prompt(),
|
||||
max_tokens=1000,
|
||||
api_type=api_type,
|
||||
)
|
||||
if result is None:
|
||||
raise RuntimeError("summary generation failed")
|
||||
logger.info("[summarize] LLM summary: %d chars", len(result))
|
||||
return result
|
||||
except Exception:
|
||||
|
||||
Reference in new issue
Block a user