Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
from langgraph.graph import START, END, StateGraph, MessagesState
|
| 4 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
| 5 |
+
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
|
| 6 |
+
from langchain_core.tools import tool
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
# --- 1. Define Basic Tools ---
|
| 11 |
+
@tool
|
| 12 |
+
def add(a: int, b: int) -> int:
|
| 13 |
+
"""Add two numbers."""
|
| 14 |
+
return a + b
|
| 15 |
+
|
| 16 |
+
@tool
|
| 17 |
+
def multiply(a: int, b: int) -> int:
|
| 18 |
+
"""Multiply two numbers."""
|
| 19 |
+
return a * b
|
| 20 |
+
|
| 21 |
+
tools = [add, multiply]
|
| 22 |
+
|
| 23 |
+
# --- 2. Initialize the Hugging Face LLM ---
|
| 24 |
+
def get_llm():
|
| 25 |
+
# We use HuggingFaceEndpoint to connect to the model API
|
| 26 |
+
# You can change the repo_id to other models like "google/gemma-2-9b-it"
|
| 27 |
+
llm_engine = HuggingFaceEndpoint(
|
| 28 |
+
repo_id="meta-llama/Llama-3.3-70B-Instruct",
|
| 29 |
+
task="text-generation",
|
| 30 |
+
huggingfacehub_api_token=os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# Wrap it in ChatHuggingFace to make it compatible with LangGraph tools
|
| 34 |
+
model = ChatHuggingFace(llm=llm_engine)
|
| 35 |
+
return model.bind_tools(tools)
|
| 36 |
+
|
| 37 |
+
# --- 3. Define the Logic Nodes ---
|
| 38 |
+
def assistant(state: MessagesState):
|
| 39 |
+
llm = get_llm()
|
| 40 |
+
# The agent looks at the message history and decides the next move
|
| 41 |
+
return {"messages": [llm.invoke(state["messages"])]}
|
| 42 |
+
|
| 43 |
+
# --- 4. Build the Graph ---
|
| 44 |
+
def build_graph():
|
| 45 |
+
builder = StateGraph(MessagesState)
|
| 46 |
+
|
| 47 |
+
# Add Nodes
|
| 48 |
+
builder.add_node("assistant", assistant)
|
| 49 |
+
builder.add_node("tools", ToolNode(tools))
|
| 50 |
+
|
| 51 |
+
# Define Flow
|
| 52 |
+
builder.add_edge(START, "assistant")
|
| 53 |
+
|
| 54 |
+
# The conditional edge checks if the LLM called a tool
|
| 55 |
+
builder.add_conditional_edges(
|
| 56 |
+
"assistant",
|
| 57 |
+
tools_condition, # If tool called -> "tools", else -> END
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# After using a tool, always go back to the assistant to summarize
|
| 61 |
+
builder.add_edge("tools", "assistant")
|
| 62 |
+
|
| 63 |
+
return builder.compile()
|