agAdvisor / client_example.py
tirtho149's picture
Deploy AgAdvisor
b30f068 verified
Raw
History Blame Contribute Delete
6.58 kB
#!/usr/bin/env python3
"""
Example client for the Agentic AI System API.
This demonstrates how to interact with the real-world API.
"""
import requests
import json
import time
from typing import Dict, Any
class AgenticAIClient:
"""Client for the Agentic AI System API."""
def __init__(self, base_url: str = "http://localhost:8000", api_key: str = "demo-key-12345"):
"""Initialize the client."""
self.base_url = base_url.rstrip('/')
self.api_key = api_key
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def health_check(self) -> Dict[str, Any]:
"""Check system health."""
response = requests.get(f"{self.base_url}/health")
return response.json()
def process_query(self, query: str, include_debug: bool = False, max_api_calls: int = 5) -> Dict[str, Any]:
"""Process a natural language query."""
data = {
"query": query,
"include_debug": include_debug,
"max_api_calls": max_api_calls,
"metadata": {
"client": "python_client",
"timestamp": time.time()
}
}
response = requests.post(
f"{self.base_url}/query",
headers=self.headers,
json=data
)
return response.json()
def list_apis(self) -> Dict[str, Any]:
"""List available API operations."""
response = requests.get(
f"{self.base_url}/apis",
headers=self.headers
)
return response.json()
def register_api(self, name: str, method: str, endpoint: str, description: str, tags: list = None) -> Dict[str, Any]:
"""Register a new API operation."""
data = {
"name": name,
"method": method,
"endpoint": endpoint,
"description": description,
"tags": tags or [],
"parameters": []
}
response = requests.post(
f"{self.base_url}/apis",
headers=self.headers,
json=data
)
return response.json()
def extract_keywords(self, query: str) -> Dict[str, Any]:
"""Extract keywords from a query."""
response = requests.get(
f"{self.base_url}/keywords/{query}",
headers=self.headers
)
return response.json()
def get_stats(self) -> Dict[str, Any]:
"""Get system statistics (requires admin permissions)."""
response = requests.get(
f"{self.base_url}/stats",
headers=self.headers
)
return response.json()
def demo_client():
"""Demonstrate the API client."""
print("πŸš€ Agentic AI System - API Client Demo")
print("=" * 50)
# Initialize client
client = AgenticAIClient()
try:
# Health check
print("\\n1. Health Check:")
health = client.health_check()
print(f" Status: {health['status']}")
print(f" Uptime: {health['uptime']:.2f}s")
print(f" Total Requests: {health['total_requests']}")
# List available APIs
print("\\n2. Available APIs:")
apis = client.list_apis()
for api in apis[:3]:
print(f" β€’ {api['name']} ({api['method']} {api['endpoint']})")
# Process queries
test_queries = [
"Find machine learning datasets for image classification",
"Get user profile information",
"Retrieve CDMS labels for natural language processing"
]
print("\\n3. Processing Queries:")
for i, query in enumerate(test_queries, 1):
print(f"\\n Query {i}: {query}")
result = client.process_query(query, include_debug=True)
if result['success']:
print(f" βœ… Success ({result['processing_time']:.3f}s)")
# Show results summary
results = result['results']
query_info = results.get('query', {})
api_matches = results.get('api_matches', {})
execution_results = results.get('results', {})
print(f" πŸ“ Keywords: {query_info.get('keywords', [])[:3]}")
print(f" 🎯 Intent: {query_info.get('intent', 'unknown')}")
print(f" πŸ”— API Matches: {api_matches.get('count', 0)}")
print(f" ⚑ Executed: {execution_results.get('executed_count', 0)} APIs")
print(f" πŸ“Š Summary: {results.get('summary', 'N/A')[:80]}...")
else:
print(f" ❌ Failed: {result.get('error_message', 'Unknown error')}")
# Keyword extraction
print("\\n4. Keyword Extraction:")
keywords_result = client.extract_keywords("Create a new machine learning model for classification")
print(f" Keywords: {keywords_result['keywords'][:5]}")
# Register a new API
print("\\n5. Registering New API:")
try:
register_result = client.register_api(
name="testNewAPI",
method="POST",
endpoint="/test/new",
description="Test API for demonstration",
tags=["test", "demo"]
)
print(f" βœ… {register_result['message']}")
except Exception as e:
print(f" ⚠️ Registration: {e}")
print("\\n" + "=" * 50)
print("πŸŽ‰ API Client Demo Completed Successfully!")
print("\\nπŸ’‘ Next Steps:")
print(" β€’ Deploy to cloud (AWS, GCP, Azure)")
print(" β€’ Add real API integrations")
print(" β€’ Implement authentication & rate limiting")
print(" β€’ Add monitoring & analytics")
print(" β€’ Scale with container orchestration")
except requests.exceptions.ConnectionError:
print("❌ Error: Could not connect to API server")
print("πŸ’‘ Make sure to start the server first:")
print(" python api_server.py")
except Exception as e:
print(f"❌ Error: {e}")
if __name__ == "__main__":
demo_client()