YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: full OpenAI-compatible Apple Intelligence API (tools, JSON schema, streaming)
Louis Beaumont4f4a8282157f
diff --git a/Cargo.lock b/Cargo.lockindex 7b3b9c4e5..604092158 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6642,7 +6642,7 @@ dependencies = [[[package]]name = "screenpipe-audio"-version = "0.3.122"+version = "0.3.123"dependencies = ["anyhow","bytemuck",@@ -6695,7 +6695,7 @@ dependencies = [[[package]]name = "screenpipe-core"-version = "0.3.122"+version = "0.3.123"dependencies = ["accessibility","accessibility-sys",@@ -6746,7 +6746,7 @@ dependencies = [[[package]]name = "screenpipe-db"-version = "0.3.122"+version = "0.3.123"dependencies = ["anyhow","chrono",@@ -6770,7 +6770,7 @@ dependencies = [[[package]]name = "screenpipe-events"-version = "0.3.122"+version = "0.3.123"dependencies = ["anyhow","chrono",@@ -6788,7 +6788,7 @@ dependencies = [[[package]]name = "screenpipe-integrations"-version = "0.3.122"+version = "0.3.123"dependencies = ["anyhow","image",@@ -6803,7 +6803,7 @@ dependencies = [[[package]]name = "screenpipe-server"-version = "0.3.122"+version = "0.3.123"dependencies = ["anyhow","async-trait",@@ -6858,6 +6858,7 @@ dependencies = ["tempfile","tokenizers","tokio",+ "tokio-stream","tokio-tungstenite 0.24.0","tokio-util","tower 0.5.2",@@ -6873,7 +6874,7 @@ dependencies = [[[package]]name = "screenpipe-vision"-version = "0.3.122"+version = "0.3.123"dependencies = ["accessibility-sys","anyhow",@@ -8341,9 +8342,9 @@ dependencies = [[[package]]name = "tokio-stream"-version = "0.1.17"+version = "0.1.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047"+checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"dependencies = ["futures-core","pin-project-lite",diff --git a/apps/screenpipe-app-tauri/components/rewind/daily-summary.tsx b/apps/screenpipe-app-tauri/components/rewind/daily-summary.tsxindex 71fb66e7d..f44ade0fe 100644--- a/apps/screenpipe-app-tauri/components/rewind/daily-summary.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/daily-summary.tsx@@ -31,21 +31,98 @@ interface DailySummary {oneLiner: string;}-const SUMMARY_PROMPT = `Analyze this screen activity and audio data. Output ONLY valid JSON, no other text.-{- "timeBreakdown": [{"app": "VS Code", "minutes": 120}],- "keyMoments": [{"time": "2:30 PM", "description": "Merged PR #42"}],- "actionItems": [{"text": "Review draft by Friday", "urgency": "high"}],- "peopleMentioned": [{"name": "Dan", "context": "discussed pricing"}],- "oneLiner": "Mostly coding with a quick meeting about pricing"-}-Rules:-- timeBreakdown: top 5 apps by usage, estimate minutes from context-- keyMoments: max 5, most important events-- actionItems: things to do, "high"/"medium"/"low" urgency-- peopleMentioned: real people names only, not apps-- oneLiner: casual 1-sentence summary of the day-- If not enough data, use fewer items. Empty arrays are fine.`;+const SUMMARY_SYSTEM_PROMPT = `You generate daily summaries of the user's screen activity and audio. You have access to a search tool to query their data. Use it to gather information, then produce a summary.`;++const SUMMARY_JSON_SCHEMA = {+ type: "object",+ properties: {+ oneLiner: { type: "string", description: "casual 1-sentence summary of the day" },+ timeBreakdown: {+ type: "array",+ items: {+ type: "object",+ properties: {+ app: { type: "string" },+ minutes: { type: "number" },+ },+ required: ["app", "minutes"],+ },+ description: "top 5 apps by usage, estimate minutes from context",+ },+ keyMoments: {+ type: "array",+ items: {+ type: "object",+ properties: {+ time: { type: "string" },+ description: { type: "string" },+ },+ required: ["time", "description"],+ },+ description: "max 5 most important events",+ },+ actionItems: {+ type: "array",+ items: {+ type: "object",+ properties: {+ text: { type: "string" },+ urgency: { type: "string", enum: ["high", "medium", "low"] },+ },+ required: ["text", "urgency"],+ },+ description: "things the user needs to do",+ },+ peopleMentioned: {+ type: "array",+ items: {+ type: "object",+ properties: {+ name: { type: "string" },+ context: { type: "string" },+ },+ required: ["name", "context"],+ },+ description: "real people names only, not apps",+ },+ },+ required: ["oneLiner", "timeBreakdown", "keyMoments", "actionItems", "peopleMentioned"],+};++const SEARCH_TOOL = {+ type: "function" as const,+ function: {+ name: "search_screenpipe",+ description: "Search the user's screen recordings (OCR) and audio transcriptions captured by Screenpipe. Returns text content with timestamps and app names.",+ parameters: {+ type: "object",+ properties: {+ content_type: {+ type: "string",+ enum: ["ocr", "audio", "all"],+ description: "Type of content to search. Use 'ocr' for screen text, 'audio' for transcriptions, 'all' for both.",+ },+ start_time: {+ type: "string",+ description: "ISO 8601 start time for the search range",+ },+ end_time: {+ type: "string",+ description: "ISO 8601 end time for the search range",+ },+ limit: {+ type: "integer",+ description: "Maximum number of results to return (1-50)",+ },+ app_name: {+ type: "string",+ description: "Filter by application name",+ },+ },+ required: ["start_time"],+ },+ },+};function getStorageKey(date: string) {return `daily-summary-${date}`;@@ -185,7 +262,7 @@ export function DailySummaryCard({return () => clearInterval(interval);}, [aiAvailable, isVisible, dateStr]);- // ─── Generate Summary ───────────────────────────────────────────────────+ // ─── Generate Summary (Apple Intelligence agent loop) ─────────────────const generateSummary = useCallback(async () => {if (isGenerating) return;@@ -200,93 +277,189 @@ export function DailySummaryCard({return;}- // Fetch the day's dataconst dayStart = new Date(dateStr + "T00:00:00");const dayEnd = new Date(dateStr + "T23:59:59");const now = new Date();const endTime = dayEnd > now ? now : dayEnd;- const params = new URLSearchParams({- content_type: "all",- start_time: dayStart.toISOString(),- end_time: endTime.toISOString(),- limit: "100",- min_length: "20",+ // ── Turn 1: Ask Apple Intelligence to search, providing the tool ──+ const turn1Resp = await fetch(`${API}/ai/chat/completions`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ messages: [+ { role: "system", content: SUMMARY_SYSTEM_PROMPT },+ {+ role: "user",+ content: `Generate a daily summary for ${dateStr}. Search for screen activity (OCR) and audio transcriptions between ${dayStart.toISOString()} and ${endTime.toISOString()}.`,+ },+ ],+ tools: [SEARCH_TOOL],+ }),});- const searchResp = await fetch(`${API}/search?${params}`);- if (!searchResp.ok) throw new Error("Failed to fetch data");- const searchData = await searchResp.json();-- // Build context- const parts: string[] = [];- for (const item of searchData.data || []) {- if (item.type === "OCR") {- const c = item.content;- const text = c?.text?.trim();- if (text) {- const time = new Date(c.timestamp).toLocaleTimeString("en-US", {- hour: "numeric",- minute: "2-digit",- });- parts.push(`[${time}] [${c.app_name || "?"}] ${text}`);- }- } else if (item.type === "Audio") {- const c = item.content;- const text = c?.transcription?.trim();- if (text) {- const time = new Date(c.timestamp).toLocaleTimeString("en-US", {- hour: "numeric",- minute: "2-digit",- });- parts.push(`[${time}] [Audio] ${text}`);+ if (!turn1Resp.ok) throw new Error(`AI error: ${turn1Resp.status}`);+ const turn1Data = await turn1Resp.json();+ const turn1Msg = turn1Data.choices?.[0]?.message;++ // ── Execute tool calls (gather data) ──+ // Build conversation history for the final turn+ const messages: any[] = [+ { role: "system", content: SUMMARY_SYSTEM_PROMPT },+ {+ role: "user",+ content: `Generate a daily summary for ${dateStr}. Search for screen activity (OCR) and audio transcriptions between ${dayStart.toISOString()} and ${endTime.toISOString()}.`,+ },+ ];++ let hasData = false;++ if (turn1Msg?.tool_calls?.length) {+ // Model requested tool calls — execute them+ messages.push({+ role: "assistant",+ content: turn1Msg.content || null,+ tool_calls: turn1Msg.tool_calls,+ });++ for (const tc of turn1Msg.tool_calls) {+ let args: any = {};+ try { args = JSON.parse(tc.function.arguments); } catch {}++ const searchParams = new URLSearchParams({+ content_type: args.content_type || "all",+ start_time: args.start_time || dayStart.toISOString(),+ end_time: args.end_time || endTime.toISOString(),+ limit: String(Math.min(args.limit || 50, 50)),+ min_length: "20",+ });+ if (args.app_name) searchParams.set("app_name", args.app_name);++ const searchResp = await fetch(`${API}/search?${searchParams}`);+ const searchData = searchResp.ok ? await searchResp.json() : { data: [], pagination: { total: 0 } };+ const total = searchData.pagination?.total || 0;++ // Format results compactly+ const entries = (searchData.data || []).map((item: any) => {+ if (item.type === "OCR") {+ const c = item.content;+ const time = new Date(c.timestamp).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });+ return `[${time}] [${c.app_name || "?"}] ${(c.text || "").trim().slice(0, 120)}`;+ } else if (item.type === "Audio") {+ const c = item.content;+ const time = new Date(c.timestamp).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });+ const speaker = c.speaker?.name ? ` (${c.speaker.name})` : "";+ return `[${time}] [Audio${speaker}] ${(c.transcription || "").trim().slice(0, 120)}`;+ }+ return null;+ }).filter(Boolean);++ if (entries.length > 0) hasData = true;++ // Truncate tool result to ~6000 chars to stay within context limits+ let resultText = `Found ${total} entries (showing ${entries.length}):\n${entries.join("\n")}`;+ if (resultText.length > 6000) resultText = resultText.slice(0, 6000);++ messages.push({+ role: "tool",+ tool_call_id: tc.id,+ content: resultText,+ });+ }+ } else {+ // Model didn't use tools — fall back to fetching data ourselves+ const params = new URLSearchParams({+ content_type: "all",+ start_time: dayStart.toISOString(),+ end_time: endTime.toISOString(),+ limit: "50",+ min_length: "20",+ });+ const searchResp = await fetch(`${API}/search?${params}`);+ if (!searchResp.ok) throw new Error("Failed to fetch data");+ const searchData = await searchResp.json();++ const parts: string[] = [];+ for (const item of searchData.data || []) {+ if (item.type === "OCR") {+ const c = item.content;+ const text = c?.text?.trim();+ if (text) {+ const time = new Date(c.timestamp).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });+ parts.push(`[${time}] [${c.app_name || "?"}] ${text.slice(0, 120)}`);+ }+ } else if (item.type === "Audio") {+ const c = item.content;+ const text = c?.transcription?.trim();+ if (text) {+ const time = new Date(c.timestamp).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });+ parts.push(`[${time}] [Audio] ${text.slice(0, 120)}`);+ }}}++ if (parts.length > 0) hasData = true;++ // Use the direct text response as a user message for the final turn+ let context = parts.join("\n");+ if (context.length > 6000) context = context.slice(0, 6000);++ // Reset messages for the fallback path+ messages.length = 0;+ messages.push(+ { role: "system", content: "Analyze this screen activity and audio data. Generate a daily summary." },+ { role: "user", content: `Activity data for ${dateStr}:\n${context}` },+ );}- if (parts.length === 0) {+ if (!hasData) {setError("No activity data for this day");return;}- // Truncate to ~1500 chars- let context = parts.join("\n");- if (context.length > 1500) context = context.slice(0, 1500);-- // Call AI- const aiResp = await fetch(`${API}/ai/chat/completions`, {+ // ── Final turn: Generate JSON summary with schema enforcement ──+ const finalResp = await fetch(`${API}/ai/chat/completions`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({- messages: [- { role: "system", content: SUMMARY_PROMPT },- { role: "user", content: context },- ],+ messages,+ response_format: {+ type: "json_schema",+ json_schema: {+ name: "daily_summary",+ schema: SUMMARY_JSON_SCHEMA,+ },+ },}),});- if (!aiResp.ok) throw new Error(`AI error: ${aiResp.status}`);-- const aiData = await aiResp.json();- let raw = aiData.choices?.[0]?.message?.content || "{}";-- // Strip markdown fences- raw = raw.trim();- if (raw.startsWith("```")) {- raw = raw- .split("\n")- .slice(1)- .filter((l: string) => !l.startsWith("```"))- .join("\n");+ let parsed: any;+ if (!finalResp.ok) {+ // Fall back to text mode if json_schema isn't supported+ const fallbackResp = await fetch(`${API}/ai/chat/completions`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ messages }),+ });+ if (!fallbackResp.ok) throw new Error(`AI error: ${fallbackResp.status}`);+ const fallbackData = await fallbackResp.json();+ let raw = fallbackData.choices?.[0]?.message?.content || "{}";+ raw = raw.trim();+ if (raw.startsWith("```")) {+ raw = raw.split("\n").slice(1).filter((l: string) => !l.startsWith("```")).join("\n");+ }+ parsed = JSON.parse(raw);+ } else {+ const finalData = await finalResp.json();+ const content = finalData.choices?.[0]?.message?.content || "{}";+ parsed = JSON.parse(content);}- const parsed = JSON.parse(raw);-const newSummary: DailySummary = {date: dateStr,generatedAt: new Date().toISOString(),- timeBreakdown: parsed.timeBreakdown || [],- keyMoments: parsed.keyMoments || [],+ timeBreakdown: (parsed.timeBreakdown || []).slice(0, 5),+ keyMoments: (parsed.keyMoments || []).slice(0, 5),actionItems: (parsed.actionItems || []).map((a: any) => ({text: a.text || a.task || "",urgency: ["high", "medium", "low"].includes(a.urgency)diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lockindex fbe311b7b..acdda9a06 100755--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -9007,7 +9007,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "2.0.326"+version = "2.0.329"dependencies = ["anyhow","async-stream",@@ -9100,7 +9100,7 @@ dependencies = [[[package]]name = "screenpipe-audio"-version = "0.3.120"+version = "0.3.123"dependencies = ["anyhow","bytemuck",@@ -9148,7 +9148,7 @@ dependencies = [[[package]]name = "screenpipe-core"-version = "0.3.120"+version = "0.3.123"dependencies = ["accessibility","accessibility-sys",@@ -9199,7 +9199,7 @@ dependencies = [[[package]]name = "screenpipe-db"-version = "0.3.120"+version = "0.3.123"dependencies = ["anyhow","chrono",@@ -9223,7 +9223,7 @@ dependencies = [[[package]]name = "screenpipe-events"-version = "0.3.120"+version = "0.3.123"dependencies = ["anyhow","chrono",@@ -9239,7 +9239,7 @@ dependencies = [[[package]]name = "screenpipe-integrations"-version = "0.3.120"+version = "0.3.123"dependencies = ["anyhow","image 0.25.9",@@ -9254,7 +9254,7 @@ dependencies = [[[package]]name = "screenpipe-server"-version = "0.3.120"+version = "0.3.123"dependencies = ["anyhow","async-trait",@@ -9306,6 +9306,7 @@ dependencies = ["tempfile","tokenizers","tokio",+ "tokio-stream","tokio-util","tower 0.5.3","tower-http 0.5.2",@@ -9319,7 +9320,7 @@ dependencies = [[[package]]name = "screenpipe-vision"-version = "0.3.120"+version = "0.3.123"dependencies = ["accessibility-sys","anyhow",diff --git a/crates/screenpipe-server/Cargo.toml b/crates/screenpipe-server/Cargo.tomlindex c0457f12c..33fa6e462 100644--- a/crates/screenpipe-server/Cargo.toml+++ b/crates/screenpipe-server/Cargo.toml@@ -55,6 +55,7 @@ sentry = { workspace = true }# Serveraxum = { version = "0.7.5", features = ["ws"] }tokio = { version = "1.15", features = ["full", "tracing"] }+tokio-stream = "0.1"tower-http = { version = "0.5.2", features = ["cors", "trace"] }# Logdiff --git a/crates/screenpipe-server/src/apple_intelligence_api.rs b/crates/screenpipe-server/src/apple_intelligence_api.rsindex e5b9111f1..e5c62fa1f 100644--- a/crates/screenpipe-server/src/apple_intelligence_api.rs+++ b/crates/screenpipe-server/src/apple_intelligence_api.rs@@ -1,34 +1,127 @@-//! Generic OpenAI-compatible API wrapping Apple Foundation Models.+//! OpenAI-compatible API wrapping Apple Foundation Models.//!-//! Thin layer: HTTP in → generate_text() via Swift FFI → HTTP out.-//! No application-specific logic — just an AI endpoint anyone can use.+//! Full-featured endpoint with tool calling, JSON schema generation, and streaming.//! Feature-gated behind `apple-intelligence` (macOS aarch64 only).-use axum::{http::StatusCode, Json};-use screenpipe_apple_intelligence::{check_availability, generate_text, prewarm, Availability};+use axum::{+ http::StatusCode,+ response::{+ sse::{Event, Sse},+ IntoResponse,+ },+ Json,+};+use screenpipe_apple_intelligence::{check_availability, generate_json, generate_text, prewarm, Availability};use serde::{Deserialize, Serialize};+use std::convert::Infallible;use std::sync::Once;+use tokio_stream::StreamExt as _;use tracing::{info, warn};static PREWARM: Once = Once::new();+const MODEL_ID: &str = "apple-intelligence";++fn ensure_prewarm() {+ PREWARM.call_once(|| {+ info!("prewarming apple intelligence model");+ if let Err(e) = prewarm() {+ warn!("prewarm failed: {}", e);+ }+ });+}++fn now_ts() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs()+}++fn make_request_id() -> String {+ format!(+ "chatcmpl-{}",+ &uuid::Uuid::new_v4().to_string().replace('-', "")[..24]+ )+}+// ─── OpenAI-compatible types ────────────────────────────────────────────────#[derive(Debug, Deserialize)]pub struct ChatCompletionRequest {messages: Vec<Message>,#[serde(default)]+ stream: bool,+ #[serde(default)]#[allow(dead_code)]temperature: Option<f64>,#[serde(default)]#[allow(dead_code)]max_tokens: Option<u32>,+ #[serde(default)]+ tools: Option<Vec<ToolDef>>,+ #[serde(default)]+ #[allow(dead_code)]+ tool_choice: Option<serde_json::Value>,+ /// OpenAI-compatible response_format. Use {"type": "json_schema", "json_schema": {"schema": ...}}+ /// to get guaranteed valid JSON via Apple's GenerationSchema.+ #[serde(default)]+ response_format: Option<ResponseFormat>,}#[derive(Debug, Deserialize, Serialize, Clone)]pub struct Message {role: String,- content: String,+ #[serde(default)]+ content: Option<serde_json::Value>,+ #[serde(skip_serializing_if = "Option::is_none")]+ tool_calls: Option<Vec<ToolCall>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ tool_call_id: Option<String>,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct ToolDef {+ r#type: String,+ function: ToolFunction,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct ToolFunction {+ name: String,+ #[serde(default)]+ description: Option<String>,+ #[serde(default)]+ parameters: Option<serde_json::Value>,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct ToolCall {+ id: String,+ r#type: String,+ function: ToolCallFunction,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct ToolCallFunction {+ name: String,+ arguments: String,+}++#[derive(Debug, Deserialize)]+pub struct ResponseFormat {+ r#type: String,+ /// For "json_schema" type: {"name": "...", "schema": {...}}+ #[serde(default)]+ json_schema: Option<JsonSchemaFormat>,+}++#[derive(Debug, Deserialize)]+pub struct JsonSchemaFormat {+ #[serde(default)]+ #[allow(dead_code)]+ name: Option<String>,+ schema: serde_json::Value,}#[derive(Serialize)]@@ -44,10 +137,18 @@ pub struct ChatCompletionResponse {#[derive(Serialize)]pub struct Choice {index: u32,- message: Message,+ message: ResponseMessage,finish_reason: String,}+#[derive(Serialize)]+pub struct ResponseMessage {+ role: String,+ content: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ tool_calls: Option<Vec<ToolCall>>,+}+#[derive(Serialize)]pub struct Usage {prompt_tokens: u32,@@ -55,6 +156,32 @@ pub struct Usage {total_tokens: u32,}+#[derive(Serialize)]+pub struct ChatCompletionChunk {+ id: String,+ object: String,+ created: u64,+ model: String,+ choices: Vec<StreamChoice>,+}++#[derive(Serialize)]+pub struct StreamChoice {+ index: u32,+ delta: Delta,+ finish_reason: Option<String>,+}++#[derive(Serialize)]+pub struct Delta {+ #[serde(skip_serializing_if = "Option::is_none")]+ role: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ content: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ tool_calls: Option<Vec<ToolCall>>,+}+#[derive(Serialize)]pub struct StatusResponse {available: bool,@@ -62,6 +189,170 @@ pub struct StatusResponse {model: String,}+// ─── Prompt building (handles tools + multi-content messages) ───────────────++fn build_prompt_from_messages(+ messages: &[Message],+ tools: &Option<Vec<ToolDef>>,+) -> (Option<String>, String) {+ let mut system_parts: Vec<String> = Vec::new();+ let mut conversation: Vec<String> = Vec::new();++ // Inject tool descriptions into system prompt+ if let Some(tools) = tools {+ if !tools.is_empty() {+ let mut tool_desc = String::from("You have access to the following tools:\n\n");+ for tool in tools {+ tool_desc.push_str(&format!("### {}\n", tool.function.name));+ if let Some(desc) = &tool.function.description {+ tool_desc.push_str(&format!("{}\n", desc));+ }+ if let Some(params) = &tool.function.parameters {+ tool_desc.push_str(&format!(+ "Parameters: {}\n",+ serde_json::to_string(params).unwrap_or_default()+ ));+ }+ tool_desc.push('\n');+ }+ tool_desc.push_str(+ "To call a tool, respond with a JSON block in this exact format:\n\+ ```tool_call\n{\"name\": \"tool_name\", \"arguments\": {\"arg1\": \"value1\"}}\n```\n\n\+ You can call multiple tools. After tool results, continue your response.\n\+ If no tool is needed, respond normally with text.",+ );+ system_parts.push(tool_desc);+ }+ }++ for msg in messages {+ match msg.role.as_str() {+ "system" => {+ if let Some(content) = &msg.content {+ let text = content_to_text(content);+ if !text.is_empty() {+ system_parts.push(text);+ }+ }+ }+ "user" => {+ if let Some(content) = &msg.content {+ let text = content_to_text(content);+ if !text.is_empty() {+ conversation.push(format!("User: {}", text));+ }+ }+ }+ "assistant" => {+ if let Some(content) = &msg.content {+ let text = content_to_text(content);+ if !text.is_empty() {+ conversation.push(format!("Assistant: {}", text));+ }+ }+ if let Some(tool_calls) = &msg.tool_calls {+ for tc in tool_calls {+ conversation.push(format!(+ "Assistant called tool {}: {}",+ tc.function.name, tc.function.arguments+ ));+ }+ }+ }+ "tool" => {+ if let Some(content) = &msg.content {+ let text = content_to_text(content);+ let id = msg.tool_call_id.as_deref().unwrap_or("?");+ conversation.push(format!("Tool result ({}): {}", id, text));+ }+ }+ _ => {}+ }+ }++ let instructions = if system_parts.is_empty() {+ None+ } else {+ Some(system_parts.join("\n\n"))+ };+ (instructions, conversation.join("\n\n"))+}++/// Extract text from OpenAI content (string or array of content parts).+fn content_to_text(content: &serde_json::Value) -> String {+ match content {+ serde_json::Value::String(s) => s.clone(),+ serde_json::Value::Array(parts) => parts+ .iter()+ .filter_map(|p| {+ if p.get("type").and_then(|t| t.as_str()) == Some("text") {+ p.get("text").and_then(|t| t.as_str()).map(String::from)+ } else {+ None+ }+ })+ .collect::<Vec<_>>()+ .join("\n"),+ other => other.to_string(),+ }+}++// ─── Tool call parsing ──────────────────────────────────────────────────────++fn parse_tool_calls(text: &str) -> (Option<String>, Vec<ToolCall>) {+ let mut tool_calls = Vec::new();+ let mut remaining = String::new();+ let mut in_block = false;+ let mut block = String::new();++ for line in text.lines() {+ if line.trim() == "```tool_call" {+ in_block = true;+ block.clear();+ continue;+ }+ if in_block && line.trim() == "```" {+ in_block = false;+ if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&block) {+ if let (Some(name), Some(args)) = (+ parsed.get("name").and_then(|n| n.as_str()),+ parsed.get("arguments"),+ ) {+ tool_calls.push(ToolCall {+ id: format!(+ "call_{}",+ &uuid::Uuid::new_v4().to_string().replace('-', "")[..24]+ ),+ r#type: "function".to_string(),+ function: ToolCallFunction {+ name: name.to_string(),+ arguments: serde_json::to_string(args).unwrap_or_default(),+ },+ });+ }+ }+ continue;+ }+ if in_block {+ block.push_str(line);+ block.push('\n');+ } else {+ remaining.push_str(line);+ remaining.push('\n');+ }+ }++ let content = remaining.trim().to_string();+ (+ if content.is_empty() {+ None+ } else {+ Some(content)+ },+ tool_calls,+ )+}+// ─── Handlers ───────────────────────────────────────────────────────────────/// GET /ai/status@@ -70,68 +361,204 @@ pub async fn ai_status() -> Json<StatusResponse> {Json(StatusResponse {available: avail == Availability::Available,status: avail.to_string(),- model: "apple-intelligence".to_string(),+ model: MODEL_ID.to_string(),})}/// POST /ai/chat/completions — OpenAI-compatible chat completions+///+/// Supports:+/// - Tool calling (tools array → injected into system prompt → parsed from output)+/// - JSON schema mode (response_format.type = "json_schema" → fm_generate_json)+/// - Streaming (stream: true → SSE)+/// - Multi-content messages (string or array of content parts)+/// - Tool result messages (role: "tool")pub async fn chat_completions(Json(req): Json<ChatCompletionRequest>,-) -> Result<Json<ChatCompletionResponse>, (StatusCode, Json<serde_json::Value>)> {- // Prewarm on first call- PREWARM.call_once(|| {- info!("prewarming apple intelligence model");- if let Err(e) = prewarm() {- warn!("prewarm failed: {}", e);+) -> Result<axum::response::Response, (StatusCode, Json<serde_json::Value>)> {+ ensure_prewarm();++ let (instructions, prompt) = build_prompt_from_messages(&req.messages, &req.tools);+ let has_tools = req.tools.as_ref().map_or(false, |t| !t.is_empty());+ let prompt_len = prompt.len();++ // Check if JSON schema mode is requested+ let json_schema = req.response_format.as_ref().and_then(|rf| {+ if rf.r#type == "json_schema" {+ rf.json_schema+ .as_ref()+ .map(|js| serde_json::to_string(&js.schema).unwrap_or_default())+ } else if rf.r#type == "json_object" {+ // Basic JSON mode without schema — just use text generation+ // (the model will try to output JSON based on the prompt)+ None+ } else {+ None}});- // Build prompt from messages- let mut system: Option<String> = None;- let mut conversation = Vec::new();+ info!(+ "apple intelligence chat: {} chars, tools: {}, json_schema: {}, stream: {}",+ prompt_len,+ has_tools,+ json_schema.is_some(),+ req.stream+ );- for msg in &req.messages {- match msg.role.as_str() {- "system" => system = Some(msg.content.clone()),- "user" => conversation.push(format!("User: {}", msg.content)),- "assistant" => conversation.push(format!("Assistant: {}", msg.content)),- _ => {}- }- }+ // Generate response — either JSON-constrained or plain text+ let (response_text, is_json) = if let Some(schema_str) = json_schema {+ let result = tokio::task::spawn_blocking(move || {+ generate_json(instructions.as_deref(), &prompt, &schema_str)+ })+ .await+ .map_err(|e| mk_err(&e.to_string()))?+ .map_err(|e| mk_err(&e.to_string()))?;- let prompt = conversation.join("\n\n");- let prompt_len = prompt.len();+ info!(+ "apple intelligence json response: {:.0}ms",+ result.metrics.total_time_ms+ );+ (result.json.to_string(), true)+ } else {+ let result = tokio::task::spawn_blocking(move || {+ generate_text(instructions.as_deref(), &prompt)+ })+ .await+ .map_err(|e| mk_err(&e.to_string()))?+ .map_err(|e| mk_err(&e.to_string()))?;- // Call Foundation Models (blocking FFI → spawn_blocking)- let result = tokio::task::spawn_blocking(move || {- generate_text(system.as_deref(), &prompt)- })- .await- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))))?- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()}))))?;+ info!(+ "apple intelligence text response: {} chars, {:.0}ms",+ result.text.len(),+ result.metrics.total_time_ms+ );+ (result.text, false)+ };- let now = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_secs();-- Ok(Json(ChatCompletionResponse {- id: format!("chatcmpl-{}", now),- object: "chat.completion".to_string(),- created: now,- model: "apple-intelligence".to_string(),- choices: vec![Choice {- index: 0,- message: Message {- role: "assistant".to_string(),- content: result.text,+ let request_id = make_request_id();+ let est_prompt_tokens = (prompt_len / 4) as u32;+ let est_completion_tokens = (response_text.len() / 4) as u32;++ // Parse tool calls from output if tools were provided+ let (text_content, tool_calls) = if has_tools && !is_json {+ parse_tool_calls(&response_text)+ } else {+ (Some(response_text), vec![])+ };++ let finish_reason = if tool_calls.is_empty() {+ "stop"+ } else {+ "tool_calls"+ };++ if req.stream {+ let chunks = build_stream_chunks(+ &request_id,+ text_content.clone(),+ if tool_calls.is_empty() {+ None+ } else {+ Some(tool_calls)+ },+ finish_reason,+ );++ let stream = tokio_stream::iter(chunks.into_iter().map(|c| {+ Ok::<_, Infallible>(Event::default().data(serde_json::to_string(&c).unwrap()))+ }))+ .chain(tokio_stream::once(Ok(Event::default().data("[DONE]"))));++ Ok(Sse::new(stream)+ .keep_alive(axum::response::sse::KeepAlive::default())+ .into_response())+ } else {+ Ok(Json(ChatCompletionResponse {+ id: request_id,+ object: "chat.completion".to_string(),+ created: now_ts(),+ model: MODEL_ID.to_string(),+ choices: vec![Choice {+ index: 0,+ message: ResponseMessage {+ role: "assistant".to_string(),+ content: text_content,+ tool_calls: if tool_calls.is_empty() {+ None+ } else {+ Some(tool_calls)+ },+ },+ finish_reason: finish_reason.to_string(),+ }],+ usage: Usage {+ prompt_tokens: est_prompt_tokens,+ completion_tokens: est_completion_tokens,+ total_tokens: est_prompt_tokens + est_completion_tokens,},- finish_reason: "stop".to_string(),- }],- usage: Usage {- prompt_tokens: (prompt_len / 4) as u32,- completion_tokens: 0, // we don't track this- total_tokens: (prompt_len / 4) as u32,+ })+ .into_response())+ }+}++fn build_stream_chunks(+ request_id: &str,+ content: Option<String>,+ tool_calls: Option<Vec<ToolCall>>,+ finish_reason: &str,+) -> Vec<ChatCompletionChunk> {+ vec![+ ChatCompletionChunk {+ id: request_id.to_string(),+ object: "chat.completion.chunk".to_string(),+ created: now_ts(),+ model: MODEL_ID.to_string(),+ choices: vec![StreamChoice {+ index: 0,+ delta: Delta {+ role: Some("assistant".to_string()),+ content: None,+ tool_calls: None,+ },+ finish_reason: None,+ }],+ },+ ChatCompletionChunk {+ id: request_id.to_string(),+ object: "chat.completion.chunk".to_string(),+ created: now_ts(),+ model: MODEL_ID.to_string(),+ choices: vec![StreamChoice {+ index: 0,+ delta: Delta {+ role: None,+ content,+ tool_calls,+ },+ finish_reason: None,+ }],},- }))+ ChatCompletionChunk {+ id: request_id.to_string(),+ object: "chat.completion.chunk".to_string(),+ created: now_ts(),+ model: MODEL_ID.to_string(),+ choices: vec![StreamChoice {+ index: 0,+ delta: Delta {+ role: None,+ content: None,+ tool_calls: None,+ },+ finish_reason: Some(finish_reason.to_string()),+ }],+ },+ ]+}++fn mk_err(msg: &str) -> (StatusCode, Json<serde_json::Value>) {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(serde_json::json!({"error": {"message": msg}})),+ )}