CoolFace
Apppublic

mansiTeamB/Assignment_agents

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
agent.py225 linesDownload Raw Back to root
1import os2from dotenv import load_dotenv3from langgraph.graph import START, StateGraph, MessagesState4from langgraph.prebuilt import tools_condition, ToolNode5from langchain_google_genai import ChatGoogleGenerativeAI6from langchain_groq import ChatGroq7from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings8from langchain_community.tools.tavily_search import TavilySearchResults9from langchain_community.document_loaders import WikipediaLoader, ArxivLoader10from langchain_community.vectorstores import Chroma11from langchain_core.documents import Document12from langchain_core.messages import SystemMessage, HumanMessage13from langchain_core.tools import tool14from langchain.tools.retriever import create_retriever_tool15import json16from langchain_community.vectorstores import Chroma17# from langchain.vectorstores import Chroma18from langchain_community.embeddings import HuggingFaceEmbeddings19from langchain.schema import Document20 21load_dotenv()22 23os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"24groq_api_key = os.getenv("GROQ_API_KEY")25 26# Tools27@tool28def multiply(a: int, b: int) -> int:29    """Multiply two numbers.30    Args:31        a: first int32        b: second int33    """34    return a * b35 36@tool37def add(a: int, b: int) -> int:38    """Add two numbers.39    40    Args:41        a: first int42        b: second int43    """44    return a + b45 46@tool47def subtract(a: int, b: int) -> int:48    """Subtract two numbers.49    50    Args:51        a: first int52        b: second int53    """54    return a - b55 56@tool57def divide(a: int, b: int) -> int:58    """Divide two numbers.59    60    Args:61        a: first int62        b: second int63    """64    if b == 0:65        raise ValueError("Cannot divide by zero.")66    return a / b67 68@tool69def modulus(a: int, b: int) -> int:70    """Get the modulus of two numbers.71    72    Args:73        a: first int74        b: second int75    """76    return a % b77 78@tool79def wiki_search(query: str) -> str:80    """Search Wikipedia for a query and return maximum 2 results.81    82    Args:83        query: The search query."""84    search_docs = WikipediaLoader(query=query, load_max_docs=2).load()85    formatted_search_docs = "\n\n---\n\n".join(86        [87            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'88            for doc in search_docs89        ])90    return {"wiki_results": formatted_search_docs}91 92@tool93def web_search(query: str) -> str:94    """Search Tavily for a query and return maximum 3 results.95    96    Args:97        query: The search query."""98    search_docs = TavilySearchResults(max_results=3).invoke(query=query)99    formatted_search_docs = "\n\n---\n\n".join(100        [101            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'102            for doc in search_docs103        ])104    return {"web_results": formatted_search_docs}105 106@tool107def arvix_search(query: str) -> str:108    """Search Arxiv for a query and return maximum 3 result.109    110    Args:111        query: The search query."""112    search_docs = ArxivLoader(query=query, load_max_docs=3).load()113    formatted_search_docs = "\n\n---\n\n".join(114        [115            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'116            for doc in search_docs117        ])118    return {"arvix_results": formatted_search_docs}119 120@tool121def similar_question_search(question: str) -> str:122    """Search the vector database for similar questions and return the first results.123    124    Args:125        question: the question human provided."""126    matched_docs = vector_store.similarity_search(query, 3)127    formatted_search_docs = "\n\n---\n\n".join(128        [129            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'130            for doc in matched_docs131        ])132    return {"similar_questions": formatted_search_docs}133 134# Load system prompt135system_prompt = """136You are a helpful assistant tasked with answering questions using a set of tools. 137Now, I will ask you a question. Report your thoughts, and finish your answer with the following template: 138FINAL ANSWER: [YOUR FINAL ANSWER]. 139YOUR FINAL 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.140Your answer should only start with "FINAL ANSWER: ", then follows with the answer. 141"""142 143# System message144sys_msg = SystemMessage(content=system_prompt)145 146embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")147 148with open('metadata.jsonl', 'r') as jsonl_file:149    json_list = list(jsonl_file)150 151json_QA = []152for json_str in json_list:153    json_data = json.loads(json_str)154    json_QA.append(json_data)155 156documents = []157for sample in json_QA:158    content = f"Question : {sample['Question']}\n\nFinal answer : {sample['Final answer']}"159    metadata = {"source": sample["task_id"]}160    documents.append(Document(page_content=content, metadata=metadata))161 162# Initialize vector store and add documents163vector_store = Chroma.from_documents(164    documents=documents,165    embedding=embeddings,166    persist_directory="./chroma_db",167    collection_name="my_collection"168)169vector_store.persist()170print("Documents inserted:", vector_store._collection.count())171 172 173# Retriever tool (optional if you want to expose to agent)174retriever_tool = create_retriever_tool(175    retriever=vector_store.as_retriever(),176    name="Question Search",177    description="A tool to retrieve similar questions from a vector store.",178)179 180# Tool list181tools = [182    multiply, add, subtract, divide, modulus,183    wiki_search, web_search, arvix_search,184]185 186# Build graph187def build_graph(provider: str = "groq"):188    # if provider == "google":189    #     llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)190    # elif provider == "groq":191    #     llm = ChatGroq(model="qwen-qwq-32b", temperature=0)192    # elif provider == "huggingface":193    #     llm = ChatHuggingFace(194    #     llm=HuggingFaceEndpoint(195    #         repo_id="mosaicml/mpt-30b",196    #         temperature=0,197    #     )198    # )199    # else:200    #     raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")201 202    # llm_with_tools = llm.bind_tools(tools)203    llm = ChatGroq(model="qwen-qwq-32b", temperature=0,api_key=groq_api_key)204    llm_with_tools = llm.bind_tools(tools)205 206    def assistant(state: MessagesState):207        return {"messages": [llm_with_tools.invoke(state["messages"])]}208 209    def retriever(state: MessagesState):210        similar = vector_store.similarity_search(state["messages"][0].content)211        if similar:212            example_msg = HumanMessage(content=f"Here is a similar question:\n\n{similar[0].page_content}")213            return {"messages": [sys_msg] + state["messages"] + [example_msg]}214        return {"messages": [sys_msg] + state["messages"]}215 216    builder = StateGraph(MessagesState)217    builder.add_node("retriever", retriever)218    builder.add_node("assistant", assistant)219    builder.add_node("tools", ToolNode(tools))220    builder.add_edge(START, "retriever")221    builder.add_edge("retriever", "assistant")222    builder.add_conditional_edges("assistant", tools_condition)223    builder.add_edge("tools", "assistant")224 225    return builder.compile()