|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from pathlib import Path |
| 5 | +from typing import Dict, List, Any, Callable |
| 6 | +from src.agents.base_agent import Agent |
| 7 | +from src.config.logger import logger |
| 8 | +from src.config.settings import OverpassSettings |
| 9 | +from src.utils.db import summarize, query_hash, payload_hash |
| 10 | +from src.utils.overpass import build_query, run_query, save_json |
| 11 | +from src.memory.store import MemoryStore |
| 12 | + |
| 13 | +Tool = Callable[..., Any] |
| 14 | + |
| 15 | + |
| 16 | +class ScraperAgent(Agent): |
| 17 | + """ |
| 18 | + Agent that fetches `man_made=surveillance` objects from OpenStreetMap via the Overpass API and remembers every step. |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__( |
| 22 | + self, name: str, memory: MemoryStore, tools: Dict[str, Tool] | None = None |
| 23 | + ) -> None: |
| 24 | + """ |
| 25 | + Constructor. |
| 26 | + :param name: The Agent name. |
| 27 | + :param memory: The memory store. |
| 28 | + :param tools: The tools to use. |
| 29 | + """ |
| 30 | + default_tools: Dict[str, Tool] = { |
| 31 | + "run_query": run_query, |
| 32 | + "save_json": save_json, |
| 33 | + } |
| 34 | + super().__init__(name=name, tools=tools or default_tools, memory=memory) |
| 35 | + |
| 36 | + def perceive(self, input_data: Dict[str, Any]) -> Dict[str, Any]: |
| 37 | + """ |
| 38 | + Expect query params and build query text. |
| 39 | + :param input_data: The query params. Eg. `{"city": "Malmö", "overpass_dir": "data"}` |
| 40 | + :return: An enriched observation for subsequent stages |
| 41 | + """ |
| 42 | + |
| 43 | + city = input_data["city"] |
| 44 | + country = input_data.get("country") # new, optional |
| 45 | + query = build_query(city, country=country) |
| 46 | + return { |
| 47 | + "city": city, |
| 48 | + "country": country, |
| 49 | + "query": query, |
| 50 | + "overpass_dir": input_data.get("overpass_dir", "overpass_data"), |
| 51 | + } |
| 52 | + |
| 53 | + def plan(self, observation: Dict[str, Any]) -> List[str]: |
| 54 | + """ |
| 55 | + Very simple two-step plan: (1) fetch → (2) persist. |
| 56 | + :param observation: |
| 57 | + :return: The available steps. |
| 58 | + """ |
| 59 | + return ["run_query", "save_json"] |
| 60 | + |
| 61 | + def act(self, action: str, context: Dict[str, Any]) -> Any: |
| 62 | + """ |
| 63 | + Map action name to the corresponding tool and return its result. |
| 64 | + :param action: The name of the action. |
| 65 | + :param context: The data from `perceive()`. |
| 66 | + :return: The actions result. |
| 67 | + """ |
| 68 | + |
| 69 | + if action not in self.tools: |
| 70 | + raise ValueError(f"No tool named '{action}' found.") |
| 71 | + |
| 72 | + if action == "run_query": |
| 73 | + q_hash = query_hash(context["query"]) |
| 74 | + # Look for a cache entry |
| 75 | + if self.memory: |
| 76 | + for m in self.memory.load(self.name): |
| 77 | + if m.step == "cache" and m.content.startswith(q_hash): |
| 78 | + _, fp, p_hash = m.content.split("|") |
| 79 | + filepath = Path(fp) |
| 80 | + if filepath.exists(): |
| 81 | + # cache hit |
| 82 | + with filepath.open(encoding="utf-8") as f: |
| 83 | + data = json.load(f) |
| 84 | + # double-check integrity |
| 85 | + if payload_hash(data) == p_hash: |
| 86 | + elements = len(data.get("elements", [])) |
| 87 | + # make sure steps down the line have what they need |
| 88 | + context.update( |
| 89 | + { |
| 90 | + "cache_hit": True, |
| 91 | + "data": data, |
| 92 | + "cached_path": str(filepath), |
| 93 | + "elements_count": elements, |
| 94 | + "empty": elements == 0, |
| 95 | + } |
| 96 | + ) |
| 97 | + return data |
| 98 | + # otherwise run the query |
| 99 | + data = self.tools[action](context["query"]) |
| 100 | + elements = len(data.get("elements", [])) |
| 101 | + context.update( |
| 102 | + { |
| 103 | + "cache_hit": False, |
| 104 | + "data": data, |
| 105 | + "elements_count": elements, |
| 106 | + "empty": elements == 0, |
| 107 | + } |
| 108 | + ) |
| 109 | + return data |
| 110 | + |
| 111 | + if action == "save_json": |
| 112 | + # skip if the query returns empty |
| 113 | + if context.get("empty", False): |
| 114 | + # remember so that we don't re-fetch |
| 115 | + self.remember( |
| 116 | + "empty", |
| 117 | + f"{context['city']}|{context.get('country')}|{query_hash(context['query'])}", |
| 118 | + ) |
| 119 | + return "NO_DATA" |
| 120 | + # skip if served from cache |
| 121 | + if context.get("cache_hit"): |
| 122 | + return context["cached_path"] |
| 123 | + overpass_dir = OverpassSettings().dir |
| 124 | + path = self.tools[action](context["data"], context["city"], overpass_dir) |
| 125 | + q_hash = query_hash(context["query"]) |
| 126 | + p_hash = payload_hash(context["data"]) |
| 127 | + self.remember("cache", f"{q_hash}|{path}|{p_hash}") |
| 128 | + return str(path) |
| 129 | + |
| 130 | + raise NotImplementedError(action) |
| 131 | + |
| 132 | + def achieve_goal(self, input_data: Dict[str, Any]) -> Dict[str, Any]: |
| 133 | + """ |
| 134 | + Orchestrates the entire agent life-cycle while keeping every intermediate result |
| 135 | + alive, inspectable, and persisted. Overridden to keep the whole `context` alive between steps. |
| 136 | + :param input_data: The user raw input. |
| 137 | + :return: The final context dictionary produced by the run. |
| 138 | + """ |
| 139 | + observation = self.perceive(input_data) |
| 140 | + plan_steps = self.plan(observation) |
| 141 | + # A shallow copy of observation i.e. the original object is not mutated. |
| 142 | + # From here on context is shared and every stage can read or extend. |
| 143 | + context: Dict[str, Any] = {**observation} |
| 144 | + |
| 145 | + for step in plan_steps: |
| 146 | + result = self.act(step, context) |
| 147 | + self.remember(step, summarize(result)) |
| 148 | + context[step] = result |
| 149 | + |
| 150 | + if context.get("empty"): |
| 151 | + logger.warning( |
| 152 | + f"[ScraperAgent] WARNING: 0 surveillance objects found for " |
| 153 | + f"{context['city']} ({context.get('country', 'no country')})" |
| 154 | + ) |
| 155 | + return context |
0 commit comments