Spaces:
Sleeping
Sleeping
EtienneB commited on
Commit ·
ffa4ee4
1
Parent(s): 7da4369
update
Browse filesFiles changed (8)
- .gitignoreAdded+1
- __pycache__/agent.cpython-313.pycAdded
- __pycache__/retriever.cpython-313.pycAdded
- __pycache__/tools.cpython-313.pycAdded
- agent.py+8-4
- app.py+38-4
- requirements.txt+6-1
- tools.py+51
1.env12345678910111213142 unmodified lines171819202122237 unmodified lines313233343536from typing import Annotated, TypedDictfrom langchain_core.messages import AIMessage, AnyMessage, HumanMessagefrom langchain_huggingface import ChatHuggingFace, HuggingFaceEndpointfrom langgraph.graph import START, StateGraphfrom langgraph.graph.message import add_messagesfrom langgraph.prebuilt import ToolNode, tools_conditionfrom retriever import guest_info_toolfrom tools import (absolute, add, divide, exponential, floor_divide, logarithm,modulus, multiply, power, square_root, subtract, web_search)# Generate the chat interface, including the toolsllm = HuggingFaceEndpoint(2 unmodified lines)chat = ChatHuggingFace(llm=llm, verbose=True)tools = [, weather_info_tool, hub_stats_tool]tools = [multiply,add,7 unmodified lineslogarithm,exponential,web_search,]chat_with_tools = chat.bind_tools(tools)12345678910111213141516172 unmodified lines2021222324257 unmodified lines3334353637383940from typing import Annotated, TypedDictfrom langchain_community.chat_models import ChatHuggingFacefrom langchain_community.llms import HuggingFaceEndpointfrom langchain_core.messages import AIMessage, AnyMessage, HumanMessagefrom langgraph.graph import START, StateGraphfrom langgraph.graph.message import add_messagesfrom langgraph.prebuilt import ToolNode, tools_conditionfrom retriever import guest_info_toolfrom tools import (absolute, add, divide, exponential, floor_divide,get_current_time_in_timezone, logarithm, modulus, multiply,power, roman_calculator_converter, square_root, subtract,web_search)# Generate the chat interface, including the toolsllm = HuggingFaceEndpoint(2 unmodified lines)chat = ChatHuggingFace(llm=llm, verbose=True)tools = [multiply,add,7 unmodified lineslogarithm,exponential,web_search,roman_calculator_converter,get_current_time_in_timezone,]chat_with_tools = chat.bind_tools(tools)
3 unmodified lines4567891011121314151617181920212223242526273 unmodified linesimport gradio as grimport pandas as pdimport requestsfrom agent import build_graphfrom langchain_core.messages import HumanMessage# (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.")self.graph = build_graph()def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."messages = [HumanMessage(content=question)]messages = self.graph.invoke({"messages": messages})answer = messages['messages'][-1].contentreturn answer[14:]3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960613 unmodified linesimport gradio as grimport pandas as pdimport requestsfrom dotenv import load_dotenvfrom langchain_community.chat_models import ChatHuggingFacefrom langchain_community.llms import HuggingFaceEndpointfrom langchain_core.messages import HumanMessagefrom tools import (absolute, add, divide, exponential, floor_divide,get_current_time_in_timezone, logarithm, modulus, multiply,power, roman_calculator_converter, square_root, subtract,web_search)# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"MAX_AGENT_ITERATIONS = 15load_dotenv()HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):print("BasicAgent initialized.")self.llm = HuggingFaceEndpoint(repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,)self.chat = ChatHuggingFace(llm=self.llm, verbose=True)self.tools = [multiply,add,subtract,power,divide,modulus,square_root,floor_divide,absolute,logarithm,exponential,web_search,roman_calculator_converter,get_current_time_in_timezone,]self.chat_with_tools = self.chat.bind_tools(tools)print(f"Total tools available: {len(self.tools)}")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")# Question in a HumanMessage from langchain_coremessages = [HumanMessage(content=question)]messages = self.chat_with_tools.invoke({"messages": messages})answer = messages['messages'][-1].contentreturn answer[14:]
1 unmodified line234567891 unmodified linerequests# LangChain dependencieslangchain-core#other# inspect1 unmodified line2345678910111213141 unmodified linerequests# LangChain dependencieslangchainlangchain-corelangchain-communitylanggraphhuggingface_hub#other# inspectpython-dotenvgradio[oauth]
179 unmodified lines1801811821831841857 unmodified lines193194195179 unmodified lines"""return math.exp(x)@tooldef web_search(query: str) -> str:"""Performs a DuckDuckGo search for the given query and returns the results.7 unmodified linessearch_tool = DuckDuckGoSearchRun()return search_tool.invoke(query)179 unmodified lines1801811821831841851867 unmodified lines194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246179 unmodified lines"""return math.exp(x)@tooldef web_search(query: str) -> str:"""Performs a DuckDuckGo search for the given query and returns the results.7 unmodified linessearch_tool = DuckDuckGoSearchRun()return search_tool.invoke(query)@tooldef roman_calculator_converter(value1:int, value2:int, oper:str) -> str:"""A tool that performs an operator on 2 numbers to calculate the resultArgs:value1: the first valuevalue2: the second valueoper: operator for the calculation, like "add", "substract", "multiply", "divide""""roman_numerals = {1000: "M", 900: "CM", 500: "D", 400: "CD",100: "C", 90: "XC", 50: "L", 40: "XL",10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"}roman_string = ""if oper == "add":result = value1 + value2elif oper == "subtract":result = value2 - value1elif oper == "divide":result = value1 / value2elif oper == "multiply":result = value1 * value2else:return "Unsupported operation. Please use 'add' or 'subtract'."for value, numeral in roman_numerals.items():while result >= value:roman_string += numeralresult -= valuereturn f"The result of {oper} on the values {value1} and {value2} is the Roman numeral: {roman_string}"@tooldef get_current_time_in_timezone(timezone: str) -> str:"""A tool that fetches the current local time in a specified timezone.Args:timezone: A string representing a valid timezone (e.g., 'America/New_York')."""try:# Create timezone objecttz = pytz.timezone(timezone)# Get current time in that timezonelocal_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")return f"The current local time in {timezone} is: {local_time}"except Exception as e:return f"Error fetching time for timezone '{timezone}': {str(e)}"
.gitignoreAdded+1
__pycache__/agent.cpython-313.pycAdded
__pycache__/retriever.cpython-313.pycAdded
__pycache__/tools.cpython-313.pycAdded
agent.py+8-4
app.py+38-4
requirements.txt+6-1
tools.py+51