"""Tool Calls tracking example for SecAFS Python SDK"""
import asyncio
import json
import time
from secafs_sdk import SecAFS, SecAFSOptions
async def main():
secafs_inst = await SecAFS.open(SecAFSOptions(id="toolcalls-demo"))
print("=== Tool Call Tracking Example ===\n")
print("1. Tracking a successful web search:")
start_time1 = int(time.time())
await asyncio.sleep(0.1)
end_time1 = int(time.time())
search_id = await secafs_inst.tools.record(
"web_search",
start_time1,
end_time1,
parameters={"query": "AI agents and LLMs", "maxResults": 10},
result={
"results": [
{"title": "Understanding AI Agents", "url": "https://example.com/1"},
{"title": "LLM Best Practices", "url": "https://example.com/2"},
],
"count": 2,
},
)
print(f" Recorded tool call with ID: {search_id}\n")
print("2. Tracking a failed API call:")
start_time2 = int(time.time())
await asyncio.sleep(0.05)
end_time2 = int(time.time())
api_id = await secafs_inst.tools.record(
"api_call",
start_time2,
end_time2,
parameters={"endpoint": "/users", "method": "GET"},
error="Connection timeout after 30s",
)
print(f" Recorded failed call with ID: {api_id}\n")
print("3. Tracking multiple database queries:")
for i in range(3):
start = int(time.time())
await asyncio.sleep(0.02)
end = int(time.time())
await secafs_inst.tools.record(
"database_query",
start,
end,
parameters={"sql": f"SELECT * FROM users WHERE id = {i + 1}"},
result={"rows": 1},
)
print(" Created 3 database query records\n")
print("4. Using start/success pattern:")
call_id = await secafs_inst.tools.start("data_processing", {"file": "data.csv"})
await asyncio.sleep(0.05)
await secafs_inst.tools.success(call_id, {"rows_processed": 1000})
print(f" Completed tool call {call_id}\n")
print("5. Querying tool calls by name:")
searches = await secafs_inst.tools.get_by_name("web_search")
print(f" Found {len(searches)} web search calls")
if searches:
search = searches[0]
print(f" - Duration: {search.duration_ms}ms")
print(f" - Parameters: {json.dumps(search.parameters)}")
print(f" - Result: {json.dumps(search.result)}")
print()
print("6. Getting recent tool calls:")
one_minute_ago = int(time.time()) - 60
recent = await secafs_inst.tools.get_recent(one_minute_ago)
print(f" Found {len(recent)} calls in the last minute:")
for tc in recent:
status = "failed" if tc.error else "success"
print(f" - {tc.name} ({status})")
print()
print("7. Performance statistics:")
stats = await secafs_inst.tools.get_stats()
print(" Tool Performance:")
for stat in stats:
print(f" - {stat.name}:")
print(f" Total: {stat.total_calls}, Success: {stat.successful}, Failed: {stat.failed}")
print(f" Avg Duration: {stat.avg_duration_ms:.2f}ms")
await secafs_inst.close()
print("\n✓ Example completed successfully!")
if __name__ == "__main__":
asyncio.run(main())