RajeshKothiya's picture
[ADD] Agent: Adding initial agent code
cffde6b verified
"""LangGraph Agent"""
import os
from dotenv import load_dotenv
from langchain_groq import ChatGroq
from langchain_core.tools import tool
from langgraph.prebuilt import ToolNode
from langgraph.prebuilt import tools_condition
from langgraph.graph import START, StateGraph, MessagesState
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_community.tools import DuckDuckGoSearchResults
load_dotenv()
@tool
def web_search(query: str) -> str:
"""
Search DuckDuckGo for a query.
Args:
query: The search query.
Returns:
A dict with key ``"web_results"`` containing a
markdown-formatted string of the retrieved documents.
"""
# Instantiate the DuckDuckGo search utility
search = DuckDuckGoSearchResults(max_results=3)
# Perform the search
search_result = search.invoke(query)
return {"web_results": search_result}
tools = [
web_search,
]
llm = ChatGroq(model="meta-llama/llama-4-maverick-17b-128e-instruct", temperature=0)
llm_with_tools = llm.bind_tools(tools)
llm_with_tools = llm.bind_tools(tools)
# Node
def start_preprocess(state: MessagesState):
# System message
system_prompt = "You are a general AI assistant. I will ask you a question. Your answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."
sys_msg = SystemMessage(content=system_prompt)
return {"messages": [sys_msg] + state["messages"]}
# Node
def assistant(state: MessagesState):
"""Assistant node"""
return {"messages": [llm_with_tools.invoke(state["messages"])]}
builder = StateGraph(MessagesState)
builder.add_node("start_preprocess", start_preprocess)
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "start_preprocess")
builder.add_edge("start_preprocess", "assistant")
builder.add_conditional_edges(
"assistant",
tools_condition,
)
builder.add_edge("tools", "assistant")
# Compile graph
graph = builder.compile()
if __name__ == "__main__":
question = "NAMO age ?"
# Run the graph
messages = [HumanMessage(content=question)]
messages = graph.invoke({"messages": messages})
for m in messages["messages"]:
m.pretty_print()