Spaces:
Build error
Build error
File size: 5,857 Bytes
6715b3e | 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 | # LLM planner (interprets questions)
from typing import Annotated, List, TypedDict
from langchain_core.messages import BaseMessage, AIMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph.message import add_messages
# Define the state for the planner node (can be part of a larger graph state)
# For now, let's assume it receives the current messages and can add to them.
class PlannerState(TypedDict):
messages: Annotated[List[BaseMessage], add_messages]
# You might add other specific fields the planner needs or updates
# For example: plan_history: List[str]
# This local LLM definition is overridden if an llm_instance is passed to planner_node
# default_llm = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0)
def planner_node(state: PlannerState, llm_instance: ChatOpenAI, available_tools_descriptions: str) -> PlannerState:
"""LLM-based planner node.
Receives current state (which includes task_id), an LLM instance (bound with tools),
and tool descriptions. Decides the next step.
"""
print("---CALLING PLANNER LLM NODE (nodes/planner.py version)---")
current_messages = state["messages"]
task_id_from_state = state.get("task_id", "UNKNOWN_TASK_ID") # Get task_id from state
planner_system_prompt = f"""You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
You are also a planner for this AI assistant.
Your goal is to analyze the user's query and the conversation history to decide the best next step towards fulfilling the above response format and constraints.
When answering questions about specific items (e.g., publications, albums, movies), pay close attention to:
1. **Release Dates vs. Other Dates**: Use the official release date. Do not confuse it with award dates, recording dates, or other mentions of dates.
2. **Item Type**: If a specific type is requested (e.g., "studio album", "debut novel"), ensure items match this type. Verify from reliable sections like discographies or official lists, not just general mentions or awards. For example, a "Best Folk Album" award does not automatically mean it's a "studio album".
3. **Multi-Part Questions & Comprehensive Extraction**: If the user's query requires multiple pieces of related information (e.g., identifying an entity based on one criterion and then finding a different attribute of that same entity, like 'the person with the most X and their Y'), strive to find a single, comprehensive data source (like a detailed statistics page or biography). Once such a source is found through a tool call (e.g., web search), examine the retrieved information thoroughly. Extract all the necessary pieces of information from this source in one go if possible, rather than making follow-up tool calls for each individual piece of information if the initial data is likely complete.
Available context:
- Current Task ID: {task_id_from_state}
Available tools and their descriptions:
{available_tools_descriptions}
Based on the latest user message and conversation history, decide if a tool needs to be called.
If a tool is needed, specify which tool and what parameters to use in the AIMessage's tool_calls attribute.
IMPORTANT: If a tool requires a 'task_id' (like video processing tools for path organization),
ensure you use the Current Task ID: {task_id_from_state} for that argument.
If no tool is needed, or if you have enough information to answer, set your content to indicate readiness for answer composition (e.g., "Proceeding to compose answer.").
If the query is ambiguous, you can ask a clarifying question.
Focus on creating a plan or selecting the correct tool to gather necessary information.
Do not try to generate the final answer to the user here, unless it's a simple greeting or clarification.
Your response should be an AIMessage, possibly with tool_calls.
"""
messages_for_planner = [SystemMessage(content=planner_system_prompt)] + current_messages
print(f"Planner (nodes/planner.py) received: {current_messages[-1].content if current_messages else 'No messages'}. Task ID from state: {task_id_from_state}")
response = llm_instance.invoke(messages_for_planner)
print(f"Planner (nodes/planner.py) LLM response: {response.content[:100]}, Tool calls: {response.tool_calls}")
# Ensure task_id is preserved in the state update if it was there
# The add_messages in the StateGraph handles messages. We need to ensure other state parts are not lost.
# This node only returns messages to be added. The graph should merge the rest of the state.
# However, if this node were to *change* task_id, it would need to return it.
# For now, it just uses it.
returned_state_update = {"messages": [response]}
# if task_id_from_state != "UNKNOWN_TASK_ID":
# returned_state_update["task_id"] = task_id_from_state # Not strictly needed if graph merges state
return returned_state_update
# Remove the old placeholder TypedDict definition if PlannerState is now correctly defined at the top.
# if "TypedDict" not in globals():
# from typing import TypedDict # This was a placeholder, remove if PlannerState is fine
|