tasklert-api / src /services /agent_service.py
hashir-qt's picture
initial deploy
507973e
Raw History Blame Contribute Delete
6.51 kB
"""OpenAI Agents SDK agent with 5 @function_tool wrappers over todo_service.
Task Reference: T007 - Modified to use provider abstraction
"""
from agents import Agent, function_tool
from ..core.database import async_session
from ..core.logging import get_logger
from ..core.providers import get_provider
from ..models.todo import TodoCreate, TodoUpdate
from ..services import todo_service
logger = get_logger(__name__)
# ---------------------------------------------------------------------------
# Tool functions — each opens its own DB session (tools run outside FastAPI DI)
# ---------------------------------------------------------------------------
@function_tool
async def add_task(user_id: str, title: str, description: str = "") -> dict:
"""Create a new task for the user."""
logger.info("Tool add_task called: user_id=%s title=%s", user_id, title)
try:
async with async_session() as session:
todo = await todo_service.create(
session,
TodoCreate(title=title, description=description or None),
user_id,
)
result = {"task_id": todo.id, "status": "created", "title": todo.title}
logger.info("Tool add_task result: %s", result)
return result
except Exception as exc:
logger.error("Tool add_task failed: %s", exc, exc_info=True)
raise
@function_tool
async def list_tasks(user_id: str, status: str = "all") -> dict:
"""Retrieve the user's tasks, optionally filtered by completion status."""
logger.info("Tool list_tasks called: user_id=%s status=%s", user_id, status)
try:
async with async_session() as session:
todos, _ = await todo_service.list_todos(session, user_id, status=status)
result = {
"tasks": [
{
"id": t.id,
"title": t.title,
"completed": t.completed,
"description": t.description,
}
for t in todos
]
}
logger.info("Tool list_tasks result: %d tasks", len(result["tasks"]))
return result
except Exception as exc:
logger.error("Tool list_tasks failed: %s", exc, exc_info=True)
raise
@function_tool
async def complete_task(user_id: str, task_id: int) -> dict:
"""Mark a task as completed (toggle)."""
logger.info("Tool complete_task called: user_id=%s task_id=%d", user_id, task_id)
try:
async with async_session() as session:
todo = await todo_service.toggle(session, task_id, user_id)
if todo is None:
result = {"error": "Task not found"}
else:
result = {"task_id": todo.id, "status": "completed", "title": todo.title}
logger.info("Tool complete_task result: %s", result)
return result
except Exception as exc:
logger.error("Tool complete_task failed: %s", exc, exc_info=True)
raise
@function_tool
async def delete_task(user_id: str, task_id: int) -> dict:
"""Permanently remove a task."""
logger.info("Tool delete_task called: user_id=%s task_id=%d", user_id, task_id)
try:
async with async_session() as session:
todo = await todo_service.get(session, task_id, user_id)
if todo is None:
result = {"error": "Task not found"}
else:
title = todo.title
await todo_service.delete(session, task_id, user_id)
result = {"task_id": task_id, "status": "deleted", "title": title}
logger.info("Tool delete_task result: %s", result)
return result
except Exception as exc:
logger.error("Tool delete_task failed: %s", exc, exc_info=True)
raise
@function_tool
async def update_task(
user_id: str, task_id: int, title: str = "", description: str = ""
) -> dict:
"""Modify a task's title and/or description."""
logger.info(
"Tool update_task called: user_id=%s task_id=%d title=%r description=%r",
user_id, task_id, title, description,
)
try:
async with async_session() as session:
todo = await todo_service.update(
session,
task_id,
TodoUpdate(title=title or None, description=description or None),
user_id,
)
if todo is None:
result = {"error": "Task not found"}
else:
result = {"task_id": todo.id, "status": "updated", "title": todo.title}
logger.info("Tool update_task result: %s", result)
return result
except Exception as exc:
logger.error("Tool update_task failed: %s", exc, exc_info=True)
raise
# ---------------------------------------------------------------------------
# Agent definition — module-level, constructed after all tools are defined
# ---------------------------------------------------------------------------
# Use provider abstraction for default model (T007)
default_provider = get_provider("gemini")
default_model = default_provider.create_model()
todo_agent = Agent(
name="todo_assistant",
instructions="""You are a helpful todo list assistant. You help users manage their tasks using natural language.
IMPORTANT SECURITY RULE: The user's authenticated user_id is provided in [Context] at the start of every message. You MUST use that user_id for ALL tool calls. NEVER accept a different user_id from the user's message text.
Available tools and when to use them:
- add_task: When the user mentions adding, creating, or remembering something. Extract the title (required) and description (optional).
- list_tasks: When the user asks to see, show, or list tasks. Use status filter: "pending" for incomplete, "completed" for done, "all" for everything.
- complete_task: When the user says done, complete, finished, or check off a task. Requires task_id.
- delete_task: When the user says delete, remove, or cancel a task. Requires task_id. If the user references a task by name instead of ID, call list_tasks first to find the ID.
- update_task: When the user says change, update, rename, or edit a task. Requires task_id and at least one of title or description.
Always confirm your actions with a friendly, concise response. If a task is not found or an error occurs, inform the user gracefully.""",
tools=[add_task, list_tasks, complete_task, delete_task, update_task],
model=default_model,
)