Add agent functionality and update requirements
Browse files- agent.py +49 -0
- requirements.txt +6 -0
agent.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, TypedDict, Annotated, Optional
|
| 2 |
+
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
| 3 |
+
from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
|
| 4 |
+
from langgraph.graph.message import add_messages
|
| 5 |
+
from langgraph.graph import START, StateGraph
|
| 6 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
| 7 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
search_tool = DuckDuckGoSearchRun()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class AgentState(TypedDict):
|
| 14 |
+
messages: Annotated[List[AnyMessage], add_messages]
|
| 15 |
+
|
| 16 |
+
llm = HuggingFaceEndpoint(
|
| 17 |
+
repo_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 18 |
+
huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
chat = ChatHuggingFace(llm=llm, verbose=True)
|
| 22 |
+
tools = [search_tool]
|
| 23 |
+
chat_with_tools = chat.bind_tools(tools)
|
| 24 |
+
|
| 25 |
+
# The graph
|
| 26 |
+
builder = StateGraph(AgentState)
|
| 27 |
+
|
| 28 |
+
# Define nodes: these do the work
|
| 29 |
+
builder.add_node("assistant", assistant)
|
| 30 |
+
builder.add_node("tools", ToolNode(tools))
|
| 31 |
+
|
| 32 |
+
# Define edges: these determine how the control flow moves
|
| 33 |
+
builder.add_edge(START, "assistant")
|
| 34 |
+
builder.add_conditional_edges(
|
| 35 |
+
"assistant",
|
| 36 |
+
# If the latest message requires a tool, route to tools
|
| 37 |
+
# Otherwise, provide a direct response
|
| 38 |
+
tools_condition,
|
| 39 |
+
)
|
| 40 |
+
builder.add_edge("tools", "assistant")
|
| 41 |
+
react_graph = builder.compile()
|
| 42 |
+
|
| 43 |
+
messages=[
|
| 44 |
+
SystemMessage(
|
| 45 |
+
content="You are a helpful assistant that can answer questions and use tools when necessary."
|
| 46 |
+
),
|
| 47 |
+
HumanMessage(content="What is the capital of France?"),
|
| 48 |
+
]
|
| 49 |
+
chat_with_tools.invoke(messages=messages)
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
requests
|
| 3 |
+
langchain-huggingface
|
| 4 |
+
langgraph
|
| 5 |
+
langchain_core
|
| 6 |
+
langchain-community
|