Skip to content

Commit

Permalink
update langgraph cookbook
Browse files Browse the repository at this point in the history
  • Loading branch information
synacktraa committed Oct 2, 2024
1 parent 9d695eb commit f149560
Show file tree
Hide file tree
Showing 2 changed files with 264 additions and 264 deletions.
264 changes: 264 additions & 0 deletions cookbooks/langgraph-groq-example.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"#@title Install and import necessary libraries\n",
"%pip install -qU \"tool-parse[langchain]\" langchain-groq langgraph duckduckgo-search\n",
"\n",
"import typing as t\n",
"\n",
"from duckduckgo_search import DDGS\n",
"\n",
"from langchain_groq.chat_models import ChatGroq\n",
"from langchain_core.messages import AIMessage, HumanMessage, ToolMessage\n",
"\n",
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langgraph.prebuilt import create_react_agent\n",
"\n",
"from tool_parse.integrations.langchain import ExtendedStructuredTool, patch_chat_model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Define tools"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[ExtendedStructuredTool(name='search_text', description='Search for text in the web.', func=<function search_text at 0x0000012F2A321120>),\n",
" ExtendedStructuredTool(name='product_info', description='Information about the product.', func=<class '__main__.ProductInfo'>)]"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def search_text(\n",
" text: str,\n",
" *,\n",
" safe_search: bool = True,\n",
" backend: t.Literal[\"api\", \"html\", \"lite\"] = \"api\",\n",
" max_results: int = 1,\n",
"):\n",
" \"\"\"\n",
" Search for text in the web.\n",
" :param text: Text to search for.\n",
" :param safe_search: If True, enable safe search.\n",
" :param backend: Backend to use for retrieving results.\n",
" :param max_results: Max results to return.\n",
" \"\"\"\n",
" return DDGS().text(\n",
" keywords=text,\n",
" safesearch=\"on\" if safe_search else \"off\",\n",
" backend=backend,\n",
" max_results=max_results,\n",
" )\n",
"\n",
"class ProductInfo(t.NamedTuple): # Can be t.TypedDict or pydantic.BaseModel\n",
" \"\"\"\n",
" Information about the product.\n",
" :param name: Name of the product.\n",
" :param price: Price of the product.\n",
" :param in_stock: If the product is in stock.\n",
" \"\"\"\n",
"\n",
" name: str\n",
" price: float\n",
" in_stock: bool = False\n",
"\n",
"tools = [\n",
" ExtendedStructuredTool(func=search_text),\n",
" ExtendedStructuredTool(func=ProductInfo, name=\"product_info\"),\n",
"]\n",
"# OR # tools = ExtendedStructuredTool.from_objects(search_text, ProductInfo)\n",
"tools"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Patch the langchain chat model"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# Set groq api key (https://console.groq.com/keys)\n",
"\n",
"import os, getpass\n",
"\n",
"def set_env(var: str):\n",
" if not os.environ.get(var):\n",
" os.environ[var] = getpass.getpass(f\"{var}: \")\n",
"\n",
"set_env(\"GROQ_API_KEY\")"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"# Patch the instance\n",
"model = patch_chat_model(ChatGroq(api_key=os.getenv(\"GROQ_API_KEY\"), model=\"llama3-70b-8192\"))\n",
"# OR Patch the class and then instantiate it\n",
"model = patch_chat_model(ChatGroq)(api_key=os.getenv(\"GROQ_API_KEY\"), model=\"llama3-70b-8192\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a react agent"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"agent_executor = create_react_agent(model, tools, checkpointer=MemorySaver())\n",
"config = {\"configurable\": {\"thread_id\": \"id123\"}}\n",
"\n",
"def query_agent(__query: str):\n",
" for chunk in agent_executor.stream({\"messages\": [HumanMessage(content=__query)]}, config):\n",
" message = list(chunk.values())[0][\"messages\"][0]\n",
" if isinstance(message, AIMessage):\n",
" print(\"[AGENT]\")\n",
" if message.tool_calls:\n",
" print(\"Calling tool:\")\n",
" metadata = message.tool_calls[0]\n",
" print(f\"name={metadata['name']!r}\")\n",
" print(f\"arguments={metadata['args']}\")\n",
" else:\n",
" print(message.content)\n",
" elif isinstance(message, ToolMessage):\n",
" print(f\"[{message.name!r} TOOL OUTPUT]\")\n",
" print(message.content)\n",
"\n",
" print(\"---\" * 20)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[AGENT]\n",
"Calling tool:\n",
"name='search_text'\n",
"arguments={'backend': 'lite', 'max_results': 5, 'text': 'langgraph docs'}\n",
"------------------------------------------------------------\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\synac\\AppData\\Local\\Temp\\ipykernel_7024\\857887115.py:15: UserWarning: lxml is not installed. Using backend='api'.\n",
" return DDGS().text(\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"['search_text' TOOL OUTPUT]\n",
"[{\"title\": \"LangGraph - LangChain\", \"href\": \"https://www.langchain.com/langgraph\", \"body\": \"LangGraph is a framework for building stateful, multi-agent systems with LLMs. Learn how to use LangGraph with Python or JavaScript, see conceptual guides, and access LangGraph Cloud for deployment and scaling.\"}, {\"title\": \"️LangGraph - GitHub Pages\", \"href\": \"https://langchain-ai.github.io/langgraph/\", \"body\": \"LangGraph is a framework for creating stateful, multi-actor applications with LLMs, using cycles, controllability, and persistence. Learn how to use LangGraph with examples, features, and integration with LangChain and LangSmith.\"}, {\"title\": \"️LangGraph.js - GitHub Pages\", \"href\": \"https://langchain-ai.github.io/langgraphjs/\", \"body\": \"LangGraph.js is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows. Compared to other LLM frameworks, it offers these core benefits: cycles, controllability, and persistence. LangGraph allows you to define flows that involve cycles, essential for most agentic architectures ...\"}, {\"title\": \"Introduction to LangGraph\", \"href\": \"https://academy.langchain.com/courses/intro-to-langgraph\", \"body\": \"No. LangGraph is an orchestration framework for complex agentic systems and is more low-level and controllable than LangChain agents. On the other hand, LangChain provides a standard interface to interact with models and other components, useful for straight-forward chains and retrieval flows. How is LangGraph different from other agent frameworks?\"}, {\"title\": \"langgraph - PyPI\", \"href\": \"https://pypi.org/project/langgraph/\", \"body\": \"LangGraph is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows. Compared to other LLM frameworks, it offers these core benefits: cycles, controllability, and persistence. LangGraph allows you to define flows that involve cycles, essential for most agentic architectures ...\"}]\n",
"------------------------------------------------------------\n",
"[AGENT]\n",
"Here are the top 5 sources for LangGraph docs using the lite backend: \n",
"\n",
"1. LangGraph - LangChain (https://www.langchain.com/langgraph) - Learn how to use LangGraph with Python or JavaScript, see conceptual guides, and access LangGraph Cloud for deployment and scaling.\n",
"\n",
"2. ️LangGraph - GitHub Pages (https://langchain-ai.github.io/langgraph/) - LangGraph is a framework for creating stateful, multi-actor applications with LLMs, using cycles, controllability, and persistence.\n",
"\n",
"3. ️LangGraph.js - GitHub Pages (https://langchain-ai.github.io/langgraphjs/) - LangGraph.js is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows.\n",
"\n",
"4. Introduction to LangGraph (https://academy.langchain.com/courses/intro-to-langgraph) - LangGraph is an orchestration framework for complex agentic systems and is more low-level and controllable than LangChain agents.\n",
"\n",
"5. langgraph - PyPI (https://pypi.org/project/langgraph/) - LangGraph is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows.\n",
"------------------------------------------------------------\n"
]
}
],
"source": [
"query_agent(\"Search 5 sources for langgraph docs using lite backend\")"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[AGENT]\n",
"Calling tool:\n",
"name='product_info'\n",
"arguments={'in_stock': True, 'name': 'RTX 4900', 'price': 3500}\n",
"------------------------------------------------------------\n",
"['product_info' TOOL OUTPUT]\n",
"[\"RTX 4900\", 3500.0, true]\n",
"------------------------------------------------------------\n",
"[AGENT]\n",
"Here is the product information:\n",
"\n",
"The product is RTX 4900, priced at $3500.00, and it is in stock.\n",
"------------------------------------------------------------\n"
]
}
],
"source": [
"query_agent(\"Parse the product: RTX 4900, priced at $3.5k, is in stock.\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Loading

0 comments on commit f149560

Please sign in to comment.