Spaces:
Build error
Build error
Update agents.py
Browse files
agents.py
CHANGED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import TypedDict, Annotated, List
|
| 3 |
+
from langchain.tools import DuckDuckGoSearchResults
|
| 4 |
+
from langchain_groq import ChatGroq
|
| 5 |
+
from langgraph.graph import StateGraph, END, START
|
| 6 |
+
from langgraph.graph.message import AnyMessage, add_messages
|
| 7 |
+
|
| 8 |
+
# --- Setup API Key ---
|
| 9 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 10 |
+
|
| 11 |
+
# --- Setup Search Tool ---
|
| 12 |
+
search = DuckDuckGoSearchResults()
|
| 13 |
+
|
| 14 |
+
# --- Setup Model ---
|
| 15 |
+
model = ChatGroq(
|
| 16 |
+
model_name="llama3-8b-8192",
|
| 17 |
+
api_key=groq_api_key,
|
| 18 |
+
temperature=0
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# --- Tool List ---
|
| 22 |
+
tools = [search]
|
| 23 |
+
|
| 24 |
+
# --- Bind Model with Tools ---
|
| 25 |
+
llm_with_tools = model.bind_tools(
|
| 26 |
+
tools,
|
| 27 |
+
parallel_tool_calls=True
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# --- Define State Class ---
|
| 31 |
+
class AgentState(TypedDict):
|
| 32 |
+
messages: Annotated[List[AnyMessage], add_messages]
|
| 33 |
+
|
| 34 |
+
# --- Define Search Node ---
|
| 35 |
+
def search_node(state: AgentState):
|
| 36 |
+
response = llm_with_tools.invoke(state["messages"])
|
| 37 |
+
return {"messages": [response]}
|
| 38 |
+
|
| 39 |
+
# --- Build Graph ---
|
| 40 |
+
builder = StateGraph(AgentState)
|
| 41 |
+
builder.add_node("search", search_node)
|
| 42 |
+
builder.add_edge(START, "search")
|
| 43 |
+
builder.add_edge("search", END)
|
| 44 |
+
graph = builder.compile()
|
| 45 |
+
|
| 46 |
+
# --- Chat Function ---
|
| 47 |
+
def chat(question: str):
|
| 48 |
+
initial_messages = [{"role": "user", "content": question}]
|
| 49 |
+
result = graph.invoke({"messages": initial_messages})
|
| 50 |
+
return result
|