Spaces:
Runtime error
Runtime error
| from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| from typing import Optional, Dict, Any, List | |
| import requests | |
| from pydantic import BaseModel, Field, validator, FieldValidator | |
| class PDOKLocationSearchInput(BaseModel): | |
| postal_code: Optional[str] = Field(None, description="Postal code in the format '1234 AA'.") | |
| house_number: Optional[str] = Field(None, description="House number.") | |
| street_name: Optional[str] = Field(None, description="Street name.") | |
| city: Optional[str] = Field(None, description="City name.") | |
| def validate_postal_code(cls, v): | |
| if v is not None and (len(v) != 7 or not v[0:4].isdigit() or v[4] != " " or not v[5:7].isalpha()): | |
| raise ValueError("Invalid postal code format. It must be '1234 AA'.") | |
| return v | |
| def construct_query(self) -> str: | |
| """Constructs the query string based on provided inputs.""" | |
| if self.postal_code and self.house_number: | |
| return f"{self.postal_code} {self.house_number}" | |
| elif self.street_name and self.city and self.house_number: | |
| return f"{self.street_name} {self.house_number}, {self.city}" | |
| else: | |
| return "" | |
| class PDOKLocationInfo(BaseModel): | |
| type: str | |
| weergavenaam: str | |
| straatnaam: str | |
| huisnummer: int | |
| huisletter: Optional[str] | |
| huisnummertoevoeging: Optional[str] | |
| postcode: str | |
| woonplaatsnaam: str | |
| gemeentenaam: str | |
| provincienaam: str | |
| centroide_ll: str | |
| centroide_rd: str | |
| def pdok_location_info(postal_code: Optional[str] = None, house_number: Optional[str] = None, street_name: Optional[str] = None, city: Optional[str] = None) -> Optional[PDOKLocationInfo]: | |
| """Provides information about a Dutch address or postal code. | |
| Args: | |
| postal_code: Postal code in the format '1234 AA'. | |
| house_number: House number. | |
| street_name: Street name. | |
| city: City name. | |
| Returns: | |
| A PDOKLocationInfo object containing the location information, or None if no results are found. | |
| """ | |
| base_url = "https://api.pdok.nl/bzk/locatieserver/search/v3_1/free" | |
| headers = {"accept": "application/json"} | |
| input_data = PDOKLocationSearchInput(postal_code=postal_code, house_number=house_number, street_name=street_name, city=city) | |
| query_string = input_data.construct_query() | |
| if not query_string: | |
| return None | |
| params = { | |
| "q": query_string, | |
| "fl": "*", # Request all fields | |
| "fq": "type:(gemeente OR woonplaats OR weg OR postcode OR adres)", | |
| "df": "tekst", | |
| "bq": "type:provincie^1.5", | |
| "bq": "type:gemeente^1.5", | |
| "bq": "type:woonplaats^1.5", | |
| "bq": "type:weg^1.5", | |
| "bq": "type:postcode^0.5", | |
| "bq": "type:adres^1", | |
| "start": 0, | |
| "rows": 10, | |
| "sort": "score desc,sortering asc,weergavenaam asc", | |
| "wt": "json", | |
| } | |
| try: | |
| response = requests.get(base_url, params=params, headers=headers) | |
| response.raise_for_status() | |
| data = response.json() | |
| docs = data.get("response", {}).get("docs", []) | |
| if not docs: | |
| return None | |
| first_result = docs[0] | |
| location_info = PDOKLocationInfo(**first_result) | |
| # Format the output in a more user-friendly way | |
| print(f"Information about: {location_info.weergavenaam}") | |
| print("-" * 30) | |
| for field, value in location_info.dict().items(): | |
| print(f" {field.capitalize()}: {value}") | |
| return location_info | |
| except requests.exceptions.RequestException as e: | |
| print(f"Error during API request: {e}") | |
| return None | |
| except (ValueError, KeyError) as e: | |
| print(f"Error processing API response: {e}") | |
| return None | |
| def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type | |
| #Keep this format for the description / args / args description but feel free to modify the tool | |
| """A tool that does nothing yet | |
| Args: | |
| arg1: the first argument | |
| arg2: the second argument | |
| """ | |
| return "What magic will you build ?" | |
| def 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 object | |
| tz = pytz.timezone(timezone) | |
| # Get current time in that timezone | |
| local_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)}" | |
| final_answer = FinalAnswerTool() | |
| # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder: | |
| # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded | |
| custom_role_conversions=None, | |
| ) | |
| # Import tool from Hub | |
| image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
| with open("prompts.yaml", 'r') as stream: | |
| prompt_templates = yaml.safe_load(stream) | |
| agent = CodeAgent( | |
| model=model, | |
| tools=[final_answer, get_current_time_in_timezone, pdok_location_info], ## add your tools here (don't remove final answer) | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() |