Update agent.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""LangGraph Agent"""import osfrom dotenv import load_dotenvfrom langgraph.graph import START, StateGraph, MessagesStatefrom langgraph.prebuilt import tools_conditionfrom langgraph.prebuilt import ToolNodefrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_groq import ChatGroqfrom langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddingsfrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langchain_community.document_loaders import WikipediaLoaderfrom langchain_community.document_loaders import ArxivLoaderfrom langchain_community.vectorstores import SupabaseVectorStorefrom langchain_core.messages import SystemMessage, HumanMessagefrom langchain_core.tools import toolfrom langchain.tools.retriever import create_retriever_toolfrom supabase.client import Client, create_clientload_dotenv()@tooldef multiply(a: int, b: int) -> int:"""Multiply two numbers.Args:a: first intb: second int"""return a * b@tooldef add(a: int, b: int) -> int:"""Add two numbers.Args:a: first intb: second int"""return a + b@tooldef subtract(a: int, b: int) -> int:"""Subtract two numbers.Args:a: first intb: second int"""return a - b@tooldef divide(a: int, b: int) -> int:"""Divide two numbers.Args:a: first intb: second int"""if b == 0:raise ValueError("Cannot divide by zero.")return a / b@tooldef modulus(a: int, b: int) -> int:"""Get the modulus of two numbers.Args:a: first intb: second int"""return a % b@tooldef wiki_search(query: str) -> str:"""Search Wikipedia for a query and return maximum 2 results.Args:query: The search query."""search_docs = WikipediaLoader(query=query, load_max_docs=2).load()formatted_search_docs = "\n\n---\n\n".join([f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'for doc in search_docs])return {"wiki_results": formatted_search_docs}@tooldef web_search(query: str) -> str:"""Search Tavily for a query and return maximum 3 results.Args:query: The search query."""search_docs = TavilySearchResults(max_results=3).invoke(query=query)formatted_search_docs = "\n\n---\n\n".join([f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'for doc in search_docs])return {"web_results": formatted_search_docs}@tooldef arvix_search(query: str) -> str:"""Search Arxiv for a query and return maximum 3 result.Args:query: The search query."""search_docs = ArxivLoader(query=query, load_max_docs=3).load()formatted_search_docs = "\n\n---\n\n".join([f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'for doc in search_docs])return {"arvix_results": formatted_search_docs}# load the system prompt from the filewith open("system_prompt.txt", "r", encoding="utf-8") as f:system_prompt = f.read()# System messagesys_msg = SystemMessage(content=system_prompt)# build a retrieverembeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768supabase: Client = create_client(os.environ.get("SUPABASE_URL"),os.environ.get("SUPABASE_SERVICE_KEY"))vector_store = SupabaseVectorStore(client=supabase,embedding= embeddings,table_name="documents",query_name="match_documents_langchain",)create_retriever_tool = create_retriever_tool(retriever=vector_store.as_retriever(),name="Question Search",description="A tool to retrieve similar questions from a vector store.",)tools = [multiply,add,subtract,divide,modulus,wiki_search,web_search,arvix_search,]# Build graph functiondef build_graph(provider: str = "google"):"""Build the graph"""# Load environment variables from .env fileif provider == "google":# Google Geminillm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)elif provider == "groq":# Groq https://console.groq.com/docs/modelsllm = ChatGroq(model="qwen-qwq-32b", temperature=0) # optional : qwen-qwq-32b gemma2-9b-itelif provider == "huggingface":# TODO: Add huggingface endpointllm = ChatHuggingFace(llm=HuggingFaceEndpoint(url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",temperature=0,),)else:raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")# Bind tools to LLMllm_with_tools = llm.bind_tools(tools)# Nodedef assistant(state: MessagesState):"""Assistant node"""return {"messages": [llm_with_tools.invoke(state["messages"])]}# def retriever(state: MessagesState):# """Retriever node"""# similar_question = vector_store.similarity_search(state["messages"][0].content)#example_msg = HumanMessage(# content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",# )# return {"messages": [sys_msg] + state["messages"] + [example_msg]}from langchain_core.messages import AIMessagedef retriever(state: MessagesState):query = state["messages"][-1].contentsimilar_doc = vector_store.similarity_search(query, k=1)[0]content = similar_doc.page_contentif "Final answer :" in content:answer = content.split("Final answer :")[-1].strip()else:answer = content.strip()return {"messages": [AIMessage(content=answer)]}# builder = StateGraph(MessagesState)#builder.add_node("retriever", retriever)#builder.add_node("assistant", assistant)#builder.add_node("tools", ToolNode(tools))#builder.add_edge(START, "retriever")#builder.add_edge("retriever", "assistant")#builder.add_conditional_edges(# "assistant",# tools_condition,#)#builder.add_edge("tools", "assistant")builder = StateGraph(MessagesState)builder.add_node("retriever", retriever)# Retriever ist Start und Endpunktbuilder.set_entry_point("retriever")builder.set_finish_point("retriever")# Compile graphreturn builder.compile()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109from smolagents import Tool, tool, CodeAgent, OpenAIServerModel, DuckDuckGoSearchToolimport timeimport osimport requestsimport markdownify#for the mp3 file readingimport whisperimport tempfileimport ioclass Mod4Agent:def __init__(self):self.api_key=os.getenv("OPENAI_KEY")#base modelself.model = OpenAIServerModel(model_id="gpt-4o",api_base="https://api.openai.com/v1",temperature=0.0,api_key=self.api_key)#base_promptself.base_prompt="""You are an agent with a set of tools for answering to questions.You need to be accurate and get the best possible answer in the simplest possible way.You need to think step-by-step, and if at some point there is an error, backtrack and use a different method.It is important to adhere to the instructions of the question as close as possible.IMPORTANT: always answer according to the format required to the best of your abilities. Stating that you do not know, or explaining why, will give a score of 0 therefore it is to be avoided.You can do it!Question:"""@tooldef audio_interpreter(input: bytes)->str:"""Function to transcribe an mp3 file from raw bytes or file path into the corresponding textArgs:input: raw bytes content of the input mp3 file, or its file pathReturn:str: a string with the text corresponding to the mp3 input file"""model = whisper.load_model("tiny")if isinstance(input, bytes):with tempfile.NamedTemporaryFile(suffix=".mp3", delete=True) as tmp:tmp.write(input)tmp.flush()result = model.transcribe(tmp.name)elif isinstance(input, str) and os.path.exists(input):# Safe if the HF environment mounts the fileresult = model.transcribe(input)else:raise TypeError("Unsupported input type. Expected bytes or a valid file path.")return result["text"]self.list_tools=[DuckDuckGoSearchTool(), audio_interpreter]self.agent = CodeAgent(tools=self.list_tools,model=self.model,additional_authorized_imports=['pandas','io', 'requests','markdownify'],max_steps=10,add_base_tools=True # Add any additional base tools#planning_interval=3 # Enable planning every 3 steps) #-1 to suppress display of reasoning steps)print("BasicAgent initialized.")#Retry policy if quota exceededdef retry(self, prompt):backoff = 20while True:try:response = self.agent.run(prompt)return responsebreak # Successexcept Exception as e:if "429" in str(e):print(f"Rate limit hit. Sleeping for {backoff} seconds...")time.sleep(backoff)backoff = min(backoff * 2, 80) # max backoff = 80 secondselse:print("Error:", e)breakdef __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")prompt=f'{self.base_prompt}\n {question}'answer = self.retry(prompt)print(f"Agent returning fixed answer: {answer}")return answer
agent.py+106-220