File size: 6,508 Bytes
507973e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""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,
)