mirror of
https://github.com/open-webui/computer.git
synced 2026-12-04 10:37:57 -05:00
refac
This commit is contained in:
1 parent
44a95ab042
commit
07f35e7060
12 files changed
+275
-160
No files matched your search
@@ -130,6 +130,7 @@ export interface Connection {
|
||||
name: string;
|
||||
provider: string;
|
||||
api_type: string;
|
||||
provider_type?: 'default' | 'llama.cpp' | null;
|
||||
prefix_id: string | null;
|
||||
base_url: string | null;
|
||||
api_key: string | null;
|
||||
@@ -146,6 +147,7 @@ export const createConnection = (conn: {
|
||||
name: string;
|
||||
provider: string;
|
||||
api_type?: string;
|
||||
provider_type?: 'default' | 'llama.cpp' | null;
|
||||
prefix_id?: string | null;
|
||||
base_url?: string | null;
|
||||
api_key?: string | null;
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
} from '$lib/apis/admin';
|
||||
import Icon from '$lib/components/Icon.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import AgentProfileModal from './AgentProfileModal.svelte';
|
||||
@@ -179,8 +180,7 @@
|
||||
modal = null;
|
||||
}
|
||||
|
||||
function toggleProfile(e: Event, index: number) {
|
||||
e.stopPropagation();
|
||||
function toggleProfile(index: number) {
|
||||
const profile = profiles[index];
|
||||
if (!profile) return;
|
||||
const mode = profile.mode === 'disabled' ? 'enabled' : 'disabled';
|
||||
@@ -262,11 +262,12 @@
|
||||
{:else}
|
||||
<div class="divide-y divide-gray-100 dark:divide-white/5">
|
||||
{#each profiles as profile, index (profile.id)}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full min-h-9 py-1.5 text-left"
|
||||
onclick={() => (modal = { mode: 'edit', index, profile })}
|
||||
>
|
||||
<span class="flex-1 min-w-0">
|
||||
<div class="group flex items-center gap-2 w-full min-h-9 py-1.5 text-left">
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left"
|
||||
onclick={() => (modal = { mode: 'edit', index, profile })}
|
||||
>
|
||||
<span
|
||||
class="block text-[0.8125rem] truncate {profile.mode === 'disabled'
|
||||
? 'text-gray-400 dark:text-gray-600'
|
||||
@@ -282,36 +283,15 @@
|
||||
{detected[profile.id]?.message}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
</button>
|
||||
<span
|
||||
class="hidden sm:flex items-center gap-1.5 shrink-0 text-[0.6875rem] text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
<span class="w-1.5 h-1.5 rounded-full {statusTone(profile)}"></span>
|
||||
<span>{$t(statusKey(profile))}</span>
|
||||
</span>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
|
||||
{profile.mode !== 'disabled' ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={profile.mode !== 'disabled'}
|
||||
onclick={(e) => toggleProfile(e, index)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleProfile(e, index);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{profile.mode !== 'disabled'
|
||||
? 'left-3 bg-white dark:bg-gray-900'
|
||||
: 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
<ToggleSwitch value={profile.mode !== 'disabled'} onchange={() => toggleProfile(index)} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import { t } from '$lib/i18n';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
|
||||
let connections = $state<Connection[]>([]);
|
||||
let loading = $state(true);
|
||||
@@ -35,9 +36,7 @@
|
||||
load();
|
||||
}
|
||||
|
||||
async function toggleEnabled(e: Event, conn: Connection) {
|
||||
e.stopPropagation();
|
||||
const newVal = !conn.enabled;
|
||||
async function toggleEnabled(conn: Connection, newVal: boolean) {
|
||||
// Optimistic update
|
||||
conn.enabled = newVal;
|
||||
connections = [...connections];
|
||||
@@ -72,37 +71,17 @@
|
||||
{:else}
|
||||
<div>
|
||||
{#each connections as conn}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => (editConn = conn)}
|
||||
>
|
||||
<span
|
||||
class="flex-1 text-[0.8125rem] truncate
|
||||
<div class="group flex items-center gap-2 w-full h-7 text-left">
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left text-[0.8125rem] truncate
|
||||
{conn.enabled ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}"
|
||||
onclick={() => (editConn = conn)}
|
||||
>
|
||||
{conn.name}
|
||||
</span>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
|
||||
{conn.enabled ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={conn.enabled}
|
||||
onclick={(e) => toggleEnabled(e, conn)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleEnabled(e, conn);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{conn.enabled ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
</button>
|
||||
<ToggleSwitch value={conn.enabled} onchange={(value) => toggleEnabled(conn, value)} />
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if connections.length === 0}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
let formName = $state('');
|
||||
let formProvider = $state<'openai' | 'anthropic'>('openai');
|
||||
let formApiType = $state<'chat_completions' | 'responses'>('chat_completions');
|
||||
let formProviderType = $state<'default' | 'llama.cpp'>('default');
|
||||
let formBaseUrl = $state('');
|
||||
let formApiKey = $state('');
|
||||
let formPrefixId = $state('');
|
||||
@@ -49,6 +50,7 @@
|
||||
name,
|
||||
provider: formProvider,
|
||||
api_type: formProvider === 'openai' ? formApiType : 'chat_completions',
|
||||
provider_type: formProvider === 'openai' ? formProviderType : 'default',
|
||||
prefix_id: formPrefixId.trim() || null,
|
||||
base_url: formBaseUrl.trim(),
|
||||
api_key: formApiKey.trim(),
|
||||
@@ -115,6 +117,21 @@
|
||||
<option value="chat_completions">{$t('connections.chatCompletions')}</option>
|
||||
<option value="responses">{$t('connections.responses')}</option>
|
||||
</select>
|
||||
|
||||
<label
|
||||
for="create-provider-type"
|
||||
class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>
|
||||
Provider Type
|
||||
</label>
|
||||
<select
|
||||
id="create-provider-type"
|
||||
bind:value={formProviderType}
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
<option value="default">Default</option>
|
||||
<option value="llama.cpp">llama.cpp</option>
|
||||
</select>
|
||||
{/if}
|
||||
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
|
||||
@@ -27,6 +27,9 @@
|
||||
let formApiType = $state<'chat_completions' | 'responses'>(
|
||||
connection.api_type === 'responses' ? 'responses' : 'chat_completions'
|
||||
);
|
||||
let formProviderType = $state<'default' | 'llama.cpp'>(
|
||||
connection.provider_type === 'llama.cpp' ? 'llama.cpp' : 'default'
|
||||
);
|
||||
let formBaseUrl = $state(connection.base_url || '');
|
||||
let formApiKey = $state('');
|
||||
let formPrefixId = $state(connection.prefix_id || '');
|
||||
@@ -61,6 +64,7 @@
|
||||
name,
|
||||
provider: formProvider,
|
||||
api_type: formProvider === 'openai' ? formApiType : 'chat_completions',
|
||||
provider_type: formProvider === 'openai' ? formProviderType : 'default',
|
||||
prefix_id: formPrefixId.trim() || null,
|
||||
base_url: formBaseUrl.trim(),
|
||||
models
|
||||
@@ -151,6 +155,21 @@
|
||||
<option value="chat_completions">{$t('connections.chatCompletions')}</option>
|
||||
<option value="responses">{$t('connections.responses')}</option>
|
||||
</select>
|
||||
|
||||
<label
|
||||
for="edit-provider-type"
|
||||
class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>
|
||||
Provider Type
|
||||
</label>
|
||||
<select
|
||||
id="edit-provider-type"
|
||||
bind:value={formProviderType}
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
<option value="default">Default</option>
|
||||
<option value="llama.cpp">llama.cpp</option>
|
||||
</select>
|
||||
{/if}
|
||||
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { listBots, deleteBot, startBot, stopBot, type BotData } from '$lib/apis/bots';
|
||||
import { t } from '$lib/i18n';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
|
||||
let bots = $state<BotData[]>([]);
|
||||
let loading = $state(true);
|
||||
@@ -29,8 +30,7 @@
|
||||
load();
|
||||
}
|
||||
|
||||
async function toggleRunning(e: Event, bot: BotData) {
|
||||
e.stopPropagation();
|
||||
async function toggleRunning(bot: BotData) {
|
||||
const wasRunning = bot.is_running;
|
||||
// Optimistic
|
||||
bot.is_running = !wasRunning;
|
||||
@@ -108,27 +108,7 @@
|
||||
<Icon name="trash" size={11} />
|
||||
</button>
|
||||
|
||||
<!-- Toggle switch -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
|
||||
{bot.is_running ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={bot.is_running}
|
||||
onclick={(e) => toggleRunning(e, bot)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleRunning(e, bot);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{bot.is_running ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
<ToggleSwitch value={bot.is_running} onchange={() => toggleRunning(bot)} />
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
|
||||
@@ -278,9 +278,7 @@ Files:
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleModel(e: Event, model: ModelEntry) {
|
||||
e.stopPropagation();
|
||||
const newVal = !model.is_active;
|
||||
async function toggleModel(model: ModelEntry, newVal: boolean) {
|
||||
model.is_active = newVal;
|
||||
models = [...models];
|
||||
try {
|
||||
@@ -659,38 +657,18 @@ Files:
|
||||
|
||||
<!-- Per-model list -->
|
||||
{#each models as model}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => (selectedId = selectedId === model.id ? null : model.id)}
|
||||
>
|
||||
<span
|
||||
class="flex-1 text-[0.8125rem] truncate {model.is_active
|
||||
<div class="group flex items-center gap-2 w-full h-7 text-left">
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left text-[0.8125rem] truncate {model.is_active
|
||||
? 'text-gray-700 dark:text-gray-300'
|
||||
: 'text-gray-400 dark:text-gray-600'}"
|
||||
onclick={() => (selectedId = selectedId === model.id ? null : model.id)}
|
||||
>
|
||||
{model.name}
|
||||
</span>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
|
||||
{model.is_active ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={model.is_active}
|
||||
onclick={(e) => toggleModel(e, model)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleModel(e, model);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{model.is_active ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
</button>
|
||||
<ToggleSwitch value={model.is_active} onchange={(value) => toggleModel(model, value)} />
|
||||
</div>
|
||||
|
||||
{#if selectedId === model.id}
|
||||
{@render compactThresholdField(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import Icon from '../Icon.svelte';
|
||||
import Modal from '../Modal.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
listToolServers,
|
||||
@@ -188,9 +189,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleEnabled(e: Event, s: ToolServer) {
|
||||
e.stopPropagation();
|
||||
const newVal = !s.enabled;
|
||||
async function toggleEnabled(s: ToolServer, newVal: boolean) {
|
||||
s.enabled = newVal;
|
||||
servers = [...servers];
|
||||
try {
|
||||
@@ -222,10 +221,7 @@
|
||||
{:else}
|
||||
<div>
|
||||
{#each servers as s}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => openEdit(s)}
|
||||
>
|
||||
<div class="group flex items-center gap-2 w-full h-7 text-left">
|
||||
<span
|
||||
class="text-[0.625rem] font-mono shrink-0
|
||||
{s.type === 'mcp' || s.type === 'mcp_stdio'
|
||||
@@ -234,33 +230,16 @@
|
||||
>
|
||||
{s.type === 'mcp' ? 'MCP' : s.type === 'mcp_stdio' ? 'STDIO' : 'API'}
|
||||
</span>
|
||||
<span
|
||||
class="flex-1 text-[0.8125rem] truncate
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left text-[0.8125rem] truncate
|
||||
{s.enabled ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}"
|
||||
onclick={() => openEdit(s)}
|
||||
>
|
||||
{s.name || s.command || s.url}
|
||||
</span>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
|
||||
{s.enabled ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={s.enabled}
|
||||
onclick={(e) => toggleEnabled(e, s)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleEnabled(e, s);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{s.enabled ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
</button>
|
||||
<ToggleSwitch value={s.enabled} onchange={(value) => toggleEnabled(s, value)} />
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if servers.length === 0}
|
||||
|
||||
@@ -3,18 +3,25 @@
|
||||
value: boolean;
|
||||
onchange?: (value: boolean) => void;
|
||||
disabled?: boolean;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
let { value, onchange, disabled = false, ariaLabel = 'Toggle' }: Props = $props();
|
||||
|
||||
function toggle(event: MouseEvent) {
|
||||
event.stopPropagation();
|
||||
onchange?.(!value);
|
||||
}
|
||||
let { value, onchange, disabled = false }: Props = $props();
|
||||
</script>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="relative w-7 h-4 rounded-full transition-colors duration-150 shrink-0
|
||||
{value ? 'bg-gray-900 dark:bg-white' : 'bg-gray-300 dark:bg-gray-700'}"
|
||||
onclick={() => onchange?.(!value)}
|
||||
onclick={toggle}
|
||||
{disabled}
|
||||
role="switch"
|
||||
aria-checked={value}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<span
|
||||
class="absolute top-[0.125rem] w-3 h-3 rounded-full transition-all duration-150
|
||||
|
||||
@@ -235,6 +235,9 @@ async def create_connection(body: CreateConnectionRequest, request: Request):
|
||||
"name": body.name,
|
||||
"provider": body.provider,
|
||||
"api_type": body.api_type, # "chat_completions" | "responses" (openai only)
|
||||
"provider_type": "llama.cpp"
|
||||
if body.provider == "openai" and body.provider_type == "llama.cpp"
|
||||
else "default",
|
||||
"prefix_id": body.prefix_id,
|
||||
"base_url": body.base_url,
|
||||
"api_key": encrypt_key(body.api_key, _get_jwt_secret()) if body.api_key else None,
|
||||
@@ -260,8 +263,16 @@ async def update_connection(conn_id: str, body: UpdateConnectionRequest, request
|
||||
conn["name"] = body.name
|
||||
if body.provider is not None:
|
||||
conn["provider"] = body.provider
|
||||
if body.provider != "openai":
|
||||
conn["provider_type"] = "default"
|
||||
if body.api_type is not None:
|
||||
conn["api_type"] = body.api_type
|
||||
if "provider_type" in body.model_fields_set:
|
||||
conn["provider_type"] = (
|
||||
"llama.cpp"
|
||||
if conn.get("provider") == "openai" and body.provider_type == "llama.cpp"
|
||||
else "default"
|
||||
)
|
||||
if body.prefix_id is not None:
|
||||
conn["prefix_id"] = body.prefix_id or None
|
||||
if body.base_url is not None:
|
||||
@@ -389,6 +400,7 @@ class CreateConnectionRequest(BaseModel):
|
||||
name: str
|
||||
provider: str # "anthropic" | "openai"
|
||||
api_type: str = "chat_completions" # "chat_completions" | "responses" (openai only)
|
||||
provider_type: Optional[str] = None # None | "default" | "llama.cpp" (openai only)
|
||||
prefix_id: Optional[str] = None # e.g. "openrouter" → "openrouter/model-id"
|
||||
base_url: Optional[str] = None
|
||||
api_key: Optional[str] = None
|
||||
@@ -400,6 +412,7 @@ class UpdateConnectionRequest(BaseModel):
|
||||
name: Optional[str] = None
|
||||
provider: Optional[str] = None
|
||||
api_type: Optional[str] = None
|
||||
provider_type: Optional[str] = None
|
||||
prefix_id: Optional[str] = None
|
||||
base_url: Optional[str] = None
|
||||
api_key: Optional[str] = None
|
||||
|
||||
+117
-4
@@ -669,7 +669,35 @@ async def stream_openai_completions(
|
||||
# ── OpenAI Responses API ─────────────────────────────────────
|
||||
|
||||
|
||||
def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
def _reasoning_item_has_replayable_state(item: dict) -> bool:
|
||||
if not isinstance(item, dict) or item.get("type") != "reasoning":
|
||||
return False
|
||||
if item.get("status") not in (None, "completed"):
|
||||
return False
|
||||
if item.get("encrypted_content") or item.get("reasoning_details"):
|
||||
return True
|
||||
return bool(_reasoning_items_to_content([item]))
|
||||
|
||||
|
||||
def _replayable_reasoning_items(items: list[dict] | None, *, provider_type: str) -> list[dict]:
|
||||
replayable: list[dict] = []
|
||||
for item in items or []:
|
||||
if not _reasoning_item_has_replayable_state(item):
|
||||
continue
|
||||
if str(item.get("id", "")).startswith("reasoning-") and item.get("source") != "provider":
|
||||
continue
|
||||
out = copy.deepcopy(item)
|
||||
if provider_type == "llama.cpp" and not _reasoning_text_from_blocks(out.get("content")):
|
||||
text = _reasoning_items_to_content([out])
|
||||
if text:
|
||||
out["content"] = [{"type": "text", "text": text}]
|
||||
replayable.append(out)
|
||||
return replayable
|
||||
|
||||
|
||||
def _to_responses_input(
|
||||
messages: list[dict], instructions: str, *, provider_type: str = "default"
|
||||
) -> list[dict]:
|
||||
"""Canonical messages → Responses API input items."""
|
||||
# Pre-collect all tool result call_ids so we can validate function_calls
|
||||
# have matching outputs. This prevents orphaned function_calls (from
|
||||
@@ -701,7 +729,9 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
)
|
||||
elif role == "assistant" and m.get("tool_calls"):
|
||||
# Emit reasoning items before function calls (required by reasoning models)
|
||||
for ri in m.get("reasoning_items", []):
|
||||
for ri in _replayable_reasoning_items(
|
||||
m.get("reasoning_items"), provider_type=provider_type
|
||||
):
|
||||
items.append(ri)
|
||||
for tc in m["tool_calls"]:
|
||||
call_id = tc.get("id", "")
|
||||
@@ -729,6 +759,11 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
}
|
||||
)
|
||||
else:
|
||||
if role == "assistant":
|
||||
for ri in _replayable_reasoning_items(
|
||||
m.get("reasoning_items"), provider_type=provider_type
|
||||
):
|
||||
items.append(ri)
|
||||
content = m.get("content", "")
|
||||
if isinstance(content, list):
|
||||
formatted_content = []
|
||||
@@ -747,7 +782,12 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
|
||||
|
||||
async def stream_openai_responses(
|
||||
form_data: ChatCompletionForm, url: str, key: str, *, request_params: dict | None = None
|
||||
form_data: ChatCompletionForm,
|
||||
url: str,
|
||||
key: str,
|
||||
*,
|
||||
request_params: dict | None = None,
|
||||
provider_type: str = "default",
|
||||
) -> AsyncIterator[dict]:
|
||||
tools = [
|
||||
{
|
||||
@@ -761,7 +801,9 @@ async def stream_openai_responses(
|
||||
|
||||
body: dict = {
|
||||
"model": form_data.model,
|
||||
"input": _to_responses_input(form_data.messages, form_data.instructions),
|
||||
"input": _to_responses_input(
|
||||
form_data.messages, form_data.instructions, provider_type=provider_type
|
||||
),
|
||||
"stream": True,
|
||||
}
|
||||
if form_data.instructions:
|
||||
@@ -801,6 +843,20 @@ async def stream_openai_responses(
|
||||
error_body.decode(errors="replace"),
|
||||
)
|
||||
resp.raise_for_status()
|
||||
output_items_by_id: dict[str, dict] = {}
|
||||
active_reasoning_item: dict | None = None
|
||||
|
||||
def get_reasoning_item(event: dict) -> dict:
|
||||
nonlocal active_reasoning_item
|
||||
item_id = event.get("item_id") or event.get("output_item_id") or "rs_stream"
|
||||
if item_id in output_items_by_id:
|
||||
active_reasoning_item = output_items_by_id[item_id]
|
||||
if active_reasoning_item is None:
|
||||
active_reasoning_item = _reasoning_output_item()
|
||||
active_reasoning_item["id"] = item_id
|
||||
output_items_by_id[item_id] = active_reasoning_item
|
||||
return active_reasoning_item
|
||||
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.startswith("data: "):
|
||||
continue
|
||||
@@ -814,8 +870,53 @@ async def stream_openai_responses(
|
||||
emitted = True
|
||||
yield {"type": "text_delta", "content": event["delta"]}
|
||||
|
||||
elif etype == "response.output_item.added":
|
||||
item = event.get("item") or {}
|
||||
item_id = item.get("id")
|
||||
if item_id:
|
||||
output_items_by_id[item_id] = copy.deepcopy(item)
|
||||
if item.get("type") == "reasoning":
|
||||
active_reasoning_item = output_items_by_id.get(item_id) or item
|
||||
|
||||
elif etype in (
|
||||
"response.reasoning.delta",
|
||||
"response.reasoning_text.delta",
|
||||
):
|
||||
item = get_reasoning_item(event)
|
||||
delta = event.get("delta", "")
|
||||
content = item.setdefault("content", [{"type": "text", "text": ""}])
|
||||
if not content:
|
||||
content.append({"type": "text", "text": ""})
|
||||
if isinstance(content[0], dict):
|
||||
content[0]["type"] = content[0].get("type") or "text"
|
||||
content[0]["text"] = f"{content[0].get('text', '')}{delta}"
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(item)}
|
||||
|
||||
elif etype == "response.reasoning_summary_text.delta":
|
||||
item = get_reasoning_item(event)
|
||||
delta = event.get("delta", "")
|
||||
summary = item.setdefault("summary", [{"type": "summary_text", "text": ""}])
|
||||
if not summary:
|
||||
summary.append({"type": "summary_text", "text": ""})
|
||||
if isinstance(summary[0], dict):
|
||||
summary[0]["type"] = summary[0].get("type") or "summary_text"
|
||||
summary[0]["text"] = f"{summary[0].get('text', '')}{delta}"
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(item)}
|
||||
|
||||
elif etype == "response.reasoning_summary_part.added":
|
||||
item = get_reasoning_item(event)
|
||||
part = event.get("part")
|
||||
if part:
|
||||
item.setdefault("summary", []).append(copy.deepcopy(part))
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(item)}
|
||||
|
||||
elif etype == "response.output_item.done":
|
||||
item = event["item"]
|
||||
if item.get("id"):
|
||||
output_items_by_id[item["id"]] = copy.deepcopy(item)
|
||||
if item["type"] == "function_call":
|
||||
emitted = True
|
||||
yield {
|
||||
@@ -827,6 +928,12 @@ async def stream_openai_responses(
|
||||
}
|
||||
elif item["type"] == "reasoning":
|
||||
# Reasoning items must be round-tripped for reasoning models
|
||||
item.setdefault("source", "provider")
|
||||
if (
|
||||
active_reasoning_item is not None
|
||||
and active_reasoning_item.get("id") == item.get("id")
|
||||
):
|
||||
active_reasoning_item = None
|
||||
emitted = True
|
||||
yield {
|
||||
"type": "output",
|
||||
@@ -839,6 +946,12 @@ 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_item_has_replayable_state(
|
||||
{**active_reasoning_item, "status": "completed"}
|
||||
):
|
||||
active_reasoning_item["status"] = "completed"
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(active_reasoning_item)}
|
||||
usage = event.get("response", {}).get("usage", {})
|
||||
if usage:
|
||||
emitted = True
|
||||
|
||||
+55
-7
@@ -909,6 +909,8 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
for item in m.output:
|
||||
itype = item.get("type")
|
||||
if itype == "reasoning":
|
||||
if not _is_provider_replayable_reasoning_item(item):
|
||||
continue
|
||||
# A reasoning item after we already have outputs means
|
||||
# a new API iteration started — flush the current turn.
|
||||
if current_turn["outputs"]:
|
||||
@@ -951,7 +953,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
# Skip other types (message, artifact, pending calls, etc.)
|
||||
|
||||
# Don't forget the last turn
|
||||
if current_turn["calls"] or current_turn["outputs"]:
|
||||
if current_turn["reasoning"] or current_turn["calls"] or current_turn["outputs"]:
|
||||
turns.append(current_turn)
|
||||
|
||||
if not turns:
|
||||
@@ -965,6 +967,18 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
call_names = {
|
||||
tc["id"]: tc.get("function", {}).get("name", "") for tc in turn["calls"]
|
||||
}
|
||||
if turn["reasoning"] and not matched_calls and not turn["outputs"]:
|
||||
if ti == 0:
|
||||
entry["reasoning_items"] = turn["reasoning"]
|
||||
else:
|
||||
result.append(entry)
|
||||
entry = {
|
||||
"id": m.id,
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"reasoning_items": turn["reasoning"],
|
||||
}
|
||||
continue
|
||||
if matched_calls:
|
||||
if ti == 0:
|
||||
# First turn: attach to the existing entry
|
||||
@@ -1125,6 +1139,19 @@ def _tool_result_for_model(tool_name: str, result: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _is_provider_replayable_reasoning_item(item: dict) -> bool:
|
||||
"""Return True for provider reasoning that can be sent back to model APIs."""
|
||||
if item.get("type") != "reasoning":
|
||||
return False
|
||||
if item.get("status") not in (None, "completed"):
|
||||
return False
|
||||
if str(item.get("id", "")).startswith("reasoning-") and item.get("source") != "provider":
|
||||
return False
|
||||
if item.get("encrypted_content") or item.get("reasoning_details"):
|
||||
return True
|
||||
return _reasoning_text_len(item) > 0
|
||||
|
||||
|
||||
def _append_tool_to_messages(
|
||||
messages: list[dict],
|
||||
event: dict,
|
||||
@@ -1289,10 +1316,18 @@ def _scrub_incomplete_items(output_items: list[dict]) -> None:
|
||||
|
||||
def _reasoning_text_len(item: dict) -> int:
|
||||
"""Return displayable reasoning text length for diagnostics."""
|
||||
blocks = item.get("summary") or item.get("content") or []
|
||||
if not isinstance(blocks, list):
|
||||
return 0
|
||||
return sum(len(block.get("text") or "") for block in blocks if isinstance(block, dict))
|
||||
total = 0
|
||||
for blocks in (item.get("summary"), item.get("content")):
|
||||
if isinstance(blocks, str):
|
||||
total += len(blocks)
|
||||
elif isinstance(blocks, list):
|
||||
total += sum(
|
||||
len(block.get("text") or "")
|
||||
for block in blocks
|
||||
if isinstance(block, dict)
|
||||
and block.get("type") in ("text", "output_text", "summary_text")
|
||||
)
|
||||
return total
|
||||
|
||||
|
||||
def _output_debug_stats(output_items: list[dict] | None) -> tuple[dict[str, int], int, int]:
|
||||
@@ -2143,6 +2178,11 @@ async def run_chat_task(
|
||||
instructions=system,
|
||||
tools=tools,
|
||||
)
|
||||
provider_type = (
|
||||
"llama.cpp"
|
||||
if provider == "openai" and connection.get("provider_type") == "llama.cpp"
|
||||
else "default"
|
||||
)
|
||||
|
||||
if provider == "anthropic":
|
||||
stream = stream_anthropic(
|
||||
@@ -2150,11 +2190,19 @@ async def run_chat_task(
|
||||
)
|
||||
elif connection.get("api_type") == "responses":
|
||||
stream = stream_openai_responses(
|
||||
form_data, base_url, api_key, request_params=request_params
|
||||
form_data,
|
||||
base_url,
|
||||
api_key,
|
||||
request_params=request_params,
|
||||
provider_type=provider_type,
|
||||
)
|
||||
else:
|
||||
stream = stream_openai_completions(
|
||||
form_data, base_url, api_key, request_params=request_params
|
||||
form_data,
|
||||
base_url,
|
||||
api_key,
|
||||
request_params=request_params,
|
||||
provider_type=provider_type,
|
||||
)
|
||||
|
||||
restart = False
|
||||
|
||||
Reference in new issue
Block a user