from typing import Annotated, List, TypedDict from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage, AIMessage from langchain_openai import ChatOpenAI from langgraph.graph.message import add_messages import os # Define the state for the answer composer node class ComposerState(TypedDict): messages: Annotated[List[BaseMessage], add_messages] # May include other fields like 'accumulated_tool_outputs' if processed separately llm = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0) # The SYSTEM_PROMPT from agent.py should be used here for consistency in final answer formatting. # It would be better to import it from a shared constants file if it becomes complex. # For now, I'll redefine a simplified version. Ensure it matches your agent.py's prompt for FINAL ANSWER format. COMPOSER_SYSTEM_PROMPT = """You are a helpful AI assistant. Your primary task is to synthesize a concise and accurate final answer to the user's most recent query, based on the entire preceding conversation history (which includes user questions, your own previous messages, tool calls, and their outputs like text from web pages or analysis summaries). Specific instructions for content synthesis: - If the user's question involves counting items from a list (e.g., albums from a discography within a specific date range) found in provided text: 1. Carefully identify the correct section (e.g., 'Studio Albums'). 2. For each item, accurately extract its title and its primary listed year of release/publication. 3. Strictly filter these items based on the date range given in the user's question (inclusive). 4. Only count items that match the specified type (e.g., 'studio album'). 5. For album projects released in multiple parts very closely together (e.g., Cantora 1 & Cantora 2 in the same year), count them as ONE album project for 'how many albums' questions. 6. State the final count clearly. - If a tool output (often in a ToolMessage) contains a 'source_frame_for_summary' key with a relevant frame name (not 'N/A' or 'Error'), and this frame is pertinent to the answer, include a brief sentence mentioning it, for example: 'This information pertains to frame [frame_name].' or 'The key observation was in frame [frame_name].' Place this sentence naturally within your response before the final conclusion. After synthesizing the answer based on these guidelines and the conversation history, you MUST conclude your entire response with the exact phrase 'FINAL ANSWER: [Your synthesized answer here]'. The format of '[Your synthesized answer here]' should follow general rules for conciseness: a number, as few words as possible, or a comma-separated list, as appropriate for the question. """ def answer_composer_node(state: ComposerState) -> ComposerState: """ LLM-based node to synthesize the final answer or pass through if already provided. If the last message from the planner already contains 'FINAL ANSWER:', this node will pass that message through. Otherwise, it uses an LLM to generate a final, consolidated answer to the user. It should adhere to the specified FINAL ANSWER format when generating. """ print("---CALLING ANSWER COMPOSER LLM NODE---") current_messages = state["messages"] # Check if the last message (likely from planner) already contains a FINAL ANSWER if current_messages and isinstance(current_messages[-1], AIMessage) and "FINAL ANSWER:" in current_messages[-1].content: print("Answer Composer detected FINAL ANSWER from planner. Passing through.") # Ensure the message is in the correct format for the graph state update final_ai_message = current_messages[-1] # No need to append dummy FINAL ANSWER here, as it's already present. return {"messages": [final_ai_message]} # Return the planner's message to be added to state # If no FINAL ANSWER from planner, proceed to compose one print("No FINAL ANSWER from planner detected. Composer will generate one.") messages_for_composer = [SystemMessage(content=COMPOSER_SYSTEM_PROMPT)] # Filter out any previous system messages to avoid confusion, if necessary, # or make sure the history is clean. For now, just append history. # Exclude the initial system prompt if it was generic and not for the composer. for msg in current_messages: if not isinstance(msg, SystemMessage): # Avoid duplicating system prompts if agent adds its own messages_for_composer.append(msg) elif isinstance(msg, SystemMessage) and msg.content != COMPOSER_SYSTEM_PROMPT: # If there are other system messages you want to retain, add them. # For now, only the composer system prompt is used. pass # Ensure the last message isn't an AI planning message if the planner adds one # The composer needs the *result* of the plan (tool outputs) not the plan itself as the last thing. print(f"Answer Composer received {len(messages_for_composer)} messages. Last: {messages_for_composer[-1].content[:100] if messages_for_composer else 'No messages'}") response_message = llm.invoke(messages_for_composer) # The response should be an AIMessage. If it's not, wrap it. if not isinstance(response_message, AIMessage): final_ai_message = AIMessage(content=str(response_message.content if hasattr(response_message, 'content') else response_message)) else: final_ai_message = response_message # Ensure the final answer format is present if "FINAL ANSWER:" not in final_ai_message.content: print("Warning: 'FINAL ANSWER:' not found in composer output. Appending dummy for safety.") # This indicates a problem with the prompt or model behavior. # For robustness, you might try to extract the likely answer or add a fallback. # For now, just append to the existing content if it's missing. final_ai_message.content += "\nFINAL ANSWER: [Could not reliably extract final answer]" print(f"Answer Composer generated: {final_ai_message.content[:300]}") # Increased preview length # The graph expects a dictionary with 'messages' to be added. # We add only the final composed AIMessage to avoid re-adding the whole history. # However, standard LangGraph practice is to return the message to be *added* to the state. # The StateGraph using `add_messages` will handle appending it to the existing `messages` list. return {"messages": [final_ai_message]}