Skip to content

Commit 242efab

Browse files
authored
Merge pull request #46 from jethronap/38_logging
38 logging
2 parents 7fa735d + 14b4620 commit 242efab

File tree

6 files changed

+84
-36
lines changed

6 files changed

+84
-36
lines changed

src/agents/analyser_agent.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
)
2121
from src.tools.mapping_tools import to_heatmap
2222
from src.tools.stat_tools import compute_statistics
23-
23+
from src.utils.decorators import log_action
2424

2525
Tool = Callable[..., Any]
2626

@@ -76,6 +76,7 @@ def plan(self, observation: Dict[str, Any]) -> List[str]:
7676
steps.append("report")
7777
return steps
7878

79+
@log_action
7980
def act(self, action: str, context: Dict[str, Any]) -> Any:
8081
if action not in self.tools:
8182
raise ValueError(f"No tool named '{action}' found.")

src/tools/ollama_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from src.config.logger import logger
44

55
from src.config.settings import OllamaSettings
6-
from src.utils.retry import with_retry
6+
from src.utils.decorators import with_retry
77

88

99
class OllamaClient:

src/utils/decorators.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import time
2+
from functools import wraps
3+
from typing import Callable, Dict, Any
4+
5+
import requests
6+
from loguru import logger
7+
8+
from src.config.settings import OverpassSettings
9+
10+
11+
def log_action(fn):
12+
"""
13+
Decorator for logging:
14+
- INFO at start/end (with elapsed time)
15+
- DEBUG of args/kwargs and a short repr(result)
16+
- exception() on error
17+
"""
18+
19+
@wraps(fn)
20+
def wrapped(self, *args, **kwargs):
21+
agent = getattr(self, "name", fn.__qualname__)
22+
action = fn.__name__
23+
24+
logger.info(f"{agent}.{action}")
25+
26+
# DEBUG: key arguments
27+
# if first arg is a string show it
28+
if args:
29+
first = args[0]
30+
logger.debug(f"{agent}.{action} args[0]={first!r}")
31+
# if there's a context dict, log its size
32+
ctx = kwargs.get("context") or (args[1] if len(args) > 1 else None)
33+
if isinstance(ctx, dict):
34+
logger.debug(f"{agent}.{action} context_keys={list(ctx.keys())}")
35+
36+
start = time.time()
37+
result = fn(self, *args, **kwargs)
38+
elapsed = time.time() - start
39+
40+
# build a small result hint
41+
hint = ""
42+
if isinstance(result, (list, tuple)):
43+
hint = f" (count={len(result)})"
44+
elif isinstance(result, str) and result.endswith(
45+
(".json", ".geojson", ".html")
46+
):
47+
hint = f" → {result!r}"
48+
49+
logger.info(f"{agent}.{action}: in {elapsed:.2f}s{hint}")
50+
return result
51+
52+
return wrapped
53+
54+
55+
def with_retry(
56+
fn: Callable[..., Dict[str, Any]], settings: OverpassSettings = OverpassSettings()
57+
):
58+
"""
59+
Decorator that retries fn(*args, **kwargs) on non-permanent Overpass errors
60+
"""
61+
62+
def wrapped(*args, **kwargs):
63+
attempt = 0
64+
while True:
65+
attempt += 1
66+
try:
67+
response = fn(*args, **kwargs)
68+
return response
69+
except requests.HTTPError as e:
70+
if e.response.status_code not in settings.retry_http:
71+
raise
72+
except (requests.ConnectionError, requests.Timeout):
73+
pass
74+
if attempt >= settings.max_attempts:
75+
raise
76+
delay = settings.base_delay * 2 ** (attempt - 1)
77+
time.sleep(min(delay, 60))
78+
79+
return wrapped

src/utils/overpass.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import textwrap
44
import requests
55
from src.config.settings import OverpassSettings
6-
from src.utils.retry import with_retry
6+
from src.utils.decorators import with_retry
77

88

99
def best_area_candidate(results: list[Dict[str, Any]]) -> tuple[int, str]:

src/utils/retry.py

Lines changed: 0 additions & 32 deletions
This file was deleted.

tests/utils/test_retry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import requests
22
import pytest
3-
from src.utils.retry import with_retry
3+
from src.utils.decorators import with_retry
44
from src.config.settings import OverpassSettings
55
from tests.conftest import http_error
66

0 commit comments

Comments
 (0)