File size: 2,059 Bytes
e758f09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from globals import *

# model_name = 'qwen3:8b'
model_name = 'llama3.2:latest'


# Initialize Laminar - this single step enables automatic tracing
Laminar.initialize(project_api_key=LAMINAR_API_KEY)

llm = ChatOllama(model=model_name)


# def load_guest_dataset():
guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train")

docs = [
    Document(
        page_content='\n'.join([
            f"Name: {guest['name']}",
            f"Relation: {guest['relation']}",
            f"Description: {guest['description']}",
            f"Email: {guest['email']}",
        ]),
        metadata={'name': guest['name']}
    ) for guest in guest_dataset
]


bm25_retriever = BM25Retriever.from_documents(docs)

def extract_text(query: str) -> str:
    """Retrieves detailed information about gala guests based on their name or relation."""
    results = bm25_retriever.invoke(query)
    if results:
        return '\n\n'.join([doc.page_content for doc in results[:3]])
    else:
        return 'NO match!'

guest_info_tool = Tool(
    name='guest_info_retriever',
    func=extract_text,
    description='Retrieves detailed information about gala guests based on their name or relation.'
)

tools = [guest_info_tool]
llm_with_tools = llm.bind_tools(tools)


class AgentState(TypedDict):
    messages: Annotated[list[AnyMessage], add_messages]

def assistant(state: AgentState):
    return {
        'messages': [llm_with_tools.invoke(state['messages'])]
    }

builder = StateGraph(AgentState)

builder.add_node('assistant', assistant)
builder.add_node('tools', ToolNode(tools))

builder.add_edge(START, 'assistant')
builder.add_conditional_edges('assistant', tools_condition)
builder.add_edge('tools', 'assistant')
alfred = builder.compile()
with open("langgraph.png", "wb") as f:
    f.write(alfred.get_graph().draw_mermaid_png())

messages = [HumanMessage(content="Tell me about our guest named 'Lady Ada Lovelace'.")]
response = alfred.invoke({'messages': messages})

print("🎩 Alfred's Response:")
print(response['messages'][-1].content)