Spaces:
Sleeping
Sleeping
Create agent.py
Browse files
agent.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TypedDict, Annotated
|
| 2 |
+
from langgraph.graph.message import add_messages
|
| 3 |
+
from langchain_core.messages import AnyMessage, HumanMessage, AIMessage
|
| 4 |
+
from langgraph.prebuilt import ToolNode
|
| 5 |
+
from langgraph.graph import START, StateGraph
|
| 6 |
+
from langgraph.prebuilt import tools_condition
|
| 7 |
+
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
| 8 |
+
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
| 9 |
+
|
| 10 |
+
# Generate the chat interface, including the tools
|
| 11 |
+
llm = HuggingFaceEndpoint(
|
| 12 |
+
repo_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 13 |
+
huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
chat = ChatHuggingFace(llm=llm, verbose=True)
|
| 17 |
+
tools = [search_tool, weather_info_tool, hub_stats_tool]
|
| 18 |
+
chat_with_tools = chat.bind_tools(tools)
|
| 19 |
+
|
| 20 |
+
# Generate the AgentState and Agent graph
|
| 21 |
+
class AgentState(TypedDict):
|
| 22 |
+
messages: Annotated[list[AnyMessage], add_messages]
|
| 23 |
+
|
| 24 |
+
def assistant(state: AgentState):
|
| 25 |
+
return {
|
| 26 |
+
"messages": [chat_with_tools.invoke(state["messages"])],
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
## The graph
|
| 30 |
+
builder = StateGraph(AgentState)
|
| 31 |
+
|
| 32 |
+
# Define nodes: these do the work
|
| 33 |
+
builder.add_node("assistant", assistant)
|
| 34 |
+
builder.add_node("tools", ToolNode(tools))
|
| 35 |
+
|
| 36 |
+
# Define edges: these determine how the control flow moves
|
| 37 |
+
builder.add_edge(START, "assistant")
|
| 38 |
+
builder.add_conditional_edges(
|
| 39 |
+
"assistant",
|
| 40 |
+
# If the latest message requires a tool, route to tools
|
| 41 |
+
# Otherwise, provide a direct response
|
| 42 |
+
tools_condition,
|
| 43 |
+
)
|
| 44 |
+
builder.add_edge("tools", "assistant")
|
| 45 |
+
agent = builder.compile()
|