mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-09-11 04:07:52 +02:00
update notebooks
This commit is contained in:
@@ -68,7 +68,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"execution_count": 1,
|
||||
"id": "f04c6778-403b-4b49-9b93-678e910d5cec",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@@ -97,7 +97,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"execution_count": 2,
|
||||
"id": "c4823dd9-26bd-4e1a-8117-b97b2860211a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@@ -106,11 +106,10 @@
|
||||
"from langchain_core.messages import BaseMessage, HumanMessage\n",
|
||||
"from langchain_openai import ChatOpenAI\n",
|
||||
"\n",
|
||||
"from langgraph.graph import END, StateGraph\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def create_worker_node(\n",
|
||||
" workflow: StateGraph, name: str, llm: ChatOpenAI, tools: list, system_prompt: str\n",
|
||||
"def create_agent(\n",
|
||||
" llm: ChatOpenAI, tools: list, system_prompt: str\n",
|
||||
"):\n",
|
||||
" # Each worker node will be given a name and some tools.\n",
|
||||
" prompt = ChatPromptTemplate.from_messages(\n",
|
||||
@@ -135,67 +134,38 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a07d507f-34d1-4f1b-8dde-5e58d17b2166",
|
||||
"id": "b7c302b0-cd57-4913-986f-5dc7d6d77386",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Construct Graph\n",
|
||||
"\n",
|
||||
"We're ready to start building the graph. Below, define the state and worker nodes using the function we just defined."
|
||||
"We can also define a function that we will use to be the nodes in the graph - it takes care of converting the agent response to a human message. This is important because that is how we will add it the global state of the graph"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "6a430af7-8fce-4e66-ba9e-d940c1bc48e8",
|
||||
"execution_count": 3,
|
||||
"id": "80862241-a1a7-4726-bce5-f867b233832e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import operator\n",
|
||||
"from typing import Annotated, Any, Dict, List, Optional, Sequence, TypedDict\n",
|
||||
"\n",
|
||||
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# The agent state is the input to each node in the graph\n",
|
||||
"class AgentState(TypedDict):\n",
|
||||
" # The annotation tells the graph that new messages will always\n",
|
||||
" # be added to the current states\n",
|
||||
" messages: Annotated[Sequence[BaseMessage], operator.add]\n",
|
||||
" # The 'next' field indicates where to route to next\n",
|
||||
" next: str\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"workflow = StateGraph(AgentState)\n",
|
||||
"\n",
|
||||
"llm = ChatOpenAI(model=\"gpt-4-1106-preview\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"create_worker_node(\n",
|
||||
" workflow, \"Researcher\", llm, [tavily_tool], \"You are a web researcher.\"\n",
|
||||
")\n",
|
||||
"# NOTE: THIS PERFORMS ARBITRARY CODE EXECUTION. PROCEED WITH CAUTION\n",
|
||||
"create_worker_node(\n",
|
||||
" workflow,\n",
|
||||
" \"Coder\",\n",
|
||||
" llm,\n",
|
||||
" [python_repl_tool],\n",
|
||||
" \"You may generate safe python code to analyze data \"\n",
|
||||
" \"and generate charts using matplotlib.\",\n",
|
||||
")"
|
||||
"def agent_node(state, agent, name):\n",
|
||||
" result = agent.invoke(state)\n",
|
||||
" return {\"messages\": [HumanMessage(content=result[\"output\"], name=name)]}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "d6374825-912f-40c9-910d-afa267b401bf",
|
||||
"id": "d32962d2-5487-496d-aefc-2a3b0d194985",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Almost done, now create create the team supervisor. It will use function calling to choose the next worker node OR finish processing."
|
||||
"### Create Agent Supervisor\n",
|
||||
"\n",
|
||||
"It will use function calling to choose the next worker node OR finish processing."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"id": "17c108a0-6dc3-46fd-a5e6-a1fcfad5458a",
|
||||
"id": "311f0a58-b425-4496-adac-dc4cd8ffb912",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -249,6 +219,57 @@
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a07d507f-34d1-4f1b-8dde-5e58d17b2166",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Construct Graph\n",
|
||||
"\n",
|
||||
"We're ready to start building the graph. Below, define the state and worker nodes using the function we just defined."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"id": "6a430af7-8fce-4e66-ba9e-d940c1bc48e8",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import operator\n",
|
||||
"from typing import Annotated, Any, Dict, List, Optional, Sequence, TypedDict\n",
|
||||
"import functools\n",
|
||||
"\n",
|
||||
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
|
||||
"from langgraph.graph import StateGraph, END\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# The agent state is the input to each node in the graph\n",
|
||||
"class AgentState(TypedDict):\n",
|
||||
" # The annotation tells the graph that new messages will always\n",
|
||||
" # be added to the current states\n",
|
||||
" messages: Annotated[Sequence[BaseMessage], operator.add]\n",
|
||||
" # The 'next' field indicates where to route to next\n",
|
||||
" next: str\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"llm = ChatOpenAI(model=\"gpt-4-1106-preview\")\n",
|
||||
"\n",
|
||||
"research_agent = create_agent(llm, [tavily_tool], \"You are a web researcher.\")\n",
|
||||
"research_node = functools.partial(agent_node, agent=research_agent, name=\"Researcher\")\n",
|
||||
"\n",
|
||||
"# NOTE: THIS PERFORMS ARBITRARY CODE EXECUTION. PROCEED WITH CAUTION\n",
|
||||
"code_agent = create_agent(llm, [python_repl_tool], \"You may generate safe python code to analyze data and generate charts using matplotlib.\")\n",
|
||||
"code_node = functools.partial(agent_node, agent=code_agent, name=\"Coder\")\n",
|
||||
"\n",
|
||||
"workflow = StateGraph(AgentState)\n",
|
||||
"workflow.add_node(\"Researcher\", research_node)\n",
|
||||
"workflow.add_node(\"Coder\", code_node)\n",
|
||||
"workflow.add_node(\"supervisor\", supervisor_chain)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "2c1593d5-39f7-4819-96d2-4ad7d7991d72",
|
||||
@@ -259,14 +280,11 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"execution_count": 13,
|
||||
"id": "14778e86-077b-4e6a-893c-400e59b0cdbf",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"workflow.add_node(\"supervisor\", supervisor_chain)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"for member in members:\n",
|
||||
" # We want our workers to ALWAYS \"report back\" to the supervisor when done\n",
|
||||
" workflow.add_edge(member, \"supervisor\")\n",
|
||||
@@ -293,10 +311,18 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"execution_count": 14,
|
||||
"id": "56ba78e9-d9c1-457c-a073-d606d5d3e013",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"{'supervisor': {'next': 'Coder'}}\n",
|
||||
"----\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
@@ -308,30 +334,29 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
||||
"\n",
|
||||
"The code `print('Hello, World!')` was executed, and the output is:\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"Hello, World!\n",
|
||||
"```\n"
|
||||
"{'Coder': {'messages': [HumanMessage(content=\"The code `print('Hello, World!')` was executed, and it printed `Hello, World!` to the terminal.\", name='Coder')]}}\n",
|
||||
"----\n",
|
||||
"{'supervisor': {'next': 'FINISH'}}\n",
|
||||
"----\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"results = graph.invoke(\n",
|
||||
"for s in graph.stream(\n",
|
||||
" {\n",
|
||||
" \"messages\": [\n",
|
||||
" HumanMessage(content=\"Code hello world and print it to the terminal\")\n",
|
||||
" ]\n",
|
||||
" }\n",
|
||||
")\n",
|
||||
"results[\"messages\"][-1].pretty_print()"
|
||||
"):\n",
|
||||
" if \"__end__\" not in s:\n",
|
||||
" print(s)\n",
|
||||
" print(\"----\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"execution_count": 16,
|
||||
"id": "45a92dfd-0e11-47f5-aad4-b68d24990e34",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
@@ -339,51 +364,27 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"================================\u001b[1m Human Message \u001b[0m=================================\n",
|
||||
"\n",
|
||||
"# Research Report on Pikas\n",
|
||||
"\n",
|
||||
"Pikas are small, mountain-dwelling mammals that are closely related to rabbits. They are known for their distinctive chirps and typically inhabit boulder fields at high elevations, up to 14,000 feet in treeless slopes like those found in the Southern Rockies. These animals are recognized for their ability to adapt to some of the most inhospitable climates.\n",
|
||||
"\n",
|
||||
"## Climate Change Impact\n",
|
||||
"\n",
|
||||
"Pikas have been a topic of interest in climate change research due to their sensitivity to high temperatures and reliance on cold habitats. They have historically responded to climate shifts by moving to higher elevations or latitudes to find suitable cooler environments. For instance, pikas were once found in the Appalachian Mountains and even in the Mojave Desert, but as the Earth's climate warmed, they moved to cooler, high-elevation areas where they live today.\n",
|
||||
"\n",
|
||||
"Recent studies suggest that pikas are showing remarkable adaptability to climate change. Despite predictions that they might become endangered due to rising temperatures, these animals are displaying resilience. Some research indicates that pikas can adjust certain genes to make better use of oxygen in higher altitudes where the air is thinner, which could be a potential hope for their survival as climate change drives them to higher elevations.\n",
|
||||
"\n",
|
||||
"However, there have been reports of pikas disappearing from parts of the Great Basin, and in Colorado, pikas have retracted upslope by about 1,160 feet. It's been noted that while climate change may be a factor, it might not be the sole cause for these local disappearances.\n",
|
||||
"\n",
|
||||
"## Adaptation Strategies\n",
|
||||
"\n",
|
||||
"Pikas exhibit several interesting behaviors that help them cope with their challenging environment. During the summer, they engage in activities like \"making hay\" — collecting and storing vegetation in preparation for the harsh winters. Their diet and caching behavior are essential for their survival during the months when food is scarce.\n",
|
||||
"\n",
|
||||
"## Conservation and Research\n",
|
||||
"\n",
|
||||
"Conservationists and scientists continue to study pikas to understand their adaptation mechanisms and how they might inform broader climate change mitigation strategies. For example, studies have been conducted on pikas at different elevations to observe genetic changes and their effects on adaptation. Such research is crucial for predicting the future of pikas and potentially other species affected by climate change.\n",
|
||||
"\n",
|
||||
"## Conclusion\n",
|
||||
"\n",
|
||||
"Pikas serve as an important indicator species for the impacts of climate change on wildlife. Their ability to adapt to changing climates offers hope and also highlights the importance of understanding genetic adaptability in the face of environmental challenges. Conservation efforts and further research are essential to ensure the survival of pikas and to learn from their resilience.\n",
|
||||
"\n",
|
||||
"### Sources\n",
|
||||
"- [The Conversation: Pikas are adapting to climate change remarkably well](https://theconversation.com/pikas-are-adapting-to-climate-change-remarkably-well-contrary-to-many-predictions-150726)\n",
|
||||
"- [Stanford Sustainability: It's in the genes – potential hope for pikas hit by climate change](https://sustainability.stanford.edu/news/its-genes-potential-hope-pikas-hit-climate-change)\n",
|
||||
"- [Colorado Sun: Colorado pika population and climate change](https://coloradosun.com/2023/08/27/colorado-pika-population-climate-change/)\n",
|
||||
"- [PetaPixel: Photographing the American Pika – a tiny indicator of climate change](https://petapixel.com/2022/01/03/photographing-the-american-pika-a-tiny-indicator-of-climate-change/)\n",
|
||||
"- [The Wildlife Society: Can pikas survive climate change after all?](https://wildlife.org/can-pikas-survive-climate-change-after-all/)\n"
|
||||
"{'supervisor': {'next': 'Researcher'}}\n",
|
||||
"----\n",
|
||||
"{'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')]}}\n",
|
||||
"----\n",
|
||||
"{'supervisor': {'next': 'FINISH'}}\n",
|
||||
"----\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"results = graph.invoke(\n",
|
||||
"for s in graph.stream(\n",
|
||||
" {\n",
|
||||
" \"messages\": [\n",
|
||||
" HumanMessage(content=\"Write a brief research report on pikas.\")\n",
|
||||
" ]\n",
|
||||
" },\n",
|
||||
" {\"recursion_limit\": 100},\n",
|
||||
")\n",
|
||||
"results[\"messages\"][-1].pretty_print()"
|
||||
"):\n",
|
||||
" if \"__end__\" not in s:\n",
|
||||
" print(s)\n",
|
||||
" print(\"----\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -411,7 +412,7 @@
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
"version": "3.11.1"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
Reference in New Issue
Block a user