langchain
Version:
Typescript bindings for langchain
1 lines • 13 kB
Source Map (JSON)
{"version":3,"file":"todoListMiddleware.cjs","names":["z","tool","Command","ToolMessage","createMiddleware","AIMessage"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { AIMessage, ToolMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../index.js\";\n\n/**\n * Description for the write_todos tool\n * Ported exactly from Python WRITE_TODOS_DESCRIPTION\n */\nconst WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress and organize complex tasks.\n\nOnly use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the task directly.\n\n## When to Use This Tool\n\nUse this tool in these scenarios:\n\n1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions\n2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations\n3. User explicitly requests todo list - When the user directly asks you to use the todo list\n4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\n5. The plan may need future revisions or updates based on results from the first few steps\n\n## How to Use This Tool\n\n1. When you start working on a task - Mark it as in_progress BEFORE beginning work.\n2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.\n3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.\n4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.\n\n## When NOT to Use This Tool\n\nIt is important to skip using this tool when:\n1. There is only a single, straightforward task\n2. The task is trivial and tracking it provides no benefit\n3. The task can be completed in less than 3 trivial steps\n4. The task is purely conversational or informational\n\n## Task States and Management\n\n1. **Task States**: Use these states to track progress:\n - pending: Task not yet started\n - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)\n - completed: Task finished successfully\n\n2. **Task Management**:\n - Update task status in real-time as you work\n - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)\n - Complete current tasks before starting new ones\n - Remove tasks that are no longer relevant from the list entirely\n - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.\n - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress.\n\n3. **Task Completion Requirements**:\n - ONLY mark a task as completed when you have FULLY accomplished it\n - If you encounter errors, blockers, or cannot finish, keep the task as in_progress\n - When blocked, create a new task describing what needs to be resolved\n - Never mark a task as completed if:\n - There are unresolved issues or errors\n - Work is partial or incomplete\n - You encountered blockers that prevent completion\n - You couldn't find necessary resources or dependencies\n - Quality standards haven't been met\n\n4. **Task Breakdown**:\n - Create specific, actionable items\n - Break complex tasks into smaller, manageable steps\n - Use clear, descriptive task names\n\nBeing proactive with task management ensures you complete all requirements successfully\nRemember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.\n\n## When You Finish\n\n\\`write_todos\\` tracks your work; it does not deliver the answer. Whatever the user asked for — computations, summaries, comparisons, data — must appear as text content in a message after your final \\`write_todos\\` call. Marking the last todo complete is not itself an answer to the user.`;\n\nexport const TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = `## \\`write_todos\\`\n\nYou have access to the \\`write_todos\\` tool to help you manage and plan complex objectives.\nUse this tool for complex objectives to ensure that you are tracking each necessary step.\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\n\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\n\n## Important To-Do List Usage Notes to Remember\n\n- The \\`write_todos\\` tool should never be called multiple times in parallel.\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.\n\n## Finishing a task\n\nWhen you finish all work, write your final answer in the message AFTER your last \\`write_todos\\` call — not in the same turn as that call. Start the final message with the substantive content the user asked for — the data, computation, summary, or analysis. The user wants the result, not confirmation that the work is done.`;\n\nconst TodoStatus = z\n .enum([\"pending\", \"in_progress\", \"completed\"])\n .describe(\"Status of the todo\");\nconst TodoSchema = z.object({\n content: z.string().describe(\"Content of the todo item\"),\n status: TodoStatus,\n});\nexport type Todo = z.infer<typeof TodoSchema>;\n\nconst stateSchema = z.object({\n todos: z.array(TodoSchema).default([]),\n});\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\n\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively. It also enforces that the\n * `write_todos` tool is called at most once per model turn, since the tool replaces\n * the entire todo list and parallel calls would create ambiguity about precedence.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport function todoListMiddleware(options?: TodoListMiddlewareOptions) {\n /**\n * Write todos tool - manages todo list with Command return\n */\n const writeTodos = tool(\n ({ todos }, config) => {\n return new Command({\n update: {\n todos,\n messages: [\n new ToolMessage({\n content: `Updated todo list to ${JSON.stringify(todos)}`,\n tool_call_id: config.toolCall?.id as string,\n name: \"write_todos\",\n }),\n ],\n },\n });\n },\n {\n name: \"write_todos\",\n description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION,\n schema: z.object({\n todos: z.array(TodoSchema).describe(\"List of todo items to update\"),\n }),\n }\n );\n\n return createMiddleware({\n name: \"todoListMiddleware\",\n stateSchema,\n tools: [writeTodos],\n wrapModelCall: (request, handler) =>\n handler({\n ...request,\n systemMessage: request.systemMessage.concat(\n `\\n\\n${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`\n ),\n }),\n afterModel: (state) => {\n /**\n * Check for parallel write_todos tool calls and return errors if detected.\n *\n * The todo list is designed to be updated at most once per model turn. Since\n * the `write_todos` tool replaces the entire todo list with each call, making\n * multiple parallel calls would create ambiguity about which update should take\n * precedence. This method prevents such conflicts by rejecting any response that\n * contains multiple write_todos tool calls.\n */\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return undefined;\n }\n\n /**\n * Find the last AI message\n */\n const lastAiMsg = [...messages]\n .reverse()\n .find((msg) => AIMessage.isInstance(msg));\n if (\n !lastAiMsg ||\n !lastAiMsg.tool_calls ||\n lastAiMsg.tool_calls.length === 0\n ) {\n return undefined;\n }\n\n /**\n * Count write_todos tool calls\n */\n const writeTodosCalls = lastAiMsg.tool_calls.filter(\n (tc) => tc.name === writeTodos.name\n );\n\n if (writeTodosCalls.length > 1) {\n /**\n * Create error tool messages for all write_todos calls\n */\n const errorMessages = writeTodosCalls.map(\n (tc) =>\n new ToolMessage({\n content:\n \"Error: The `write_todos` tool should never be called multiple times \" +\n \"in parallel. Please call it only once per model invocation to update \" +\n \"the todo list.\",\n tool_call_id: tc.id as string,\n name: \"write_todos\",\n status: \"error\",\n })\n );\n\n /**\n * Keep the tool calls in the AI message but return error messages\n * This follows the same pattern as HumanInTheLoopMiddleware\n */\n return { messages: errorMessages };\n }\n\n return undefined;\n },\n });\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEhC,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;AAmBlD,MAAM,aAAaA,OAAAA,EAChB,KAAK;CAAC;CAAW;CAAe;AAAW,CAAC,CAAC,CAC7C,SAAS,oBAAoB;AAChC,MAAM,aAAaA,OAAAA,EAAE,OAAO;CAC1B,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,0BAA0B;CACvD,QAAQ;AACV,CAAC;AAGD,MAAM,cAAcA,OAAAA,EAAE,OAAO,EAC3B,OAAOA,OAAAA,EAAE,MAAM,UAAU,CAAC,CAAC,QAAQ,CAAC,CAAC,EACvC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDD,SAAgB,mBAAmB,SAAqC;;;;CAItE,MAAM,cAAA,GAAaC,sBAAAA,KAAAA,EAChB,EAAE,SAAS,WAAW;EACrB,OAAO,IAAIC,qBAAAA,QAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAIC,yBAAAA,YAAY;IACd,SAAS,wBAAwB,KAAK,UAAU,KAAK;IACrD,cAAc,OAAO,UAAU;IAC/B,MAAM;GACR,CAAC,CACH;EACF,EACF,CAAC;CACH,GACA;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQH,OAAAA,EAAE,OAAO,EACf,OAAOA,OAAAA,EAAE,MAAM,UAAU,CAAC,CAAC,SAAS,8BAA8B,EACpE,CAAC;CACH,CACF;CAEA,OAAOI,mBAAAA,iBAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAU;EAClB,gBAAgB,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,OAAO,SAAS,gBAAA,+2CAClB;EACF,CAAC;EACH,aAAa,UAAU;;;;;;;;;;GAUrB,MAAM,WAAW,MAAM;GACvB,IAAI,CAAC,YAAY,SAAS,WAAW,GACnC;;;;GAMF,MAAM,YAAY,CAAC,GAAG,QAAQ,CAAC,CAC5B,QAAQ,CAAC,CACT,MAAM,QAAQC,yBAAAA,UAAU,WAAW,GAAG,CAAC;GAC1C,IACE,CAAC,aACD,CAAC,UAAU,cACX,UAAU,WAAW,WAAW,GAEhC;;;;GAMF,MAAM,kBAAkB,UAAU,WAAW,QAC1C,OAAO,GAAG,SAAS,WAAW,IACjC;GAEA,IAAI,gBAAgB,SAAS;;;;;GAqB3B,OAAO,EAAE,UAjBa,gBAAgB,KACnC,OACC,IAAIF,yBAAAA,YAAY;IACd,SACE;IAGF,cAAc,GAAG;IACjB,MAAM;IACN,QAAQ;GACV,CAAC,CAO0B,EAAE;EAIrC;CACF,CAAC;AACH"}