AI Agents with LangGraph

Nov 12 2024 · Python 3.12, LangGraph 0.2.x, JupyterLab 4.2.4

Lesson 03: Building Complex AI Agents

Tools Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Tools Demo

Open the tools.ipynb notebook in the Starter folder. To get your feet wet working with tools, you’ll use Tavily search from the LangChain community. Begin by installing the necessary libraries:

!pip install langchain-community tavily-python
OPENAI_API_KEY=<your-api-key>
TAVILY_API_KEY=<your-api-key>
from dotenv import load_dotenv
load_dotenv()
from langchain_community.tools.tavily_search import TavilySearchResults

tool = TavilySearchResults()
tool.invoke({"query": "What's in the AI news?"})
import os
from langchain_openai import ChatOpenAI

tools = [tool]

llm = ChatOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
llm_with_tools = llm.bind_tools(tools)
from typing import TypedDict, Annotated, Sequence
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
import operator

class State(TypedDict):
  messages: Annotated[Sequence[BaseMessage], operator.add]
def call_llm(state):
  messages = state["messages"]
  response = llm_with_tools.invoke(messages)
  return {"messages": [response]}
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode, tools_condition

graph = StateGraph(State)

graph.add_node("chatbot", call_llm)
graph.add_node("tools", ToolNode(tools))

graph.add_edge(START, "chatbot")
graph.add_conditional_edges(
  "chatbot", tools_condition
)
graph.add_edge("tools", "chatbot")

app = graph.compile()
from IPython.display import Image, display

display(Image(app.get_graph().draw_mermaid_png()))
inputs = {"messages": [HumanMessage(content="What's the latest AI news?")]}
app.invoke(inputs)
from langchain_core.tools import tool

@tool
def count_characters(text: str) -> int:
  """Counts the number of characters in the text"""
  return len(text)

tool = count_characters
See forum comments
Cinema mode Download course materials from Github
Previous: Tools Next: Localizer Project