Spaces:
Sleeping
Sleeping
base_agent (ReAct) first commit
Browse filesFiles changed (6)
- .gitignoreAdded+7
- app.py+12-11
- basic_agent.pyAdded+86
- requirements.txt+7-2
- test_models.pyAdded+45
- tools.pyAdded+19
1234567.venv/venv/__pycache__*.pyc*.pyo*.pyd.env2 unmodified lines3456789101112131415161718192021222316 unmodified lines404142434445462 unmodified linesimport requestsimport inspectimport pandas as pd# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""16 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None2 unmodified lines345678910111213141516171819202122232416 unmodified lines414243444546472 unmodified linesimport requestsimport inspectimport pandas as pdfrom basic_agent import basic_agent# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# # --- Basic Agent Definition ---# # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------# class BasicAgent:# def __init__(self):# print("BasicAgent initialized.")# def __call__(self, question: str) -> str:# print(f"Agent received question (first 50 chars): {question[:50]}...")# fixed_answer = "This is a default answer."# print(f"Agent returning fixed answer: {fixed_answer}")# return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""16 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:agent = basic_agentexcept Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586from langgraph.graph import Graph, add_messagesfrom langchain.prompts import PromptTemplatefrom langchain_ollama.chat_models import ChatOllamafrom langchain_ollama.llms import OllamaLLMfrom langchain.agents import AgentExecutor, create_react_agentfrom langchain_ollama import OllamaEmbeddingsfrom langchain_community.tools import DuckDuckGoSearchRun
EMBEDDINGS_MODEL = "bge-m3"# ollama pull nomic-embed-text# mxbai-embed-largeembeddings = OllamaEmbeddings(model=EMBEDDINGS_MODEL)
CHAT_MODEL = "gemma3:4b"llm = ChatOllama( model=CHAT_MODEL, temperature=0.0, #max_tokens=512, #streaming=True, verbose=True,)
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].YOUR 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."""
REACT_PROMPT = """Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answerThought: you should always think about what to doAction: the action to take, should be one of [{tool_names}]Action Input: the input to the actionObservation: the result of the action... (this Thought/Action/Action Input/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input question
Begin!
Question: {input}Thought:{agent_scratchpad}"""
AGENT_PROMPT = PromptTemplate.from_template(REACT_PROMPT)
# USER_PROMPT_TEMPLATE = """# Answer the following question as best you can. # Do not use a tool if not required. # Question: {question}# """
# user_prompt_template = PromptTemplate.from_template(USER_PROMPT_TEMPLATE)
class BasicAgent():
def __init__(self, prompt=AGENT_PROMPT, tools=[], llm=llm, embeddings=embeddings): print("Agent initialized.") self.llm = llm self.embeddings = embeddings self.tools = tools self.prompt = prompt self.graph = self.__initialize_graph() def __initialize_graph(self): agent = create_react_agent(llm, self.tools, self.prompt) agent_executor = AgentExecutor(agent=agent, tools=self.tools, verbose=True) return agent_executor
def __call__(self, question: str) -> str: print(f"Agent received question (first 50 chars): {question[:50]}...") fixed_answer = self.graph.invoke({"input": question}) print(f"Agent returning fixed answer: {fixed_answer}") return fixed_answer
basic_agent = BasicAgent(tools=[DuckDuckGoSearchRun()])
12gradiorequests1234567duckduckgo-search==8.0.1gradio==5.29.0gradio[oauth]#langchain-community==0.3.23langchain-ollama==0.3.2langgraph==0.4.3requests==2.32.3
123456789101112131415161718192021222324252627282930313233343536373839404142434445from langgraph.graph import Graph, add_messagesfrom langchain_ollama.chat_models import ChatOllamafrom langchain_ollama.llms import OllamaLLMfrom langchain_ollama import OllamaEmbeddings
EMBEDDINGS_MODEL = "bge-m3"# ollama pull nomic-embed-text# mxbai-embed-largeembeddings = OllamaEmbeddings(model=EMBEDDINGS_MODEL)
CHAT_MODEL = "gemma3:4b"llm = ChatOllama( model=CHAT_MODEL, temperature=0.0, #max_tokens=512, #streaming=True, verbose=True,)
GAIA_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].YOUR 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."""
if __name__ == "__main__": print("Executing agent.py")
text = "What is the capital of France?" single_vector = embeddings.embed_query(text) print(str(single_vector)[:100]) # text2 = ( # "LangGraph is a library for building stateful, multi-actor applications with LLMs" # ) # two_vectors = embeddings.embed_documents([text, text2])
messages = [ #("system", "You are a helpful translator. Translate the user sentence to French."), ("human", "What is the capital of France?"), ] response = llm.invoke(messages) print(response)12345678910111213141516171819import requestsfrom langchain_community.tools import DuckDuckGoSearchRun, DuckDuckGoSearchResultsfrom langchain import hub
search = DuckDuckGoSearchRun()search = DuckDuckGoSearchResults(output_format="list")
def search_brave(query): url = f"https://api.brave.com/search?q={query}" response = requests.get(url) return response.json()
if __name__ == "__main__": # query = "What is the capital of France?" # results = search_brave(query) # print(results) prompt = hub.pull('hwchase17/react') print(type(prompt)) print(prompt).gitignoreAdded+7
app.py+12-11
basic_agent.pyAdded+86
requirements.txt+7-2
test_models.pyAdded+45
tools.pyAdded+19