This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-19 23:47:19 +02:00
1 parent 38d1d832d2
commit 7289c077a8
14 files changed
+962 -21

No files matched your search

+2
View File
@@ -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)
@@ -0,0 +1,235 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import ToggleSwitch from '../common/ToggleSwitch.svelte';
import Spinner from '../common/Spinner.svelte';
import { getAdminConfig, updateConfig } from '$lib/apis/admin';
import { t } from '$lib/i18n';
let loading = $state(true);
let saving = $state(false);
let generationEnabled = $state(false);
let generationBaseUrl = $state('https://api.openai.com/v1');
let generationApiKey = $state('');
let generationModel = $state('gpt-image-1');
let generationSize = $state('');
let hasGenerationKey = $state(false);
let editEnabled = $state(false);
let editBaseUrl = $state('https://api.openai.com/v1');
let editApiKey = $state('');
let editModel = $state('gpt-image-1');
let editSize = $state('');
let hasEditKey = $state(false);
onMount(async () => {
try {
const config = await getAdminConfig();
generationEnabled = config['images.generation_enabled'] === true;
generationBaseUrl =
(config['images.generation_base_url'] as string) || 'https://api.openai.com/v1';
generationModel = (config['images.generation_model'] as string) || 'gpt-image-1';
generationSize = (config['images.generation_size'] as string) || '';
hasGenerationKey = !!config['images.generation_api_key'];
editEnabled = config['images.edit_enabled'] === true;
editBaseUrl = (config['images.edit_base_url'] as string) || 'https://api.openai.com/v1';
editModel = (config['images.edit_model'] as string) || 'gpt-image-1';
editSize = (config['images.edit_size'] as string) || '';
hasEditKey = !!config['images.edit_api_key'];
} catch {}
loading = false;
});
async function save() {
saving = true;
try {
const cfg: Record<string, unknown> = {
'images.generation_enabled': generationEnabled,
'images.generation_base_url': generationBaseUrl,
'images.generation_model': generationModel,
'images.generation_size': generationSize,
'images.edit_enabled': editEnabled,
'images.edit_base_url': editBaseUrl,
'images.edit_model': editModel,
'images.edit_size': editSize
};
if (generationApiKey) {
cfg['images.generation_api_key'] = generationApiKey;
}
if (editApiKey) {
cfg['images.edit_api_key'] = editApiKey;
}
await updateConfig(cfg);
if (generationApiKey) hasGenerationKey = true;
if (editApiKey) hasEditKey = true;
generationApiKey = '';
editApiKey = '';
toast.success($t('settings.saved'));
} catch {
toast.error($t('admin.images.saveFailed'));
} finally {
saving = false;
}
}
</script>
<div class="flex flex-col h-full">
{#if loading}
<div class="flex justify-center py-8"><Spinner size={16} /></div>
{:else}
<div class="flex-1 min-h-0 overflow-y-auto">
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">
{$t('admin.images.title')}
</h2>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2">
{$t('admin.images.generation')}
</h3>
<div class="flex flex-col gap-2.5">
<label class="flex items-center justify-between cursor-pointer">
<span class="text-xs text-gray-600 dark:text-gray-400"
>{$t('admin.images.enableGeneration')}</span
>
<ToggleSwitch
value={generationEnabled}
onchange={(v) => {
generationEnabled = v;
}}
/>
</label>
<p class="text-[11px] text-gray-400 dark:text-gray-600 -mt-1">
{$t('admin.images.generationHint')}
</p>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="image-generation-base-url"
>{$t('connections.baseUrl')}</label
>
<input
id="image-generation-base-url"
type="text"
bind:value={generationBaseUrl}
placeholder="https://api.openai.com/v1"
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
/>
</div>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="image-generation-api-key"
>{$t('connections.apiKey')}</label
>
<input
id="image-generation-api-key"
type="password"
bind:value={generationApiKey}
placeholder={hasGenerationKey ? '••••••••' : 'sk-...'}
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
/>
</div>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="image-generation-model"
>{$t('automations.model')}</label
>
<input
id="image-generation-model"
type="text"
bind:value={generationModel}
placeholder="gpt-image-1"
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
/>
</div>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="image-generation-size"
>{$t('admin.images.size')}</label
>
<input
id="image-generation-size"
type="text"
bind:value={generationSize}
placeholder="1024x1024"
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
/>
</div>
</div>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">
{$t('admin.images.editing')}
</h3>
<div class="flex flex-col gap-2.5">
<label class="flex items-center justify-between cursor-pointer">
<span class="text-xs text-gray-600 dark:text-gray-400"
>{$t('admin.images.enableEditing')}</span
>
<ToggleSwitch
value={editEnabled}
onchange={(v) => {
editEnabled = v;
}}
/>
</label>
<p class="text-[11px] text-gray-400 dark:text-gray-600 -mt-1">
{$t('admin.images.editHint')}
</p>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="image-edit-base-url"
>{$t('connections.baseUrl')}</label
>
<input
id="image-edit-base-url"
type="text"
bind:value={editBaseUrl}
placeholder="https://api.openai.com/v1"
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
/>
</div>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="image-edit-api-key"
>{$t('connections.apiKey')}</label
>
<input
id="image-edit-api-key"
type="password"
bind:value={editApiKey}
placeholder={hasEditKey ? '••••••••' : $t('admin.images.editKeyPlaceholder')}
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
/>
</div>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="image-edit-model"
>{$t('automations.model')}</label
>
<input
id="image-edit-model"
type="text"
bind:value={editModel}
placeholder="gpt-image-1"
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
/>
</div>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="image-edit-size"
>{$t('admin.images.size')}</label
>
<input
id="image-edit-size"
type="text"
bind:value={editSize}
placeholder="1024x1024"
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
/>
</div>
</div>
</div>
<!-- Save -->
<div class="shrink-0 pt-3 flex justify-end">
<button
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-50"
onclick={() => save()}
disabled={saving}
>
{#if saving}{$t('settings.saving')}{:else}{$t('settings.save')}{/if}
</button>
</div>
{/if}
</div>
@@ -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}}
@@ -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 @@
<Gateway />
{:else if activeTab === 'audio'}
<AudioSettings />
{:else if activeTab === 'images'}
<Images />
{:else if activeTab === 'web'}
<AdminWeb />
{:else if activeTab === 'toolservers'}
@@ -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'}
<MarkdownRenderer
content={displayItem.item.content?.map((c: any) => c.text).join('') || ''}
/>
{@const messageText = stripStructuredImageMarkdown(messageItemText(displayItem.item))}
{#if messageText}
<MarkdownRenderer content={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}
</div>
</button>
{:else if displayItem.type === 'image_item'}
<div class="my-2 grid max-w-xl grid-cols-1 gap-2 sm:grid-cols-2">
{#each displayItem.item.images || [] as image}
<a
href={image.url}
target="_blank"
rel="noreferrer"
class="block overflow-hidden rounded-lg border border-gray-200 dark:border-white/8 bg-gray-50 dark:bg-white/[0.03]"
>
<img
src={image.url}
alt={image.name || 'Generated image'}
class="max-h-96 w-full object-contain"
/>
</a>
{/each}
</div>
{: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}
<MarkdownRenderer content={unrenderedContent} />
{@const leftoverText = stripStructuredImageMarkdown(unrenderedContent)}
{#if leftoverText}
<MarkdownRenderer content={leftoverText} />
{/if}
{:else if !done}
{#if unrenderedContent}
<MarkdownRenderer content={unrenderedContent} />
{@const leftoverText = stripStructuredImageMarkdown(unrenderedContent)}
{#if leftoverText}
<MarkdownRenderer content={leftoverText} />
{/if}
<span
class="inline-block w-[2px] h-3.5 bg-gray-400 dark:bg-gray-500 ml-0.5 animate-pulse align-text-bottom"
@@ -26,6 +26,18 @@
const isDone = $derived(item.status === 'completed');
const isRejected = $derived(item.status === 'rejected');
const isPending = $derived(item.status === 'pending');
const imageToolOutput = $derived.by(() => {
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')}
</div>
<div class="w-full min-w-0 overflow-hidden">
<pre
class="text-xs text-gray-600 dark:text-gray-300 whitespace-pre-wrap break-words font-mono max-h-64 overflow-auto leading-relaxed">{pairedOutput
.output.length > 10000
? pairedOutput.output.slice(0, 10000)
: pairedOutput.output}</pre>
{#if pairedOutput.output.length > 10000}
{#if imageToolOutput?.length}
<div class="px-1 space-y-1">
{#each imageToolOutput as image}
<div class="text-xs text-gray-600 dark:text-gray-300 break-all leading-relaxed">
{image.path || image.url || image.id}
</div>
{/each}
</div>
{:else}
<pre
class="text-xs text-gray-600 dark:text-gray-300 whitespace-pre-wrap break-words font-mono max-h-64 overflow-auto leading-relaxed">{pairedOutput
.output.length > 10000
? pairedOutput.output.slice(0, 10000)
: pairedOutput.output}</pre>
{/if}
{#if !imageToolOutput?.length && pairedOutput.output.length > 10000}
<div class="text-[10px] text-gray-400 dark:text-gray-600 mt-1 px-1">
{$t('chat.totalChars', {
count: pairedOutput.output.length.toLocaleString()
@@ -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]",
+2 -1
View File
@@ -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",
]
+6 -1
View File
@@ -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)
+11 -1
View File
@@ -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
+95
View File
@@ -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)
+74 -1
View File
@@ -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
+345
View File
@@ -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
+88 -3
View File
@@ -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()]