AI Agents with LangGraph

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

Lesson 02: Fundamentals of LangGraph

Project Demo

Episode complete

Play next episode

Next
Transcript

Project Demo

In lesson 1, you started an AI Agent project to localize app strings from English into Spanish. So far, all that it does is translate a few words. You won’t add any functionality to your agent today, but you’ll modify it to use LangGraph.

Open the localizer.ipynb notebook in the Starter folder. It contains the code in the state that you left it at the end of Lesson 1. In this lesson, you’ll modify the code just enough to use LangGraph, nothing more. In the next lesson, you’ll increase your agent’s complexity.

Go to your ai_agent function and rename it extract:

def extract(user_input):

Modify the prompt so that you’re only asking the LLM to find the text to translate. In today’s lesson, you won’t be doing any branching or decision-making:

prompt = """Analyze if the user is asking for a translation.
  If so, respond with only the text to translate.
  Do not translate the text yourself. Otherwise, respond normally.
  For example, if the user says 'How do you say hello in Spanish?'
  you should respond 'hello' """

Remove all the decision-making logic:

completion = llm.chat.completions.create(
  model="gpt-4o",
  messages=[
    {"role": "system", "content": prompt},
    {"role": "user", "content": user_input}
  ]
)

return completion.choices[0].message.content

Create a plain graph without any state:

from langgraph.graph import Graph

graph = Graph()

graph.add_node("extractor", extract)
graph.add_node("translator", translate)

graph.add_edge("extractor", "translator")

graph.set_entry_point("extractor")
graph.set_finish_point("translator")

app = graph.compile()

Finally, invoke the app to run it:

user_input = "How do you say goodbye in Spanish?"
result = app.invoke(user_input)
print(result)

As you can see, it still works as before: “adiós”. And, well, it’s adiós for this lesson as well. That brings you to the end of Lesson 2.

See forum comments
Cinema mode Download course materials from Github
Previous: State Demo Next: Conclusion