CoolFace
Apppublic

FernandoDeSantosFranco/AI_Agents_Course

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py50 linesDownload Raw Back to root
1from typing import TypedDict, Annotated2from langgraph.graph.message import add_messages3from langchain_core.messages import AnyMessage, HumanMessage, AIMessage4from langgraph.prebuilt import ToolNode5from langgraph.graph import START, StateGraph6from langgraph.prebuilt import tools_condition7from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace8 9from tools import DuckDuckGoSearchRun10 11# Initialize the web search tool12search_tool = DuckDuckGoSearchRun()13 14# Generate the chat interface, including the tools15llm = HuggingFaceEndpoint(16    repo_id="Qwen/Qwen2.5-Coder-32B-Instruct",17    huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,18)19 20chat = ChatHuggingFace(llm=llm, verbose=True)21tools = [search_tool]22chat_with_tools = chat.bind_tools(tools)23 24# Generate the AgentState and Agent graph25class AgentState(TypedDict):26    messages: Annotated[list[AnyMessage], add_messages]27 28def assistant(state: AgentState):29    return {30        "messages": [chat_with_tools.invoke(state["messages"])],31    }32 33## The graph34builder = StateGraph(AgentState)35 36# Define nodes: these do the work37builder.add_node("assistant", assistant)38builder.add_node("tools", ToolNode(tools))39 40# Define edges: these determine how the control flow moves41builder.add_edge(START, "assistant")42builder.add_conditional_edges(43    "assistant",44    # If the latest message requires a tool, route to tools45    # Otherwise, provide a direct response46    tools_condition,47)48 49builder.add_edge("tools", "assistant")50assitant = builder.compile()