agents-course-final / agents.py
mludvig's picture
Improved tools
b5b4484
Raw History Blame Contribute Delete
13.5 kB
from typing import TypedDict, Annotated, List, Union, Optional
import json
import re
import base64
from io import BytesIO
import magic
from langgraph.graph import StateGraph, add_messages
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, ToolCall
from langgraph.prebuilt import ToolNode, tools_condition
from tools import tools
from audio import audio_transcript_tool
from markitdown import MarkItDown
TASK_BLACKLIST = [
"a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
]
TASK_CUSTOM_INSTRUCTIONS = {
"6f37996b-2ac7-44b0-8e68-6d28256631b4": "Return a comma separated list with a single space after the comma. All lowercase.",
# HF IP is blacklisted by Youtube :(
"9d191bce-651d-4746-be2d-7ef8ecadb9c2": """
The response MUST be a lowercase string with no additional characters like full stops or commas.
Use this video transcript if the youtube tool is not able to get the transcript:
### Transcript
Wow this coffee's great I was just thinking that yeah is that cinnamon chicory tea oak [Music] isn't that hot extremely
"""
}
# Define the system prompt for the thinking agent
THINKER_SYSTEM_PROMPT = """
You are a thinking agent that analyzes tasks and breaks them down into steps that can be executed by other agents.
You can't directly use tools, but you can plan the steps in great detail. The next agent will then execute the steps you planned and call the tools you specified. Be very specific about what you want the next agent to do.
You will have multiple turns to think about the task. You can ask for information, use tools, or provide a final answer. After calling a tool, you will receive the results and can continue your reasoning and planning next steps.
Once you gather all the information must summarize your reasoning and provide a final answer.
Your job is to:
- Understand what the task is asking.
- Decide what information you need to solve it and the steps to obtain the information. Think step by step and think ahead about what you will need to do.
- Always print your thoughts in every step and the next steps you will take.
- After the tools are called control will return to you and you will decide what to do next, whether to use another tool or provide a final answer.
- When you think you have all the information to solve the task, present all the facts that led you to the final answer in a clear and concise summary, showing your reasoning.
- If you are not sure about the answer, ask for more information or use the tools to get it.
- If you have all the information to solve the task, provide a concise answer to the task. Often it is just a number or a single word. Comma-separated lists should have a single space after the comma. Write your response in this EXACT format:
REASONING: <your reasoning>
FINAL ANSWER: <your answer>
"""
TOOLS_PLANNER_SYSTEM_PROMPT = """
You are a tool planning agent that has access to a set of tools. You will receive a task and you must decide which tools to use and how to use them, based on the task and the information you have.
- If you need to use a tool, call it with the required arguments. You are encouraged to use multiple tools in a single turn for a quicker resolution if they don't depend on each other. For example search for multiple terms in Google or Wikipedia at once. Google results include the URLs of the pages and you are encouraged to visit them to get more information.
- You can use the tools in any order you like. You can also use the same tool multiple times. However if the tool returns an error don't use it again with the same arguments.
"""
# Define the maximum number of turns for the agent
MAX_TURNS = 10
# Initialize the LLM
# llm = ChatOpenAI(model="o4-mini")
llm = ChatOpenAI(model="gpt-4o", temperature=0)
class AgentState(TypedDict):
messages: Annotated[List[Union[SystemMessage, HumanMessage, AIMessage]], add_messages]
next_step: Optional[str]
final_answer: Optional[str]
def thinker(state: AgentState) -> AgentState:
"""Analyze the task and decide what information is needed."""
print("--- Thinker ---")
# Prepend the system message to the state, creating a new state
thinker_prompt = [SystemMessage(content=THINKER_SYSTEM_PROMPT)] + state["messages"]
thinker_prompt.append(HumanMessage(content="With the information you currently have, can you confidently answer the question? If yes emit the final answer. If not, plan the next steps and tools use to get the information you need."))
# Get the thinking agent's response
response = llm.invoke(thinker_prompt)
# print(f"Thinking response: {response}")
if response.content:
print(f"Thinking response content: {response.content}")
# Record the assistant's message
state["messages"].append(AIMessage(content=response.content))
# Check for final answer
final_match = re.search(r"FINAL ANSWER:\s*(.*?)(?:$|[\n])", response.content, re.IGNORECASE | re.DOTALL)
if final_match:
final_answer = final_match.group(1).strip()
state["final_answer"] = final_answer
return state
def tools_planner(state: AgentState) -> AgentState:
"""Plan the tools to be used based on the task."""
print("--- Tools Planner ---")
# Prepend the system message to the state
tools_planner_prompt = [SystemMessage(content=TOOLS_PLANNER_SYSTEM_PROMPT)] + state["messages"]
# Get the thinking agent's response
llm_with_tools = llm.bind_tools(tools)
response = llm_with_tools.invoke(tools_planner_prompt)
# Check if the response contains a tool call
tool_calls = response.additional_kwargs.get("tool_calls", [])
if tool_calls:
state["messages"].append(AIMessage(content=response.content, tool_calls=[
ToolCall(name=tool_call["function"]["name"], args=json.loads(tool_call["function"]["arguments"]), id=tool_call["id"])
for tool_call in tool_calls
if tool_call["type"] == "function"
and tool_call["function"]["name"] in [tool.name for tool in tools]
]))
print(f"Tool calls found: {json.dumps(tool_calls, indent=2)}")
# Extract the tool calls
for tool_call in tool_calls:
if tool_call["type"] != "function":
print(f"Skipping non-function tool call: {tool_call}")
continue
function_name = tool_call["function"]["name"]
arguments = json.loads(tool_call["function"]["arguments"])
# id = tool_call["id"]
print(f"Tool call: {function_name} with arguments: {arguments}")
return state
def router(state: AgentState) -> AgentState:
"""Route the state to the appropriate tool or final answer."""
print("--- Router ---")
# Check if the maximum number of turns has been reached
# Filter only the AI messages
ai_messages = [msg for msg in state["messages"] if isinstance(msg, AIMessage)]
if len(ai_messages) >= MAX_TURNS:
print("Maximum number of turns reached. Exiting.")
dump_state(state)
return "__end__"
# Check if a final answer has been provided
if state.get("final_answer"):
print("Final answer has been provided.")
state["next_step"] = "final_answer"
dump_state(state)
return "final_answer"
# Check if there are tool calls in the last message
last_message = state["messages"][-1]
if isinstance(last_message, AIMessage) and last_message.tool_calls:
print("Tool calls found in the last message.")
return "tools_planner"
# If no tool calls, continue to thinker
return "thinker"
def final_answer(state: AgentState) -> AgentState:
"""Provide the final answer."""
print("--- Final Answer ---")
# TODO: Implement the final answer logic
# Check if a final answer has been provided
if state.get("final_answer"):
print("Final answer has been provided.")
dump_state(state)
return "__end__"
# If no final answer, continue to thinker
return "thinker"
def build_graph() -> StateGraph:
# Create our agent state graph
graph_builder = StateGraph(AgentState)
# Add nodes
# graph_builder.add_node("tool_executor", tool_executor)
graph_builder.add_node("tools", ToolNode(tools))
graph_builder.add_node("thinker", thinker)
graph_builder.add_node("tools_planner", tools_planner)
# graph_builder.add_node("final_answer", final_answer)
# graph_builder.add_conditional_edges("thinker", lambda state: state.get("next_step") or "tools_planner")
graph_builder.add_edge("thinker", "tools_planner")
graph_builder.add_conditional_edges("tools_planner", tools_condition)
graph_builder.add_edge("tools", "thinker") # Always return to thinker after tool execution
graph_builder.set_entry_point("thinker")
# Compile the graph
graph = graph_builder.compile()
# Save the graph as a PNG file
with open("graph.png", "wb") as f:
f.write(graph.get_graph().draw_mermaid_png())
print("Graph saved as graph.png")
return graph
class ThinkerAgent:
"""
A thinker agent that uses a state graph to analyze tasks and break them down into steps.
It uses tools to help solve the task and provides a final answer at the end of its reasoning.
"""
def __init__(self):
self.graph = build_graph()
def __call__(self, task_id: str, task: str, file_io: BytesIO = None) -> AgentState:
print("====== Running task ======")
print(task)
print("==========================")
# Initialize the state
initial_state: AgentState = {
"messages": [],
"final_answer": None,
}
human_message_content = [
{"type": "text", "text": task},
]
if task_id in TASK_CUSTOM_INSTRUCTIONS:
custom_instruction = TASK_CUSTOM_INSTRUCTIONS[task_id]
print(f"Custom instructions: {custom_instruction}")
human_message_content.append({
"type": "text",
"text": f"Follow these additional instructions: {custom_instruction}",
})
if file_io:
# Figure out the file type using python-magic
file_content = file_io.read()
file_mime_type = magic.from_buffer(file_content, mime=True)
print(f"File MIME type: {file_mime_type}")
if file_mime_type.startswith("image/"):
print("Attaching image file")
base64_file = base64.b64encode(file_content).decode("utf-8")
human_message_content.append({
"type": "image",
"source_type": "base64",
"mime_type": file_mime_type,
"data": base64_file,
})
elif file_mime_type.startswith("audio/"):
print("Transcribing audio file")
base64_file = base64.b64encode(file_content).decode("ascii")
human_message_content.append({
"type": "text",
"text": "The following message contains the transcript of the referenced audio file. Disregard any file names mentioned above, the following text is the transcript of the audio file you need.",
})
human_message_content.append({
"type": "text",
"text": audio_transcript_tool(base64_file),
})
else:
print("Converting to Markdown and attaching as text")
# Convert the file to markdown
md = MarkItDown()
markdown_result = md.convert(file_io)
human_message_content.append({
"type": "text",
"text": markdown_result.markdown
})
initial_state["messages"].append(HumanMessage(content=human_message_content))
# Run the graph with the initial state
final_state = self.graph.invoke(initial_state)
final_answer = final_state.get("final_answer")
return final_answer, final_state
def dump_state(state: AgentState) -> None:
"""
Dump the state to a string for debugging.
"""
if state["messages"]:
for i, msg in enumerate(state["messages"]):
role = msg.type
# content_preview = msg.content[:50] + "..." if len(msg.content) > 50 else msg.content
content_preview = msg.content
print(f"Message {i}: {role} - {content_preview}")
# Print tool calls if present
if role == "ai" and msg.tool_calls:
for tool_call in msg.tool_calls:
print(f"- Tool Call: {tool_call['name']} with arguments: {tool_call['args']}")
# Print the final answer
if state.get("final_answer"):
print(f"Final Answer: {state['final_answer']}")
if __name__ == "__main__":
# Run the agent with a sample task
task = "How much warmer is it currently in Christchurch than in Apia in degrees Farenheit? Only provide the number with 2 decimal places and no units, may be negative if the first city is colder than the second."
print(f"Running task: {task}")
# Run the task through the graph
agent = ThinkerAgent()
answer, state = agent(task)
print("\n--- Messages ---")
dump_state(state)
print("\n--- Final Answer ---")
print(answer)
print("\n====================")