Spaces:
Sleeping
Sleeping
Agent
Browse filesFiles changed (4)
- .gitignoreAdded+2
- app.py+52-37
- custom_agent.pyAdded+195
- requirements.txt+19-1
12.env/venv/1234456789101112131314151617181920212214151617181920212822232431252627285 unmodified lines34353643373839408 unmodified lines49505158595253545556575865666759606162636410 unmodified lines7576778485787980818283848586878887888990919293949596979899100101949510210310410510610710810911063 unmodified lines1741751761651771781791801811821691701711721831841851751861871881781891901911921 unmodified line194195196186197198199189200201202203191204205206207193208209210196211import osimport gradio as grimport requestsimport inspectimport pandas as pdfrom custom_agent import CustomAgent
# (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_answer
def run_and_submit_all( profile: gr.OAuthProfile | None):
def run_and_submit_all(profile: gr.OAuthProfile | None): """ Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results. """ # --- Determine HF Space Runtime URL and Repo URL --- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
if profile: username= f"{profile.username}" username = f"{profile.username}" print(f"User logged in: {username}") else: print("User not logged in.")5 unmodified lines
# 1. Instantiate Agent ( modify this part to create your agent) try: agent = BasicAgent() agent = CustomAgent() except Exception as e: print(f"Error instantiating agent: {e}") return f"Error initializing agent: {e}", None8 unmodified lines response.raise_for_status() questions_data = response.json() if not questions_data: print("Fetched questions list is empty.") return "Fetched questions list is empty or invalid format.", None print("Fetched questions list is empty.") return "Fetched questions list is empty or invalid format.", None print(f"Fetched {len(questions_data)} questions.") except requests.exceptions.RequestException as e: print(f"Error fetching questions: {e}") return f"Error fetching questions: {e}", None except requests.exceptions.JSONDecodeError as e: print(f"Error decoding JSON response from questions endpoint: {e}") print(f"Response text: {response.text[:500]}") return f"Error decoding server response for questions: {e}", None print(f"Error decoding JSON response from questions endpoint: {e}") print(f"Response text: {response.text[:500]}") return f"Error decoding server response for questions: {e}", None except Exception as e: print(f"An unexpected error occurred fetching questions: {e}") return f"An unexpected error occurred fetching questions: {e}", None10 unmodified lines continue try: submitted_answer = agent(question_text) answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer}) results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}) answers_payload.append( {"task_id": task_id, "submitted_answer": submitted_answer} ) results_log.append( { "Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer, } ) except Exception as e: print(f"Error running agent on task {task_id}: {e}") results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"}) print(f"Error running agent on task {task_id}: {e}") results_log.append( { "Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}", } )
if not answers_payload: print("Agent did not produce any answers to submit.") return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
# 4. Prepare Submission submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} # 4. Prepare Submission submission_data = { "username": username.strip(), "agent_code": agent_code, "answers": answers_payload, } status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." print(status_update)
63 unmodified lines
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False) status_output = gr.Textbox( label="Run Status / Submission Result", lines=5, interactive=False ) # Removed max_rows=10 from DataFrame constructor results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click( fn=run_and_submit_all, outputs=[status_output, results_table] ) run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
if __name__ == "__main__": print("\n" + "-"*30 + " App Starting " + "-"*30) print("\n" + "-" * 30 + " App Starting " + "-" * 30) # Check for SPACE_HOST and SPACE_ID at startup for information space_host_startup = os.getenv("SPACE_HOST") space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
if space_host_startup: print(f"✅ SPACE_HOST found: {space_host_startup}")1 unmodified line else: print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup: # Print repo URLs if SPACE_ID is found if space_id_startup: # Print repo URLs if SPACE_ID is found print(f"✅ SPACE_ID found: {space_id_startup}") print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main") print( f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main" ) else: print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.") print( "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined." )
print("-"*(60 + len(" App Starting ")) + "\n") print("-" * (60 + len(" App Starting ")) + "\n")
print("Launching Gradio Interface for Basic Agent Evaluation...") demo.launch(debug=True, share=False) demo.launch(debug=True, share=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195from langgraph.prebuilt import create_react_agentfrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langchain_community.document_loaders import WikipediaLoaderfrom langchain_community.document_loaders import ArxivLoaderfrom dotenv import load_dotenv, find_dotenvfrom langchain_core.tools import toolfrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import SupabaseVectorStorefrom langchain_core.messages import HumanMessagefrom supabase import create_client, Clientimport os
load_dotenv(find_dotenv())
DEFAULT_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.
"""
@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}
@tooldef multiply(a: int, b: int) -> int: """Multiply two numbers. Args: a: first int b: second int """ return a * b
@tooldef add(a: int, b: int) -> int: """Add two numbers.
Args: a: first int b: second int """ return a + b
@tooldef subtract(a: int, b: int) -> int: """Subtract two numbers.
Args: a: first int b: second int """ return a - b
@tooldef divide(a: int, b: int) -> int: """Divide two numbers.
Args: a: first int b: 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 int b: second int """ return a % b
class CustomAgent: def __init__(self): print("CustomAgent initialized.")
# Initialize embeddings and vector store self.embeddings = HuggingFaceEmbeddings( model_name="sentence-transformers/all-mpnet-base-v2" ) print(os.environ.get("SUPABASE_URL")) print(os.environ.get("SUPABASE_SERVICE_KEY"))
self.supabase: Client = create_client( os.environ.get("SUPABASE_URL"), os.environ.get("SUPABASE_SERVICE_ROLE_KEY") )
self.vector_store = SupabaseVectorStore( client=self.supabase, embedding=self.embeddings, table_name="documents_1", query_name="match_documents_1", )
# Create the agent self.agent = create_react_agent( model="openai:gpt-4-1106-preview", tools=[ web_search, add, subtract, multiply, divide, modulus, wiki_search, arvix_search, ], prompt=DEFAULT_PROMPT, )
def retriever(self, query: str): """Retriever""" similar_question = self.vector_store.similarity_search(query) return HumanMessage( content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}", )
def __call__(self, question: str) -> str: """Run the agent on a question and return the answer.""" print(f"CustomAgent received question (first 50 chars): {question[:50]}...")
try: answer = self.agent.invoke( { "messages": [ self.retriever(question), HumanMessage(content=question), ] } ) result = answer["messages"][-1].content print(f"CustomAgent returning answer: {result}") return result except Exception as e: print(f"Error in CustomAgent: {e}") return f"Error: {e}"
if __name__ == "__main__": agent = CustomAgent() agent( 'What was the volume in m^3 of the fish bag that was calculated in the University of Leicester paper "Can Hiccup Supply Enough Fish to Maintain a Dragon\u2019s Diet?"' )12234567891011121314151617181920gradiorequestsrequestslangchainlangchain-communitylangchain-corelangchain-google-genailangchain-huggingfacelangchain-tavilylangchain-chromalanggraphhuggingface_hubsupabasearxivpymupdfwikipediapgvectorpython-dotenvpytesseractmatplotlibsentence-transformers.gitignoreAdded+2
app.py+52-37
custom_agent.pyAdded+195
requirements.txt+19-1