3mpj's picture
Create agent.py
f2845f9 verified
Raw
History Blame Contribute Delete
2.79 kB
import os
from dotenv import load_dotenv
from langgraph.graph import START, StateGraph, MessagesState
from langgraph.prebuilt import tools_condition
from langgraph.prebuilt import ToolNode
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_groq import ChatGroq
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint#, HuggingFaceEmbeddings
# from langchain_community.vectorstores import SupabaseVectorStore
from langchain_core.messages import SystemMessage, HumanMessage
# from langchain.tools.retriever import create_retriever_tool
# from supabase.client import Client, create_client
from prompt import SYSTEM_PROMPT
from tools import add, subtract, multiply, divide, web_search
load_dotenv()
HUGGINGFACEHUB_API_TOKEN = os.environ["HF_TOKEN"]
tools = [add, subtract, multiply, divide, web_search]
# Build graph function
def build_graph(provider: str = "huggingface") -> StateGraph:
"""Build the graph"""
sys_msg = SystemMessage(content=SYSTEM_PROMPT)
if provider == "google":
# Google Gemini
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
elif provider == "groq":
# Groq https://console.groq.com/docs/models
llm = ChatGroq(model="qwen-qwq-32b", temperature=0) # optional : qwen-qwq-32b gemma2-9b-it
elif provider == "huggingface":
llm = ChatHuggingFace(
llm=HuggingFaceEndpoint(
repo_id="Qwen/Qwen2.5-Coder-32B-Instruct",
huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN
),
)
else:
raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
llm_with_tools = llm.bind_tools(tools)
# Node
def assistant(state: MessagesState):
"""Assistant node"""
message = [sys_msg] + state["messages"]
return {"messages": [llm_with_tools.invoke(message)]}
builder = StateGraph(MessagesState)
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "assistant")
builder.add_conditional_edges(
"assistant",
tools_condition,
)
builder.add_edge("tools", "assistant")
# Compile graph
return builder.compile()
class BasicAgent:
"""A langgraph agent."""
def __init__(self):
print("BasicAgent initialized.")
self.graph = build_graph()
def __call__(self, question: str) -> str:
print(f"Agent received question (first 50 chars): {question[:50]}...")
# Wrap the question in a HumanMessage from langchain_core
messages = [HumanMessage(content=question)]
messages = self.graph.invoke({"messages": messages})
answer = messages['messages'][-1].content
return answer[14:]