mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-22 07:32:25 +02:00
16 KiB
16 KiB
In [1]:
# %%capture --no-stderr
# %pip install -U langchain langchain_openai langchain_experimental langsmith pandasIn [2]:
import getpass
import os
def _set_if_undefined(var: str):
if not os.environ.get(var):
os.environ[var] = getpass(f"Please provide your {var}")
_set_if_undefined("OPENAI_API_KEY")
_set_if_undefined("LANGCHAIN_API_KEY")
_set_if_undefined("TAVILY_API_KEY")
# Optional, add tracing in LangSmith
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_PROJECT"] = "Multi-agent Collaboration"In [1]:
from typing import Annotated, List, Tuple, Union
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.tools import tool
from langchain_experimental.tools import PythonREPLTool
tavily_tool = TavilySearchResults(max_results=5)
# This executes code locally, which can be unsafe
python_repl_tool = PythonREPLTool()In [2]:
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_core.messages import BaseMessage, HumanMessage
from langchain_openai import ChatOpenAI
def create_agent(
llm: ChatOpenAI, tools: list, system_prompt: str
):
# Each worker node will be given a name and some tools.
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
system_prompt,
),
MessagesPlaceholder(variable_name="messages"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
agent = create_openai_tools_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools)
chain = executor | (
# So the agents properly role-play in this simulation, we will
# tag their final message as a human message
lambda x: {"messages": [HumanMessage(content=x["output"], name=name)]}
)
workflow.add_node(name, chain)In [3]:
def agent_node(state, agent, name):
result = agent.invoke(state)
return {"messages": [HumanMessage(content=result["output"], name=name)]}In [6]:
from langchain.output_parsers.openai_functions import JsonOutputFunctionsParser
members = ["Researcher", "Coder"]
system_prompt = (
"You are a supervisor tasked with managing a conversation between the"
" following workers: {members}. Given the following user request,"
" respond with the worker to act next. Each worker will perform a"
" task and respond with their results and status. When finished,"
" respond with FINISH."
)
# Our team supervisor is an LLM node. It just picks the next agent to process
# and decides when the work is completed
options = ["FINISH"] + members
# Using openai function calling can make output parsing easier for us
function_def = {
"name": "route",
"description": "Select the next role.",
"parameters": {
"title": "routeSchema",
"type": "object",
"properties": {
"next": {
"title": "Next",
"anyOf": [
{"enum": options},
],
}
},
"required": ["next"],
},
}
prompt = ChatPromptTemplate.from_messages(
[
("system", system_prompt),
MessagesPlaceholder(variable_name="messages"),
(
"system",
"Given the conversation above, who should act next?"
" Or should we FINISH? Select one of: {options}",
),
]
).partial(options=str(options), members=", ".join(members))
supervisor_chain = (
prompt
| llm.bind_functions(functions=[function_def], function_call="route")
| JsonOutputFunctionsParser()
)In [12]:
import operator
from typing import Annotated, Any, Dict, List, Optional, Sequence, TypedDict
import functools
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langgraph.graph import StateGraph, END
# The agent state is the input to each node in the graph
class AgentState(TypedDict):
# The annotation tells the graph that new messages will always
# be added to the current states
messages: Annotated[Sequence[BaseMessage], operator.add]
# The 'next' field indicates where to route to next
next: str
llm = ChatOpenAI(model="gpt-4-1106-preview")
research_agent = create_agent(llm, [tavily_tool], "You are a web researcher.")
research_node = functools.partial(agent_node, agent=research_agent, name="Researcher")
# NOTE: THIS PERFORMS ARBITRARY CODE EXECUTION. PROCEED WITH CAUTION
code_agent = create_agent(llm, [python_repl_tool], "You may generate safe python code to analyze data and generate charts using matplotlib.")
code_node = functools.partial(agent_node, agent=code_agent, name="Coder")
workflow = StateGraph(AgentState)
workflow.add_node("Researcher", research_node)
workflow.add_node("Coder", code_node)
workflow.add_node("supervisor", supervisor_chain)In [13]:
for member in members:
# We want our workers to ALWAYS "report back" to the supervisor when done
workflow.add_edge(member, "supervisor")
# The supervisor populates the "next" field in the graph state
# which routes to a node or finishes
conditional_map = {k: k for k in members}
conditional_map["FINISH"] = END
workflow.add_conditional_edges("supervisor", lambda x: x["next"], conditional_map)
# Finally, add entrypoint
workflow.set_entry_point("supervisor")
graph = workflow.compile()In [14]:
for s in graph.stream(
{
"messages": [
HumanMessage(content="Code hello world and print it to the terminal")
]
}
):
if "__end__" not in s:
print(s)
print("----"){'supervisor': {'next': 'Coder'}}
----
Python REPL can execute arbitrary code. Use with caution.
{'Coder': {'messages': [HumanMessage(content="The code `print('Hello, World!')` was executed, and it printed `Hello, World!` to the terminal.", name='Coder')]}}
----
{'supervisor': {'next': 'FINISH'}}
----
In [16]:
for s in graph.stream(
{
"messages": [
HumanMessage(content="Write a brief research report on pikas.")
]
},
{"recursion_limit": 100},
):
if "__end__" not in s:
print(s)
print("----"){'supervisor': {'next': 'Researcher'}}
----
{'Researcher': {'messages': [HumanMessage(content='## Research Report on Pikas\n\nPikas are small, mountain-dwelling mammals native to Asia and North America. They are characterized by their short limbs, rounded ears, and stout bodies. Unlike rodents, with which they are sometimes confused, pikas are more closely related to rabbits and hares, belonging to the order Lagomorpha.\n\n### Physical Description\nPikas are typically 15 to 23 cm (5.9 to 9.1 inches) in body length. They have an even coat of fur, no external tail, and resemble their close relatives, the rabbits, but with short, rounded ears. Their thick fur and small ears are adaptations to their cold habitats.\n\n### Habitat and Distribution\nPikas inhabit mountainous regions where they have adapted to life in rocky terrains. These creatures can be found at high altitudes, with the large-eared pika of the Himalayas living at elevations of more than 6,000 meters.\n\n### Diet and Behavior\nPikas are herbivorous and primarily feed on plants. They are known for their diligent behavior of collecting and storing food in their tunnels for winter. During the warmer months, pikas spend their days gathering grass in montane meadows and creating hay piles. These animals are also remarkable for their distinctive vocalizations used for communication.\n\n### Reproduction and Lifespan\nDetails on pika reproduction and lifespan were not provided in the immediate search results, but like many small mammals, pikas would typically have a breeding season and a relatively short lifespan in the wild.\n\n### Conservation\nPikas are currently facing challenges due to environmental changes. As their habitats are affected by the expansion of agriculture and the increasing temperatures due to climate change, pikas may find themselves in competition for resources. They are notably heat intolerant, which makes them particularly vulnerable to global warming.\n\n### Conclusion\nPikas are fascinating creatures with unique adaptations to their high-altitude environments. Their role in the ecosystem, distinctive behaviors, and close relation to the rabbit make them an interesting subject for further study, especially in the context of environmental conservation.\n\n**Sources:**\n- [Animals.net - Pika](https://animals.net/pika/)\n- [OneKindPlanet - American Pika](https://www.onekindplanet.org/animal/american-pika/)\n- [Facts.net - 12 Facts About Pika](https://facts.net/nature/animals/12-facts-about-pika/)\n- [Wikipedia - Pika](https://en.wikipedia.org/wiki/Pika)\n- [HowStuffWorks - Pikas](https://animals.howstuffworks.com/mammals/pika.htm)', name='Researcher')]}}
----
{'supervisor': {'next': 'FINISH'}}
----
In [ ]:
