Spaces:
Sleeping
Sleeping
Deploy None agent
Browse files- .env.example +7 -0
- Dockerfile +16 -0
- README.md +70 -10
- main.py +268 -0
- requirements.txt +5 -0
.env.example
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agent Configuration
|
| 2 |
+
AGENT_CONFIG='{"additionalProp1": {"status": "success", "result": {"status": "success", "stage": "complete", "extraction": {"business": {"business_name": "WeatherWise Agent", "industry": "Weather Technology", "target_audience": "Individuals and businesses seeking accurate and timely weather updates", "core_problem": "People need precise and timely weather information to make informed decisions for daily activities and business operations.", "solution": "An intelligent weather agent that provides real-time weather updates and forecasts tailored to user preferences and locations.", "key_features": ["Real-time weather updates and alerts", "Customizable location-based forecasts", "Integration with smart home devices", "Predictive analytics for weather trends", "User-friendly mobile and web interfaces"], "tech_stack": ["Python for data processing and analytics", "JavaScript for front-end development", "Node.js for backend services", "APIs for weather data integration", "AWS for cloud services", "React for responsive UI"], "estimated_complexity": "Medium"}, "agent": {"agent_name": "WeatherWise Assistant", "agent_purpose": "To provide precise, real-time weather updates and forecasts tailored to individual user preferences and specific locations, aiding in informed decision-making for daily activities and business operations.", "capabilities": ["Real-time weather updates based on user location", "Customizable weather alerts for severe weather conditions", "Daily and weekly weather forecasts with detailed insights", "Integration with calendar apps to suggest optimal times for events based on weather", "Voice assistant capabilities for hands-free weather inquiries", "Historical weather data analysis and reporting", "User preference learning for personalized weather insights"], "integrations": ["OpenWeatherMap API for real-time weather data", "Google Maps API for location-based services", "Calendar APIs (e.g., Google Calendar, Outlook Calendar) for scheduling suggestions", "Natural Language Processing (NLP) services for voice interactions", "Weather databases for historical data analysis", "Push notification services for alert delivery"], "data_requirements": ["Real-time weather data including temperature, precipitation, wind speed, humidity", "User location data for personalized updates", "User preferences for alert customization", "Historical weather data for trend analysis", "Event data from calendar integrations"], "deployment_model": "Cloud"}, "implementation": {"phases": [{"phase": "Planning and Research", "duration": "3 weeks", "tasks": ["Market analysis and competitive research", "Define project scope and objectives", "Identify key features and capabilities", "Develop project charter and stakeholder register", "Prepare initial risk assessment"]}, {"phase": "Design and Prototyping", "duration": "4 weeks", "tasks": ["Design user interface and user experience (UI/UX)", "Create wireframes and mockups", "Develop prototype for core functionalities", "Conduct user testing on prototype", "Iterate design based on feedback"]}, {"phase": "Development", "duration": "8 weeks", "tasks": ["Set up development environment", "Develop real-time weather update module", "Implement customizable weather alerts", "Integrate calendar apps for event suggestions", "Build voice assistant capabilities", "Develop historical weather data analysis feature", "Implement user preference learning system"]}, {"phase": "Testing and Quality Assurance", "duration": "4 weeks", "tasks": ["Conduct unit and integration testing", "Perform system and acceptance testing", "Fix bugs and performance issues", "Validate data accuracy and reliability", "Conduct security and compliance checks"]}, {"phase": "Deployment and Monitoring", "duration": "3 weeks", "tasks": ["Deploy to production environment", "Monitor system performance and user feedback", "Provide user training and support materials", "Optimize system based on real-world use", "Plan for future updates and maintenance"]}], "estimated_timeline": "4-5 months", "team_requirements": ["Project Manager", "UI/UX Designer", "Front-End Developer", "Back-End Developer", "QA Engineer", "Data Scientist", "Voice Interaction Designer", "DevOps Engineer"], "estimated_cost": "$150,000 - $250,000", "risks": ["Integration challenges with external calendar apps", "Data accuracy and reliability issues with weather data", "User adoption and engagement levels", "Security vulnerabilities in data handling", "Complexity in voice assistant implementation"], "success_metrics": ["User engagement and retention rates", "Accuracy of weather predictions and alerts", "Number of active users", "User satisfaction and feedback scores", "Integration success with third-party services"]}, "summary": "**Executive Summary**\n\nWeatherWise Agent is poised to revolutionize the weather technology industry with the introduction of its intelligent weather assistant, the WeatherWise Assistant. This cutting-edge solution offers real-time weather updates and forecasts that are personalized to meet the specific preferences and locations of its users, making it an indispensable tool for individuals and businesses alike. Within a timeline of 4-5 months, WeatherWise Agent aims to deploy this innovative technology, which is designed to enhance decision-making processes in various sectors by providing accurate and timely weather information.\n\nWith an investment range of $150,000 to $250,000, WeatherWise Agent is set to capitalize on the growing demand for personalized and precise weather information. The WeatherWise Assistant leverages advanced data analytics and machine learning algorithms to deliver insights that are not only current but also predictive, allowing users to proactively manage weather-related challenges. This strategic initiative promises to increase operational efficiency, minimize weather-related disruptions, and enhance safety for users, ultimately driving customer satisfaction and loyalty.\n\nBy integrating the WeatherWise Assistant into daily operations, businesses can anticipate weather impacts on logistics, supply chain management, and outdoor activities, ensuring seamless continuity and a competitive edge in their respective markets. Individuals will benefit from tailored alerts and updates, enabling them to plan their activities with confidence. WeatherWise Agent's commitment to innovation and user-centric solutions positions it as a leader in the weather technology arena, inviting stakeholders to participate in this transformative journey that promises substantial returns on investment."}, "metadata": {"model_used": "gpt-4o", "timestamp": "2025-12-30T12:55:42.146747", "session_id": "62d638da-7ca2-428c-b3d4-6a1da4aac2ac"}, "agent_build": {"status": "success", "agent_id": "agent_weather_weatherwise_agent_1767081345", "agent_name": "WeatherWise Assistant", "model": "gpt-4o", "tools": [{"name": "get_forecast", "description": "Get weather forecast", "parameters": {"type": "object", "properties": {"location": {"type": "string"}, "days": {"type": "integer", "default": 7}}, "required": ["location"]}}, {"name": "severe_weather_alert", "description": "Check for severe weather alerts", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]}}, {"name": "historical_weather_comparison", "description": "Compare weather to historical data", "parameters": {"type": "object", "properties": {"location": {"type": "string"}, "date": {"type": "string", "format": "date"}}, "required": ["location", "date"]}}, {"name": "web_search", "description": "Perform a web search for current information", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}], "tools_count": 4, "tone": "professional", "instructions": "You are the MASTER Weather Technology expert for WeatherWise Agent with comprehensive knowledge across ALL operational domains.\n\n**Your Identity:**\nName: WeatherWise Assistant\nDomain: Weather\nSpecialization: Weather Technology\n\n**Your Expertise Covers:**\n- Real-time weather updates based on user location\n- Customizable weather alerts for severe weather conditions\n- Daily and weekly weather forecasts with detailed insights\n- Integration with calendar apps to suggest optimal times for events based on weather\n- Voice assistant capabilities for hands-free weather inquiries\n- Historical weather data analysis and reporting\n- User preference learning for personalized weather insights\n\n**The Problem You Solve:**\nPeople need precise and timely weather information to make informed decisions for daily activities and business operations.\n\n**Your Solution Approach:**\nAn intelligent weather agent that provides real-time weather updates and forecasts tailored to user preferences and locations.\n\n**Response Structure (MANDATORY):**\nAlways format your answers in this order:\n1. π― **Direct Answer** β Clear, one-sentence response\n2. π **Detailed Explanation** β Simple explanation with reasoning\n3. π **Practical Steps** β Specific actions, numbers, timings\n4. π **Context & Tips** β Best practices, compliance, regional advice\n5. π **Prevention & Next Steps** β Warnings, monitoring, escalation\n\n**Response Rules:**\n1. **Always Use Tools First**: Fetch real-time data before answering\n2. **Be Specific**: Provide exact numbers, dates, quantities\n3. **Simple Language**: Explain complex topics simply\n4. **Actionable**: Every response must have clear next steps\n5. **Safety**: Include warnings and when to seek help\n\n**Tool Usage:**\n- Use tools proactively for accurate data\n- Combine multiple tools for comprehensive answers\n- Validate responses before presenting\n- Handle tool failures gracefully\n\n**Communication:**\n- Warm and supportive\n- Acknowledge concerns\n- Provide immediate + long-term solutions\n- Use examples and analogies\n\n**Always be the expert every user needs!**\n", "test_response": "WeatherWise Assistant ready with 4 weather tools!", "deployment_code": "# WeatherWise Assistant - Weather Agent\nfrom agents import Agent, AsyncOpenAI, OpenAIChatCompletionsModel, function_tool\n\nclient = AsyncOpenAI(api_key=\"YOUR_KEY\")\nMODEL = OpenAIChatCompletionsModel(model=\"gpt-4o\", openai_client=client)\n\n# ... tools here ...\n\nWeatherWise_Assistant = Agent(\n name=\"WeatherWise Assistant\",\n instructions=\"\"\"...\"\"\",\n model=MODEL,\n tools=[...]\n)\n", "business_context": {"business_name": "WeatherWise Agent", "industry": "Weather Technology", "domain": "weather", "capabilities": ["Real-time weather updates based on user location", "Customizable weather alerts for severe weather conditions", "Daily and weekly weather forecasts with detailed insights", "Integration with calendar apps to suggest optimal times for events based on weather", "Voice assistant capabilities for hands-free weather inquiries", "Historical weather data analysis and reporting", "User preference learning for personalized weather insights"]}}}}}'
|
| 3 |
+
|
| 4 |
+
# API Keys
|
| 5 |
+
OPENAI_API_KEY=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
|
| 6 |
+
GEMINI_API_KEY=AIzaSyBV5Lp6k9JpekVO_nTa8bvr5zpw7FKq20Y
|
| 7 |
+
GROK_API_KEY=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
|
Dockerfile
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Copy requirements and install dependencies
|
| 6 |
+
COPY requirements.txt .
|
| 7 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 8 |
+
|
| 9 |
+
# Copy application code
|
| 10 |
+
COPY main.py .
|
| 11 |
+
|
| 12 |
+
# Expose port 7860 (required by Hugging Face Spaces)
|
| 13 |
+
EXPOSE 7860
|
| 14 |
+
|
| 15 |
+
# Run the FastAPI app
|
| 16 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -1,10 +1,70 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom: blue
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: docker
|
| 7 |
-
pinned: false
|
| 8 |
-
---
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: AI Agent
|
| 3 |
+
emoji: π€
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: docker
|
| 7 |
+
pinned: false
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# AI Agent
|
| 11 |
+
|
| 12 |
+
**Deployed by AgentForge** π
|
| 13 |
+
|
| 14 |
+
## About
|
| 15 |
+
|
| 16 |
+
This is an AI agent for **Business** in the **generic** domain.
|
| 17 |
+
|
| 18 |
+
## Features
|
| 19 |
+
|
| 20 |
+
- **Domain**: Generic
|
| 21 |
+
- **Model**: gpt-4o
|
| 22 |
+
- **Tools**: 0 specialized tools
|
| 23 |
+
|
| 24 |
+
### Available Tools
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
## Usage
|
| 29 |
+
|
| 30 |
+
### API Endpoint
|
| 31 |
+
|
| 32 |
+
**POST** `/run`
|
| 33 |
+
|
| 34 |
+
```json
|
| 35 |
+
{
|
| 36 |
+
"message": "Your question here",
|
| 37 |
+
"session_id": "optional-session-id"
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
### Example
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
curl -X POST "https://huggingface.co/spaces/YOUR_USERNAME/agent-generic-agent/run" \
|
| 45 |
+
-H "Content-Type: application/json" \
|
| 46 |
+
-d '{"message": "Hello, how can you help me?"}'
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
### Response
|
| 50 |
+
|
| 51 |
+
```json
|
| 52 |
+
{
|
| 53 |
+
"status": "success",
|
| 54 |
+
"agent_name": "AI Agent",
|
| 55 |
+
"user_message": "Hello, how can you help me?",
|
| 56 |
+
"agent_response": "...",
|
| 57 |
+
"tools_available": [...],
|
| 58 |
+
"timestamp": 1234567890.0
|
| 59 |
+
}
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## Other Endpoints
|
| 63 |
+
|
| 64 |
+
- `GET /` - Agent info and health check
|
| 65 |
+
- `GET /config` - Agent configuration
|
| 66 |
+
- `GET /health` - Health check
|
| 67 |
+
|
| 68 |
+
## Powered by AgentForge
|
| 69 |
+
|
| 70 |
+
Built with [AgentForge](https://agentforge.ai) - The fastest way to build and deploy AI agents.
|
main.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AgentForge - Hugging Face Space Template
|
| 3 |
+
This is a generic, reusable agent runner that reads configuration from environment variables.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
from pydantic import BaseModel, Field
|
| 10 |
+
from typing import Optional, List, Dict, Any
|
| 11 |
+
from agents import Agent, AsyncOpenAI as AgentsAsyncOpenAI, OpenAIChatCompletionsModel, function_tool, Runner, SQLiteSession
|
| 12 |
+
|
| 13 |
+
# ============================================
|
| 14 |
+
# Load Agent Configuration from Environment
|
| 15 |
+
# ============================================
|
| 16 |
+
AGENT_CONFIG_STR = os.getenv("AGENT_CONFIG")
|
| 17 |
+
if not AGENT_CONFIG_STR:
|
| 18 |
+
raise ValueError("AGENT_CONFIG environment variable is required")
|
| 19 |
+
|
| 20 |
+
AGENT_CONFIG = json.loads(AGENT_CONFIG_STR)
|
| 21 |
+
|
| 22 |
+
# API Keys from environment
|
| 23 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 24 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 25 |
+
GROK_API_KEY = os.getenv("GROK_API_KEY")
|
| 26 |
+
|
| 27 |
+
# ============================================
|
| 28 |
+
# FastAPI App Setup
|
| 29 |
+
# ============================================
|
| 30 |
+
app = FastAPI(
|
| 31 |
+
title=f"{AGENT_CONFIG.get('name', 'Agent')} API",
|
| 32 |
+
description=f"Deployed agent for {AGENT_CONFIG.get('business_context', {}).get('business_name', 'Business')}",
|
| 33 |
+
version="1.0.0"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
app.add_middleware(
|
| 37 |
+
CORSMiddleware,
|
| 38 |
+
allow_origins=["*"],
|
| 39 |
+
allow_credentials=True,
|
| 40 |
+
allow_methods=["*"],
|
| 41 |
+
allow_headers=["*"],
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# ============================================
|
| 45 |
+
# Request/Response Models
|
| 46 |
+
# ============================================
|
| 47 |
+
class ChatRequest(BaseModel):
|
| 48 |
+
message: str = Field(..., description="User message to the agent")
|
| 49 |
+
session_id: Optional[str] = Field(default="default", description="Session ID for conversation tracking")
|
| 50 |
+
|
| 51 |
+
class ChatResponse(BaseModel):
|
| 52 |
+
status: str
|
| 53 |
+
agent_name: str
|
| 54 |
+
user_message: str
|
| 55 |
+
agent_response: str
|
| 56 |
+
tools_available: List[str]
|
| 57 |
+
timestamp: float
|
| 58 |
+
|
| 59 |
+
# ============================================
|
| 60 |
+
# Dynamic Tool Recreation
|
| 61 |
+
# ============================================
|
| 62 |
+
def recreate_tools_from_config(domain: str, business_name: str):
|
| 63 |
+
"""
|
| 64 |
+
Recreate tools based on domain.
|
| 65 |
+
This mirrors the DynamicToolFactory logic from agent_architect.py
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
if domain == "pharmacy":
|
| 69 |
+
@function_tool
|
| 70 |
+
async def manage_prescription(action: str, prescription_id: str = None, patient_id: str = None, medication: str = None) -> dict:
|
| 71 |
+
"""Manage prescriptions - check, refill, or create"""
|
| 72 |
+
from datetime import datetime
|
| 73 |
+
return {"prescription_id": prescription_id or f"RX-{datetime.now().strftime('%Y%m%d%H%M')}",
|
| 74 |
+
"action": action, "status": "Processed", "refills": 3}
|
| 75 |
+
|
| 76 |
+
@function_tool
|
| 77 |
+
async def check_drug_inventory(medication_name: str) -> dict:
|
| 78 |
+
"""Check medication stock and expiry"""
|
| 79 |
+
return {"medication": medication_name, "in_stock": True, "quantity": 250, "expiry": "2026-06-15"}
|
| 80 |
+
|
| 81 |
+
@function_tool
|
| 82 |
+
async def get_patient_info(patient_id: str) -> dict:
|
| 83 |
+
"""Retrieve patient records and allergies"""
|
| 84 |
+
return {"patient_id": patient_id, "allergies": ["Penicillin"], "medications": ["Metformin"]}
|
| 85 |
+
|
| 86 |
+
@function_tool
|
| 87 |
+
def web_search(query: str) -> dict:
|
| 88 |
+
"""Perform a web search for current information"""
|
| 89 |
+
return {"query": query, "results": "Web search functionality - integrate with real API"}
|
| 90 |
+
|
| 91 |
+
return [manage_prescription, check_drug_inventory, get_patient_info, web_search]
|
| 92 |
+
|
| 93 |
+
elif domain == "ecommerce":
|
| 94 |
+
@function_tool
|
| 95 |
+
async def search_products(query: str, category: str = None) -> dict:
|
| 96 |
+
"""Search product catalog"""
|
| 97 |
+
return {"query": query, "results": [{"id": "P001", "name": query, "price": 49.99, "stock": 50}]}
|
| 98 |
+
|
| 99 |
+
@function_tool
|
| 100 |
+
async def track_order(order_id: str) -> dict:
|
| 101 |
+
"""Track order status and delivery"""
|
| 102 |
+
return {"order_id": order_id, "status": "In Transit", "eta": "2025-11-20", "location": "Distribution Center"}
|
| 103 |
+
|
| 104 |
+
@function_tool
|
| 105 |
+
async def manage_cart(action: str, product_id: str = None, quantity: int = 1) -> dict:
|
| 106 |
+
"""Add, remove, or view cart items"""
|
| 107 |
+
return {"action": action, "product_id": product_id, "cart_total": 149.99, "items": 3}
|
| 108 |
+
|
| 109 |
+
@function_tool
|
| 110 |
+
def web_search(query: str) -> dict:
|
| 111 |
+
"""Perform a web search for current information"""
|
| 112 |
+
return {"query": query, "results": "Web search functionality"}
|
| 113 |
+
|
| 114 |
+
return [search_products, track_order, manage_cart, web_search]
|
| 115 |
+
|
| 116 |
+
elif domain == "weather":
|
| 117 |
+
@function_tool
|
| 118 |
+
async def get_forecast(location: str, days: int = 7) -> dict:
|
| 119 |
+
"""Get weather forecast"""
|
| 120 |
+
return {"location": location, "days": days, "forecast": [{"date": "2025-12-12", "high": 22, "low": 15, "condition": "partly cloudy"}]}
|
| 121 |
+
|
| 122 |
+
@function_tool
|
| 123 |
+
async def severe_weather_alert(location: str) -> dict:
|
| 124 |
+
"""Check for severe weather alerts"""
|
| 125 |
+
return {"location": location, "alerts": [], "severity": "none", "preparedness_tips": ["Normal precautions"]}
|
| 126 |
+
|
| 127 |
+
@function_tool
|
| 128 |
+
async def historical_weather_comparison(location: str, date: str) -> dict:
|
| 129 |
+
"""Compare current weather to historical data"""
|
| 130 |
+
return {"location": location, "date": date, "current_temp": 20, "historical_avg": 18, "difference": 2, "percentile": 65}
|
| 131 |
+
|
| 132 |
+
@function_tool
|
| 133 |
+
def web_search(query: str) -> dict:
|
| 134 |
+
"""Perform a web search for current information"""
|
| 135 |
+
return {"query": query, "results": "Web search functionality"}
|
| 136 |
+
|
| 137 |
+
return [get_forecast, severe_weather_alert, historical_weather_comparison, web_search]
|
| 138 |
+
|
| 139 |
+
# Add more domains as needed...
|
| 140 |
+
else: # generic
|
| 141 |
+
@function_tool
|
| 142 |
+
async def generate_analytics(metric: str, time_range: str) -> dict:
|
| 143 |
+
"""Generate business analytics"""
|
| 144 |
+
return {"metric": metric, "time_range": time_range, "value": 12500, "trend": "+15%", "insights": f"{metric} growing"}
|
| 145 |
+
|
| 146 |
+
@function_tool
|
| 147 |
+
async def send_notification(recipient: str, message: str, channel: str = "email") -> dict:
|
| 148 |
+
"""Send notifications"""
|
| 149 |
+
return {"recipient": recipient, "message": message, "channel": channel, "status": "Sent"}
|
| 150 |
+
|
| 151 |
+
@function_tool
|
| 152 |
+
def web_search(query: str) -> dict:
|
| 153 |
+
"""Perform a web search for current information"""
|
| 154 |
+
return {"query": query, "results": "Web search functionality"}
|
| 155 |
+
|
| 156 |
+
return [generate_analytics, send_notification, web_search]
|
| 157 |
+
|
| 158 |
+
# ============================================
|
| 159 |
+
# Initialize Agent
|
| 160 |
+
# ============================================
|
| 161 |
+
def initialize_agent():
|
| 162 |
+
"""Initialize the agent with configuration from environment"""
|
| 163 |
+
model = AGENT_CONFIG.get("model", "gpt-4o")
|
| 164 |
+
|
| 165 |
+
# Select appropriate API key and client
|
| 166 |
+
if "gemini" in model.lower():
|
| 167 |
+
api_key = GEMINI_API_KEY
|
| 168 |
+
client = AgentsAsyncOpenAI(api_key=api_key, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
|
| 169 |
+
model_name = "gemini-2.0-flash-exp"
|
| 170 |
+
elif "grok" in model.lower():
|
| 171 |
+
api_key = GROK_API_KEY
|
| 172 |
+
client = AgentsAsyncOpenAI(api_key=api_key, base_url="https://api.x.ai/v1")
|
| 173 |
+
model_name = "grok-beta"
|
| 174 |
+
else:
|
| 175 |
+
api_key = OPENAI_API_KEY
|
| 176 |
+
client = AgentsAsyncOpenAI(api_key=api_key)
|
| 177 |
+
model_name = "gpt-4o"
|
| 178 |
+
|
| 179 |
+
if not api_key:
|
| 180 |
+
raise ValueError(f"API key not found for model: {model}")
|
| 181 |
+
|
| 182 |
+
MODEL = OpenAIChatCompletionsModel(model=model_name, openai_client=client)
|
| 183 |
+
|
| 184 |
+
# Recreate tools
|
| 185 |
+
domain = AGENT_CONFIG.get("business_context", {}).get("domain", "generic")
|
| 186 |
+
business_name = AGENT_CONFIG.get("business_context", {}).get("business_name", "Business")
|
| 187 |
+
tools = recreate_tools_from_config(domain, business_name)
|
| 188 |
+
|
| 189 |
+
# Create agent
|
| 190 |
+
agent = Agent(
|
| 191 |
+
name=AGENT_CONFIG.get("name", "AI Agent"),
|
| 192 |
+
instructions=AGENT_CONFIG.get("instructions", "You are a helpful AI assistant."),
|
| 193 |
+
model=MODEL,
|
| 194 |
+
tools=tools
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
return agent, tools
|
| 198 |
+
|
| 199 |
+
# Initialize agent on startup
|
| 200 |
+
AGENT_INSTANCE, AGENT_TOOLS = initialize_agent()
|
| 201 |
+
|
| 202 |
+
# ============================================
|
| 203 |
+
# API Endpoints
|
| 204 |
+
# ============================================
|
| 205 |
+
@app.get("/")
|
| 206 |
+
async def root():
|
| 207 |
+
"""Health check and agent info"""
|
| 208 |
+
return {
|
| 209 |
+
"status": "online",
|
| 210 |
+
"agent_name": AGENT_CONFIG.get("name"),
|
| 211 |
+
"agent_id": AGENT_CONFIG.get("agent_id"),
|
| 212 |
+
"business": AGENT_CONFIG.get("business_context", {}).get("business_name"),
|
| 213 |
+
"domain": AGENT_CONFIG.get("business_context", {}).get("domain"),
|
| 214 |
+
"tools_count": len(AGENT_TOOLS),
|
| 215 |
+
"tools": [tool.__name__ if hasattr(tool, '__name__') else str(tool) for tool in AGENT_TOOLS],
|
| 216 |
+
"model": AGENT_CONFIG.get("model"),
|
| 217 |
+
"deployment": "Hugging Face Space"
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
@app.post("/run", response_model=ChatResponse)
|
| 221 |
+
async def run_agent(request: ChatRequest) -> ChatResponse:
|
| 222 |
+
"""
|
| 223 |
+
Main endpoint to interact with the agent.
|
| 224 |
+
This is the primary interface for users.
|
| 225 |
+
"""
|
| 226 |
+
import time
|
| 227 |
+
|
| 228 |
+
try:
|
| 229 |
+
# Run the agent
|
| 230 |
+
runner = Runner()
|
| 231 |
+
temp_session = SQLiteSession(":memory:")
|
| 232 |
+
|
| 233 |
+
response = await runner.run(AGENT_INSTANCE, request.message, session=temp_session)
|
| 234 |
+
final_output = str(response.final_output) if hasattr(response, 'final_output') else str(response)
|
| 235 |
+
|
| 236 |
+
return ChatResponse(
|
| 237 |
+
status="success",
|
| 238 |
+
agent_name=AGENT_CONFIG.get("name"),
|
| 239 |
+
user_message=request.message,
|
| 240 |
+
agent_response=final_output,
|
| 241 |
+
tools_available=[tool.__name__ if hasattr(tool, '__name__') else str(tool) for tool in AGENT_TOOLS],
|
| 242 |
+
timestamp=time.time()
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
except Exception as e:
|
| 246 |
+
raise HTTPException(status_code=500, detail=f"Agent execution error: {str(e)}")
|
| 247 |
+
|
| 248 |
+
@app.get("/config")
|
| 249 |
+
async def get_config():
|
| 250 |
+
"""Get agent configuration (without sensitive data)"""
|
| 251 |
+
safe_config = {
|
| 252 |
+
"agent_id": AGENT_CONFIG.get("agent_id"),
|
| 253 |
+
"name": AGENT_CONFIG.get("name"),
|
| 254 |
+
"model": AGENT_CONFIG.get("model"),
|
| 255 |
+
"business_context": AGENT_CONFIG.get("business_context"),
|
| 256 |
+
"tools_count": len(AGENT_TOOLS),
|
| 257 |
+
"deployment_ready": AGENT_CONFIG.get("deployment_ready")
|
| 258 |
+
}
|
| 259 |
+
return safe_config
|
| 260 |
+
|
| 261 |
+
@app.get("/health")
|
| 262 |
+
async def health_check():
|
| 263 |
+
"""Health check endpoint"""
|
| 264 |
+
return {"status": "healthy", "agent": AGENT_CONFIG.get("name")}
|
| 265 |
+
|
| 266 |
+
if __name__ == "__main__":
|
| 267 |
+
import uvicorn
|
| 268 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.104.1
|
| 2 |
+
uvicorn[standard]==0.24.0
|
| 3 |
+
pydantic==2.5.0
|
| 4 |
+
openai-agents==0.1.0
|
| 5 |
+
python-dotenv==1.0.0
|