Add LLM tool calling for creating tasks, notes, and searching from chat

Ollama tool/function calling integration allows the LLM to create tasks,
create notes, and search existing notes on behalf of the user during chat.
Multi-round tool loop (max 5 rounds) lets the model execute tools then
produce a natural language response. Tool results are persisted in a new
JSONB column on messages and rendered as compact cards with linked titles.

- Migration 0013: add tool_calls JSONB column to messages
- New services/tools.py: tool definitions + execute_tool dispatcher
- llm.py: ChatChunk dataclass, stream_chat_with_tools(), date in system prompt
- generation_task.py: multi-round tool call loop with SSE tool_call events
- Frontend: ToolCallRecord type, streamingToolCalls in store, ToolCallCard
  component, rendering in ChatMessage and ChatView streaming bubble

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-14 23:34:36 -05:00
parent f089b16080
commit 8996b45e50
11 changed files with 522 additions and 29 deletions
+58 -1
View File
@@ -2,6 +2,8 @@ import json
import logging
import re
from collections.abc import AsyncGenerator
from dataclasses import dataclass, field
from typing import Literal
import httpx
@@ -98,6 +100,55 @@ async def stream_chat(
break
@dataclass
class ChatChunk:
"""A chunk yielded by stream_chat_with_tools."""
type: Literal["content", "tool_calls", "done"]
content: str = ""
tool_calls: list[dict] | None = None
async def stream_chat_with_tools(
messages: list[dict],
model: str,
tools: list[dict] | None = None,
) -> AsyncGenerator[ChatChunk, None]:
"""Stream chat completion from Ollama with tool support.
Yields ChatChunk objects. If the model returns tool_calls, a
ChatChunk(type="tool_calls") is yielded. Always ends with
ChatChunk(type="done").
"""
payload: dict = {"model": model, "messages": messages, "stream": True}
if tools:
payload["tools"] = tools
async with httpx.AsyncClient(timeout=httpx.Timeout(1800.0, connect=30.0, read=300.0)) as client:
async with client.stream(
"POST",
f"{Config.OLLAMA_URL}/api/chat",
json=payload,
) as resp:
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line.strip():
continue
data = json.loads(line)
msg = data.get("message", {})
# Content chunks
chunk = msg.get("content", "")
if chunk:
yield ChatChunk(type="content", content=chunk)
# Check for tool calls on done
if data.get("done"):
tool_calls = msg.get("tool_calls")
if tool_calls:
yield ChatChunk(type="tool_calls", tool_calls=tool_calls)
yield ChatChunk(type="done")
break
async def generate_completion(messages: list[dict], model: str) -> str:
"""Non-streaming chat completion, returns full response text."""
async with httpx.AsyncClient(timeout=httpx.Timeout(1800.0, connect=30.0, read=300.0)) as client:
@@ -166,11 +217,17 @@ async def build_context(
which notes were included as context.
"""
exclude_set = set(exclude_note_ids or [])
from datetime import date as date_type
assistant_name = await get_setting(user_id, "assistant_name", "Fable")
today = date_type.today().isoformat()
system_parts = [
f"You are a helpful assistant named {assistant_name}, integrated into a note-taking and task-tracking app called Fabled Assistant. "
"Help users with their notes, tasks, and general questions. "
"When note context is provided, use it to give relevant answers."
"When note context is provided, use it to give relevant answers. "
f"Today's date is {today}. "
"You have tools available to create tasks, create notes, and search the user's notes. "
"Use them when the user asks you to create, add, or find tasks and notes. "
"For relative dates like 'Friday' or 'next week', resolve them to YYYY-MM-DD format."
]
context_meta: dict = {