diff --git a/cptr/app.py b/cptr/app.py index a68d561..33b6e08 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -17,6 +17,7 @@ from cptr.routers import ( files_router, gateway_router, git_router, + images_router, proxy_router, search_router, skills_router, @@ -263,6 +264,7 @@ app.include_router(events_router) app.include_router(files_router) app.include_router(gateway_router) app.include_router(git_router) +app.include_router(images_router) app.include_router(proxy_router) app.include_router(search_router) app.include_router(skills_router) diff --git a/cptr/frontend/src/lib/components/Admin/Images.svelte b/cptr/frontend/src/lib/components/Admin/Images.svelte new file mode 100644 index 0000000..ff1cf4d --- /dev/null +++ b/cptr/frontend/src/lib/components/Admin/Images.svelte @@ -0,0 +1,235 @@ + + +
+ {#if loading} +
+ {:else} +
+

+ {$t('admin.images.title')} +

+ +

+ {$t('admin.images.generation')} +

+
+ +

+ {$t('admin.images.generationHint')} +

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +

+ {$t('admin.images.editing')} +

+
+ +

+ {$t('admin.images.editHint')} +

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+ +
+ {/if} +
diff --git a/cptr/frontend/src/lib/components/Admin/Models.svelte b/cptr/frontend/src/lib/components/Admin/Models.svelte index 62a9c3b..6b5812d 100644 --- a/cptr/frontend/src/lib/components/Admin/Models.svelte +++ b/cptr/frontend/src/lib/components/Admin/Models.svelte @@ -64,7 +64,7 @@ { name: 'MODEL', desc: 'Model ID being used' } ]; - const DEFAULT_PROMPT_PLACEHOLDER = `You are cptr, a helpful assistant running inside the user's computer interface. You have access to tools to read, search, and modify files in the workspace, run commands, and use configured tools. Use them to help the user directly. + const DEFAULT_PROMPT_PLACEHOLDER = `You are Computer (cptr), a helpful assistant running inside the user's computer interface. You have access to tools to read, search, and modify files in the workspace, run commands, and use configured tools. Use them to help the user directly. Approach hard requests with initiative and persistence: make the best possible attempt, adapt as needed, and keep going unless a real constraint prevents progress. {{CPTR_CONTEXT}} diff --git a/cptr/frontend/src/lib/components/SettingsModal.svelte b/cptr/frontend/src/lib/components/SettingsModal.svelte index 47fbd3b..d1970d9 100644 --- a/cptr/frontend/src/lib/components/SettingsModal.svelte +++ b/cptr/frontend/src/lib/components/SettingsModal.svelte @@ -13,6 +13,7 @@ import Messaging from './Admin/Messaging.svelte'; import Gateway from './Admin/Gateway.svelte'; import AudioSettings from './Admin/AudioSettings.svelte'; + import Images from './Admin/Images.svelte'; import AdminWeb from './Admin/Web.svelte'; import ToolServers from './Admin/ToolServers.svelte'; import Subagents from './Admin/Subagents.svelte'; @@ -31,6 +32,7 @@ | 'messaging' | 'gateway' | 'audio' + | 'images' | 'web' | 'toolservers' | 'subagents'; @@ -67,6 +69,7 @@ { id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' }, { id: 'gateway', label: $t('admin.gateway.tab'), icon: 'gateway' }, { id: 'audio', label: $t('admin.audio.title'), icon: 'microphone' }, + { id: 'images', label: $t('admin.images.title'), icon: 'image' }, { id: 'web', label: $t('admin.web'), icon: 'globe' }, { id: 'toolservers', label: $t('admin.toolServers'), icon: 'plug' }, { id: 'subagents', label: $t('admin.subagents'), icon: 'user' } @@ -168,6 +171,8 @@ {:else if activeTab === 'audio'} + {:else if activeTab === 'images'} + {:else if activeTab === 'web'} {:else if activeTab === 'toolservers'} diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte index aa0ace4..eea6b0d 100644 --- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte @@ -225,7 +225,12 @@ item: any; } - type DisplayItem = ActivityGroup | MessageItem | ArtifactItem; + interface ImageItem { + type: 'image_item'; + item: any; + } + + type DisplayItem = ActivityGroup | MessageItem | ArtifactItem | ImageItem; const outputText = $derived.by((): string => { return (output || []) @@ -236,6 +241,14 @@ .join(''); }); + const structuredImageUrls = $derived.by((): string[] => { + return (output || []) + .filter((i: any) => i.type === 'image') + .flatMap((i: any) => i.images || []) + .map((image: any) => image?.url) + .filter((url: any): url is string => typeof url === 'string' && url.length > 0); + }); + const unrenderedContent = $derived.by((): string => { if (!content) return ''; if (!outputText) return content; @@ -246,6 +259,20 @@ return (item.content || []).map((c: any) => c.text || '').join(''); } + function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + } + + function stripStructuredImageMarkdown(text: string): string { + let cleaned = text; + for (const url of structuredImageUrls) { + const escapedUrl = escapeRegExp(url); + cleaned = cleaned.replace(new RegExp(`!\\[[^\\]]*\\]\\(${escapedUrl}\\)`, 'g'), ''); + cleaned = cleaned.replace(new RegExp(`(^|\\n)[ \\t]*${escapedUrl}[ \\t]*(?=\\n|$)`, 'g'), '$1'); + } + return cleaned.replace(/\n{3,}/g, '\n\n').trim(); + } + const displayItems = $derived.by((): DisplayItem[] => { if (!output?.length) return []; @@ -298,6 +325,9 @@ } else if (item.type === 'artifact') { flushGroup(); items.push({ type: 'artifact_item', item }); + } else if (item.type === 'image') { + flushGroup(); + items.push({ type: 'image_item', item }); } // function_call_output items are handled via outputMap, skip standalone render } @@ -379,9 +409,10 @@ {/if} {#each displayItems as displayItem, groupIdx} {#if displayItem.type === 'message_item'} - c.text).join('') || ''} - /> + {@const messageText = stripStructuredImageMarkdown(messageItemText(displayItem.item))} + {#if messageText} + + {/if} {:else if displayItem.type === 'artifact_item'} {@const artifact = displayItem.item} {@const preview = (artifact.content || '').replace(/^#.*\n*/m, '').trim()} @@ -416,6 +447,23 @@ {/if} + {:else if displayItem.type === 'image_item'} +
+ {#each displayItem.item.images || [] as image} + + {image.name + + {/each} +
{:else if displayItem.type === 'activity_group'} {#if displayItem.entries.length === 1} {@const item = displayItem.entries[0]} @@ -449,10 +497,14 @@ {/if} {/each} {#if done && unrenderedContent && displayItems.length > 0} - + {@const leftoverText = stripStructuredImageMarkdown(unrenderedContent)} + {#if leftoverText} + + {/if} {:else if !done} - {#if unrenderedContent} - + {@const leftoverText = stripStructuredImageMarkdown(unrenderedContent)} + {#if leftoverText} + {/if} { + if (!['generate_image', 'edit_image'].includes(toolName) || !pairedOutput?.output) { + return null; + } + try { + const parsed = JSON.parse(pairedOutput.output); + const images = Array.isArray(parsed.images) ? parsed.images : []; + return images.filter((image: any) => image && (image.path || image.url || image.id)); + } catch { + return null; + } + }); function toggleExpanded() { expanded = !expanded; @@ -246,12 +258,22 @@ {$t('chat.toolOutput')}
-
{pairedOutput
-									.output.length > 10000
-									? pairedOutput.output.slice(0, 10000)
-									: pairedOutput.output}
- {#if pairedOutput.output.length > 10000} + {#if imageToolOutput?.length} +
+ {#each imageToolOutput as image} +
+ {image.path || image.url || image.id} +
+ {/each} +
+ {:else} +
{pairedOutput
+										.output.length > 10000
+										? pairedOutput.output.slice(0, 10000)
+										: pairedOutput.output}
+ {/if} + {#if !imageToolOutput?.length && pairedOutput.output.length > 10000}
{$t('chat.totalChars', { count: pairedOutput.output.length.toLocaleString() diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index 9477f87..b3f4b82 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -654,6 +654,17 @@ "admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.", "admin.audio.saveFailed": "Failed to save audio settings", + "admin.images.title": "Images", + "admin.images.generation": "Image Generation", + "admin.images.editing": "Image Editing", + "admin.images.enableGeneration": "Enable image generation", + "admin.images.enableEditing": "Enable image editing", + "admin.images.size": "Size", + "admin.images.generationHint": "Compatible with OpenAI's images/generations API.", + "admin.images.editHint": "Compatible with OpenAI's images/edits API. If no edit key is set, the generation key is reused.", + "admin.images.editKeyPlaceholder": "Leave blank to reuse generation key", + "admin.images.saveFailed": "Failed to save image settings", + "sqlite.loadError": "Failed to load database.", "sqlite.null": "NULL", "sqlite.blob": "[BLOB {{size}}B]", diff --git a/cptr/routers/__init__.py b/cptr/routers/__init__.py index 0f448bf..0872dcb 100644 --- a/cptr/routers/__init__.py +++ b/cptr/routers/__init__.py @@ -11,6 +11,7 @@ from cptr.routers.gateway import router as gateway_router from cptr.routers.events import router as events_router from cptr.routers.files import router as files_router from cptr.routers.git import router as git_router +from cptr.routers.images import router as images_router from cptr.routers.proxy import router as proxy_router from cptr.routers.search import router as search_router from cptr.routers.skills import router as skills_router @@ -30,6 +31,7 @@ __all__ = [ "files_router", "gateway_router", "git_router", + "images_router", "proxy_router", "search_router", "skills_router", @@ -37,4 +39,3 @@ __all__ = [ "terminal_router", "workspace_router", ] - diff --git a/cptr/routers/admin.py b/cptr/routers/admin.py index 6e2311b..0b093a7 100644 --- a/cptr/routers/admin.py +++ b/cptr/routers/admin.py @@ -134,7 +134,12 @@ def _prepare_config_updates(updates: dict) -> dict: """Normalize sensitive config values before persisting them.""" prepared = dict(updates) secret = _get_jwt_secret() - for key in ("audio.stt_api_key", "audio.tts_api_key"): + for key in ( + "audio.stt_api_key", + "audio.tts_api_key", + "images.generation_api_key", + "images.edit_api_key", + ): value = prepared.get(key) if isinstance(value, str) and value and not value.startswith("encrypted:"): prepared[key] = encrypt_key(value, secret) diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index 354719b..807608e 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -660,7 +660,7 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ ) # Emit artifact card if the tool produced an artifact - from cptr.utils.chat_task import build_artifact_item + from cptr.utils.chat_task import build_artifact_item, build_image_item artifact_item = build_artifact_item(call["name"], call.get("arguments", {}), result) if artifact_item: @@ -672,6 +672,16 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ {"chat_id": chat_id, "message_id": message_id, "output": artifact_item}, ) + image_item = build_image_item(call["name"], result) + if image_item: + output.append(image_item) + from cptr.socket.main import emit_to_user + + await emit_to_user( + user_id, + {"chat_id": chat_id, "message_id": message_id, "output": image_item}, + ) + await ChatMessage.update(message_id, output=output, done=False) # Resolve connection and continue diff --git a/cptr/routers/images.py b/cptr/routers/images.py new file mode 100644 index 0000000..8b81eb4 --- /dev/null +++ b/cptr/routers/images.py @@ -0,0 +1,95 @@ +"""OpenAI-compatible image generation and editing routes.""" + +from __future__ import annotations + +import logging + +import httpx +from fastapi import APIRouter, HTTPException, Request +from pydantic import BaseModel, Field + +from cptr.utils.config import check_access +from cptr.utils.images import MAX_IMAGES_PER_REQUEST, edit_images, generate_images + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/images", tags=["images"]) + +COOKIE_NAME = "cptr_session" + + +class GenerateImageRequest(BaseModel): + prompt: str + workspace: str | None = None + model: str | None = None + size: str | None = None + n: int | None = Field(default=1, ge=1, le=MAX_IMAGES_PER_REQUEST) + + +class EditImageRequest(BaseModel): + prompt: str + image_ids: list[str] + workspace: str | None = None + model: str | None = None + size: str | None = None + n: int | None = Field(default=1, ge=1, le=MAX_IMAGES_PER_REQUEST) + background: str | None = None + + +def _get_user(request: Request) -> str: + token = request.cookies.get(COOKIE_NAME) + client_host = request.client.host if request.client else "127.0.0.1" + auth = check_access(client_host=client_host, jwt_token=token) + if not auth or not auth.user_id: + raise HTTPException(401, "authentication required") + return auth.user_id + + +def _raise_image_error(exc: Exception) -> None: + if isinstance(exc, PermissionError): + raise HTTPException(403, str(exc)) + if isinstance(exc, ValueError): + raise HTTPException(400, str(exc)) + if isinstance(exc, httpx.HTTPStatusError): + detail = f"Image API error: {exc.response.status_code}" + logger.warning("[images] %s: %s", detail, exc.response.text[:500]) + raise HTTPException(502, detail) + if isinstance(exc, httpx.ConnectError): + raise HTTPException(502, "Could not connect to image API") + raise HTTPException(500, "Image request failed") + + +@router.post("/generations") +async def create_image_generation(body: GenerateImageRequest, request: Request): + user_id = _get_user(request) + try: + images = await generate_images( + body.prompt, + user_id=user_id, + model=body.model, + size=body.size, + n=body.n, + workspace=body.workspace, + ) + return {"images": [image.as_dict() for image in images]} + except Exception as exc: + _raise_image_error(exc) + + +@router.post("/edits") +async def create_image_edit(body: EditImageRequest, request: Request): + user_id = _get_user(request) + try: + images = await edit_images( + body.prompt, + body.image_ids, + user_id=user_id, + model=body.model, + size=body.size, + n=body.n, + background=body.background, + workspace=body.workspace, + ) + return {"images": [image.as_dict() for image in images]} + except Exception as exc: + _raise_image_error(exc) diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 9e84523..2065e86 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -556,6 +556,9 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic # Filter calls to only those with matching outputs turn_output_ids = {o["call_id"] for o in turn["outputs"]} matched_calls = [tc for tc in turn["calls"] if tc["id"] in turn_output_ids] + call_names = { + tc["id"]: tc.get("function", {}).get("name", "") for tc in turn["calls"] + } if matched_calls: if ti == 0: # First turn: attach to the existing entry @@ -578,7 +581,10 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic entry = { "role": "tool", "tool_call_id": out["call_id"], - "content": out.get("output", ""), + "content": _tool_result_for_model( + call_names.get(out["call_id"], ""), + out.get("output", ""), + ), } result.append(entry) @@ -666,6 +672,39 @@ def _parse_image_data_uri(result: str) -> tuple[str, str] | None: return None +def _tool_result_for_model(tool_name: str, result: str) -> str: + """Return the tool result text to send back to the model.""" + if tool_name not in {"generate_image", "edit_image"}: + return result + + try: + meta = json.loads(result) + except (json.JSONDecodeError, TypeError): + return result + + images = meta.get("images") + if not isinstance(images, list): + return result + + return json.dumps( + { + "status": meta.get("status", "success"), + "displayed_to_user": True, + "note": "The generated image is already displayed in the chat. Do not include markdown image links for it.", + "images": [ + { + "id": image.get("id"), + "path": image.get("path"), + "name": image.get("name"), + "mime_type": image.get("mime_type"), + } + for image in images + if isinstance(image, dict) + ], + } + ) + + def _append_tool_to_messages( messages: list[dict], event: dict, @@ -674,6 +713,8 @@ def _append_tool_to_messages( reasoning_items: list[dict] | None = None, ): """Append a tool call + result to the message history for the next API call.""" + result = _tool_result_for_model(event["name"], result) + # Check for image result before truncation (data URI is large but needed) image = _parse_image_data_uri(result) @@ -774,6 +815,8 @@ def _append_batch_to_messages( messages.append(assistant_msg) for event, result in call_results: + result = _tool_result_for_model(event["name"], result) + # Guard against oversized tool outputs image = _parse_image_data_uri(result) if not image: @@ -921,6 +964,30 @@ def build_artifact_item(tool_name: str, arguments: dict, result: str) -> dict | } +def build_image_item(tool_name: str, result: str) -> dict | None: + """Build a renderable image output item for image-generation tools.""" + if tool_name not in {"generate_image", "edit_image"}: + return None + + try: + meta = json.loads(result) + except (json.JSONDecodeError, TypeError): + return None + + images = meta.get("images") + if not isinstance(images, list) or not images: + return None + + return { + "type": "image", + "images": [ + image + for image in images + if isinstance(image, dict) and isinstance(image.get("url"), str) + ], + } + + def _default_base_url(provider: str) -> str: return { "anthropic": "https://api.anthropic.com/v1", @@ -1438,6 +1505,12 @@ async def run_chat_task( await emit(output=artifact_item) _sync_state() + image_item = build_image_item(tc["name"], result) + if image_item: + output_items.append(image_item) + await emit(output=image_item) + _sync_state() + sequential_results.append((tc, result)) # Build a single combined assistant message for all sequential calls diff --git a/cptr/utils/images.py b/cptr/utils/images.py new file mode 100644 index 0000000..9fff865 --- /dev/null +++ b/cptr/utils/images.py @@ -0,0 +1,345 @@ +"""OpenAI-compatible image generation and editing helpers.""" + +from __future__ import annotations + +import base64 +import asyncio +import hashlib +import mimetypes +import os +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path + +import httpx + +from cptr.models import Config, File +from cptr.utils.config import _get_jwt_secret, now_ms +from cptr.utils.crypto import decrypt_key +from cptr.utils.storage import get_storage + + +DEFAULT_IMAGE_BASE_URL = "https://api.openai.com/v1" +DEFAULT_IMAGE_MODEL = "gpt-image-1" +MAX_IMAGES_PER_REQUEST = 4 + + +@dataclass +class ImageResult: + id: str + url: str + name: str + content_type: str + size: int + path: str | None = None + + def as_dict(self) -> dict: + data = { + "id": self.id, + "url": self.url, + "name": self.name, + "type": "image", + "content_type": self.content_type, + "size": self.size, + } + if self.path: + data["path"] = self.path + return data + + +def clamp_image_count(n: int | None) -> int: + if n is None: + return 1 + return min(max(int(n), 1), MAX_IMAGES_PER_REQUEST) + + +def _clean_base_url(value: object) -> str: + base_url = str(value or DEFAULT_IMAGE_BASE_URL).strip().rstrip("/") + return base_url or DEFAULT_IMAGE_BASE_URL + + +def _clean_optional(value: object) -> str | None: + if not isinstance(value, str): + return None + value = value.strip() + return value or None + + +async def _decrypt_config_key(key: str) -> str | None: + encrypted = await Config.get(key) + if not encrypted: + return None + return decrypt_key(str(encrypted), _get_jwt_secret()) + + +async def image_generation_config() -> dict: + return { + "enabled": await Config.get("images.generation_enabled") is True, + "base_url": _clean_base_url(await Config.get("images.generation_base_url")), + "api_key": await _decrypt_config_key("images.generation_api_key"), + "model": _clean_optional(await Config.get("images.generation_model")) + or DEFAULT_IMAGE_MODEL, + "size": _clean_optional(await Config.get("images.generation_size")), + } + + +async def image_edit_config() -> dict: + edit_key = await _decrypt_config_key("images.edit_api_key") + generation_key = await _decrypt_config_key("images.generation_api_key") + return { + "enabled": await Config.get("images.edit_enabled") is True, + "base_url": _clean_base_url(await Config.get("images.edit_base_url")), + "api_key": edit_key or generation_key, + "model": _clean_optional(await Config.get("images.edit_model")) or DEFAULT_IMAGE_MODEL, + "size": _clean_optional(await Config.get("images.edit_size")), + } + + +def _extension_for_content_type(content_type: str) -> str: + content_type = content_type.split(";")[0].strip().lower() + ext = mimetypes.guess_extension(content_type) + if ext == ".jpe": + ext = ".jpg" + return ext or ".png" + + +def _file_url(file_id: str, content_type: str) -> str: + return f"/api/files/{file_id}{_extension_for_content_type(content_type)}" + + +def _unique_workspace_image_path(workspace: str, source: str, content_type: str) -> Path: + root = Path(workspace).expanduser().resolve() + ext = _extension_for_content_type(content_type) + stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") + name = f"{source}-{stamp}{ext}" + path = root / name + counter = 2 + while path.exists(): + path = root / f"{source}-{stamp}-{counter}{ext}" + counter += 1 + return path + + +async def _store_image( + data: bytes, + content_type: str, + user_id: str | None, + source: str, + metadata: dict, + workspace: str | None = None, +) -> ImageResult: + content_type = content_type.split(";")[0].strip().lower() or "image/png" + ext = _extension_for_content_type(content_type) + workspace_path: Path | None = None + + if workspace: + workspace_path = _unique_workspace_image_path(workspace, source, content_type) + + def _write() -> None: + workspace_path.parent.mkdir(parents=True, exist_ok=True) + workspace_path.write_bytes(data) + + await asyncio.to_thread(_write) + + filename = workspace_path.name if workspace_path else f"{source}{ext}" + meta = { + "content_type": content_type, + "size": len(data), + "hash": hashlib.sha256(data).hexdigest(), + "source": source, + **metadata, + } + if workspace_path: + meta["path"] = str(workspace_path) + + record = await File.create( + user_id=user_id, + filename=filename, + meta=meta, + created_at=now_ms(), + ) + await get_storage().put(record.id, data) + return ImageResult( + id=record.id, + url=_file_url(record.id, content_type), + name=filename, + content_type=content_type, + size=len(data), + path=str(workspace_path) if workspace_path else None, + ) + + +async def _decode_image_response_item( + client: httpx.AsyncClient, + item: dict, + headers: dict[str, str], +) -> tuple[bytes, str]: + if b64_json := item.get("b64_json"): + return base64.b64decode(b64_json), "image/png" + + if image_url := item.get("url"): + resp = await client.get(image_url, headers=headers) + resp.raise_for_status() + content_type = resp.headers.get("content-type", "image/png") + if not content_type.lower().startswith("image/"): + raise ValueError("Provider URL did not return an image.") + return resp.content, content_type + + raise ValueError("Image response did not include b64_json or url.") + + +async def generate_images( + prompt: str, + *, + user_id: str | None, + model: str | None = None, + size: str | None = None, + n: int | None = None, + workspace: str | None = None, +) -> list[ImageResult]: + cfg = await image_generation_config() + if not cfg["enabled"]: + raise PermissionError("Image generation is disabled.") + if not cfg["api_key"]: + raise ValueError("Image generation is not configured.") + + payload: dict = { + "model": model or cfg["model"], + "prompt": prompt, + "n": clamp_image_count(n), + } + if chosen_size := (size or cfg["size"]): + payload["size"] = chosen_size + + headers = {"Authorization": f"Bearer {cfg['api_key']}"} + async with httpx.AsyncClient(timeout=httpx.Timeout(120)) as client: + resp = await client.post( + f"{cfg['base_url']}/images/generations", + headers={**headers, "Content-Type": "application/json"}, + json=payload, + ) + resp.raise_for_status() + body = resp.json() + + results = [] + for item in body.get("data", []): + data, content_type = await _decode_image_response_item(client, item, headers) + results.append( + await _store_image( + data, + content_type, + user_id, + "generated-image", + {"prompt": prompt, "model": payload["model"], "kind": "generation"}, + workspace, + ) + ) + return results + + +def clean_file_id(value: str) -> str: + value = value.strip() + if value.startswith("/api/files/"): + value = value.removeprefix("/api/files/") + value, _ = os.path.splitext(value) + if "/" in value or "\\" in value or not value: + raise ValueError("Image edits only accept cptr file IDs.") + return value + + +def _resolve_workspace_image_path(value: str, workspace: str | None) -> Path | None: + raw = value.strip() + if raw.startswith("/api/workspace/files/serve/"): + raw = "/" + raw.removeprefix("/api/workspace/files/serve/") + path = Path(raw).expanduser() + if not path.is_absolute(): + if not workspace: + return None + path = Path(workspace).expanduser().resolve() / raw + return path.resolve() + + +async def _load_image_file(image_ref: str, workspace: str | None = None) -> tuple[str, bytes, str]: + path = _resolve_workspace_image_path(image_ref, workspace) + if path and path.is_file(): + content_type = mimetypes.guess_type(str(path))[0] or "application/octet-stream" + if not content_type.lower().startswith("image/"): + raise ValueError(f"File is not an image: {image_ref}") + data = await asyncio.to_thread(path.read_bytes) + return path.name, data, content_type + + clean_id = clean_file_id(image_ref) + record = await File.get_by_id(clean_id) + if not record: + raise ValueError(f"Image file not found: {image_ref}") + data = await get_storage().get(record.id) + if data is None: + raise ValueError(f"Image blob missing: {image_ref}") + content_type = (record.meta or {}).get("content_type", "application/octet-stream") + if not str(content_type).lower().startswith("image/"): + raise ValueError(f"File is not an image: {image_ref}") + return record.filename or f"{record.id}.png", data, str(content_type) + + +async def edit_images( + prompt: str, + image_ids: list[str], + *, + user_id: str | None, + model: str | None = None, + size: str | None = None, + n: int | None = None, + background: str | None = None, + workspace: str | None = None, +) -> list[ImageResult]: + cfg = await image_edit_config() + if not cfg["enabled"]: + raise PermissionError("Image editing is disabled.") + if not cfg["api_key"]: + raise ValueError("Image editing is not configured.") + if not image_ids: + raise ValueError("At least one image file ID is required.") + + payload: dict[str, str] = { + "model": model or cfg["model"], + "prompt": prompt, + } + if n is not None: + payload["n"] = str(clamp_image_count(n)) + if chosen_size := (size or cfg["size"]): + payload["size"] = chosen_size + if background: + payload["background"] = background + + loaded_files = [await _load_image_file(image_id, workspace) for image_id in image_ids] + files = [] + multi = len(loaded_files) > 1 + for filename, data, content_type in loaded_files: + field_name = "image[]" if multi else "image" + files.append((field_name, (filename, data, content_type))) + + headers = {"Authorization": f"Bearer {cfg['api_key']}"} + async with httpx.AsyncClient(timeout=httpx.Timeout(120)) as client: + resp = await client.post( + f"{cfg['base_url']}/images/edits", + headers=headers, + data=payload, + files=files, + ) + resp.raise_for_status() + body = resp.json() + + results = [] + for item in body.get("data", []): + data, content_type = await _decode_image_response_item(client, item, headers) + results.append( + await _store_image( + data, + content_type, + user_id, + "edited-image", + {"prompt": prompt, "model": payload["model"], "kind": "edit"}, + workspace, + ) + ) + return results diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index 50c73dc..009df49 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -20,7 +20,7 @@ import re import time import uuid from pathlib import Path -from typing import Callable, Optional, Pattern, get_type_hints +from typing import Callable, Optional, Pattern, get_args, get_origin, get_type_hints from cptr.env import CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS, EXECUTE_TIMEOUT try: @@ -1439,6 +1439,72 @@ async def browser_evaluate(javascript: str, *, __context__: dict) -> str: return await client.evaluate(javascript) +async def generate_image( + prompt: str, + size: Optional[str] = None, + n: int = 1, + *, + __context__: dict, +) -> str: + """Generate image files from a text prompt. + :param prompt: Detailed description of the image to generate. + :param size: Optional image size, such as 1024x1024. + :param n: Number of images to generate, from 1 to 4. + """ + from cptr.utils.images import generate_images + + images = await generate_images( + prompt, + user_id=__context__.get("user_id"), + size=size, + n=n, + workspace=__context__.get("workspace"), + ) + return json.dumps( + { + "status": "success", + "images": [image.as_dict() for image in images], + }, + ensure_ascii=False, + ) + + +async def edit_image( + prompt: str, + image_ids: list[str], + size: Optional[str] = None, + n: int = 1, + background: Optional[str] = None, + *, + __context__: dict, +) -> str: + """Edit existing cptr image files from a text prompt. + :param prompt: Description of the requested image changes. + :param image_ids: List of cptr file IDs or /api/files/... URLs for the source images. + :param size: Optional image size, such as 1024x1024. + :param n: Number of images to create, from 1 to 4. + :param background: Optional background setting supported by the image provider. + """ + from cptr.utils.images import edit_images + + images = await edit_images( + prompt, + image_ids, + user_id=__context__.get("user_id"), + size=size, + n=n, + background=background, + workspace=__context__.get("workspace"), + ) + return json.dumps( + { + "status": "success", + "images": [image.as_dict() for image in images], + }, + ensure_ascii=False, + ) + + # ── Registry ──────────────────────────────────────────────── TOOLS: dict[str, dict] = { @@ -1463,6 +1529,8 @@ TOOLS: dict[str, dict] = { "update_automation": {"fn": update_automation, "auto": False}, "toggle_automation": {"fn": toggle_automation, "auto": False}, "delete_automation": {"fn": delete_automation, "auto": False}, + "generate_image": {"fn": generate_image, "auto": False}, + "edit_image": {"fn": edit_image, "auto": False}, } # Browser tools — conditionally included in schemas based on browser.enabled @@ -1960,6 +2028,18 @@ def _unwrap_optional(hint): return hint +def _schema_for_type(hint) -> dict: + origin = get_origin(hint) + if origin is list: + args = get_args(hint) + item_hint = _unwrap_optional(args[0]) if args else str + return { + "type": "array", + "items": _schema_for_type(item_hint), + } + return {"type": _TYPE_MAP.get(hint, "string")} # type: ignore[arg-type] + + def _parse_param_descriptions(docstring: str) -> dict[str, str]: """Extract :param name: description lines from docstring.""" descs: dict[str, str] = {} @@ -1990,8 +2070,7 @@ def _fn_to_schema(name: str, fn) -> dict: continue raw_hint = hints.get(pname) hint = _unwrap_optional(raw_hint) if raw_hint else raw_hint - ptype = _TYPE_MAP.get(hint, "string") # type: ignore[arg-type] - prop: dict = {"type": ptype} + prop: dict = _schema_for_type(hint) if pname in param_descs: prop["description"] = param_descs[pname] if param.default is not inspect.Parameter.empty: @@ -2049,7 +2128,13 @@ async def get_tool_list() -> list[dict]: "true", "1", ) + if (await Config.get("images.generation_enabled")) not in (True, "true", "1"): + tools.pop("generate_image", None) + if (await Config.get("images.edit_enabled")) not in (True, "true", "1"): + tools.pop("edit_image", None) except Exception: + tools.pop("generate_image", None) + tools.pop("edit_image", None) pass schemas = [_fn_to_schema(name, t["fn"]) for name, t in tools.items()]