File size: 1,816 Bytes
5d75fc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79324eb
5d75fc5
 
 
 
 
3ea4cc7
 
 
 
 
 
5d75fc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea4cc7
 
 
 
 
 
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
from typing import List, TypedDict, Annotated, Optional
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
from langgraph.graph.message import add_messages
from langgraph.graph import START, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
from langchain_community.tools import DuckDuckGoSearchRun


search_tool = DuckDuckGoSearchRun()


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

llm = HuggingFaceEndpoint()

chat = ChatHuggingFace(llm=llm, verbose=True)
tools = [search_tool]
chat_with_tools = chat.bind_tools(tools)

def assistant(state: AgentState) -> AgentState:
    messages = state.get("messages", [])
    response = chat_with_tools.invoke(messages=messages)
    messages.append(response)
    return {"messages": messages}

# The graph
builder = StateGraph(AgentState)

# Define nodes: these do the work
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))

# Define edges: these determine how the control flow moves
builder.add_edge(START, "assistant")
builder.add_conditional_edges(
    "assistant",
    # If the latest message requires a tool, route to tools
    # Otherwise, provide a direct response
    tools_condition,
)
builder.add_edge("tools", "assistant")
react_graph = builder.compile()

def agent(question: str) -> str:
    initial_state: AgentState = {"messages": [SystemMessage(content="You are a helpful assistant that can answer questions and use tools when necessary."), HumanMessage(content=question)]}
    final_state = react_graph.run(initial_state)
    # The last message in the final state is the assistant's response
    last_message = final_state["messages"][-1]
    return last_message.content