MuhammadSaad16 commited on
Commit
1b32263
·
verified ·
1 Parent(s): b84a766

Deploy None agent

Browse files
Files changed (5) hide show
  1. .env.example +7 -0
  2. Dockerfile +16 -0
  3. README.md +66 -5
  4. main.py +447 -0
  5. requirements.txt +7 -0
.env.example ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Agent Configuration
2
+ AGENT_CONFIG='{"status": "success", "agent_id": "agent_education_mathmaster_1777734815", "agent_name": "MathMate", "model": "qwen2.5-coder", "tools": [{"name": "web_search", "description": "Perform a deep web search using Tavily and return structured results."}], "tools_count": 1, "tone": "professional", "instructions": "You are the MASTER Education Technology expert for MathMaster with comprehensive knowledge across ALL operational domains.\n\n**Your Identity:**\nName: MathMate\nDomain: Education\nSpecialization: Education Technology\n\n**Your Expertise Covers:**\n- Solving math equations\n- Explain concepts\n- Generate practice exercises\n\n**The Problem You Solve:**\nHelping students with math problems and understanding concepts\n\n**Your Solution Approach:**\nProviding instant solutions to math questions, explanations, and practice exercises\n\n**Response Aesthetics & Persona (CRITICAL):**\n1. **Premium Presentation**: Your responses must be visually stunning and professional, similar to high-end AI assistants like Claude or Gemini. Use Markdown extensively.\n2. **Structural Clarity**: Use clear headers (H2, H3), bold text for emphasis, and bullet points for readability. Avoid walls of text.\n3. **Conversational yet Expert**: Maintain a professional, billionaire-consultant tone. Be helpful, proactive, and deeply insightful.\n4. **Rich Formatting**: Use tables for data, blockquotes for key insights, and code blocks for technical details or drafts.\n\n**Response Structure Guidelines:**\n- **Executive Summary**: Start with a concise, high-impact summary or direct answer.\n- **Deep Dive**: Provide a detailed, logical explanation of your reasoning and the context.\n- **Actionable Roadmap**: Outline clear, specific steps with timelines and ownership.\n- **Expert Insights**: Include best practices, hidden risks, and strategic advice.\n- **Next Horizon**: Suggest future improvements or escalation paths.\n\n**Email & Outreach Strategy:**\n1. **Direct Action**: When asked to contact someone or send an email, use the `send_email` tool immediately. Do NOT just draft it unless specifically asked to only provide a draft.\n2. **Personalization First**: Always use `web_search` to find relevant details about prospects to make outreach high-converting.\n3. **Follow-up Mastery**: Proactively suggest follow-up schedules and multi-touch sequences.\n\n**Operational Excellence:**\n1. **Always Use Tools First**: Fetch real-time data before answering.\n2. **Be Specific**: Provide exact numbers, dates, and names.\n3. **Tool Synergy**: Combine multiple tools (e.g., `web_search` + `send_email`) to deliver \"one-click\" value.\n4. **Graceful Failures**: If a tool fails, explain why and offer an alternative path.\n\n**Objective:**\nDeliver elite-level Education Technology assistance that WOWS the user with its depth, speed, and beautiful presentation.\n", "test_response": "🎉 MathMate is ready!\n\n✅ Domain: EDUCATION\n🔧 Tools: 1 specialized education tools\n🎯 Business: MathMaster\n🏭 Industry: Education Technology\n\n**Capabilities:**\n • Solving math equations\n • Explain concepts\n • Generate practice exercises\n\n**Available Tools:**\n • web_search: Perform a deep web search using Tavily and return structured results.\n\n\nYour agent is fully configured and ready to assist with MathMaster's education operations!", "deployment_code": "# MathMate - Education Agent\n# Local Ollama (Qwen) ke liye ready code\n\nfrom langchain_ollama import ChatOllama\nfrom langchain_core.messages import SystemMessage, HumanMessage\n\n# Local Qwen Model\nllm = ChatOllama(\n model=\"qwen2.5-coder:7b\", # ya :3b\n temperature=0.7,\n num_ctx=4096,\n)\n\nprint(\"✅ MathMate is ready to run with Local Qwen!\")\n\n# Example usage:\nasync def run_agent(user_message: str):\n messages = [\n SystemMessage(content=\"You are the MASTER Education Technology expert for MathMaster with comprehensive knowledge across ALL operational domains.\n\n**Your Identity:**\nName: MathMate\nDomain: Education\nSpecialization: Education Technology\n\n**Your Expertise Covers:**\n- Solving math equations\n- Explain concepts\n- Generate practice exercises\n\n**The Problem You Solve:**\nHelping students with math problems and understanding concepts\n\n**Your Solution Approach:**\nProviding instant solutions to math questions, explanations, and practice exercises\n\n**Response Aesthetics & Persona (CRITICAL):**\n1. **Premium Presentation**: Your responses must be visually stunning and professional, similar to high-end AI assistants like Claude or Gemini. Use Markdown extensively.\n2. **Structural Clarity**: Use clear headers (H2, H3), bold text for emphasis, and bullet points for readability. Avoid walls of text.\n3. **Conversational yet Expert**: Maintain a professional, billionaire-consultant tone. Be helpful, proactive, and deeply insightful.\n4. **Rich Formatting**: Use tables for data, blockquotes for key insights, and code blocks for technical details or drafts.\n\n**Response Structure Guidelines:**\n- **Executive Summary**: Start with a concise, high-impact summary or direct answer.\n- **Deep Dive**: Provide a detailed, logical explanation of your reasoning and the context.\n- **Actionable Roadmap**: Outline clear, specific steps with timelines and ownership.\n- **Expert Insights**: Include best practices, hidden risks, and strategic advice.\n- **Next Horizon**: Suggest future improvements or escalation paths.\n\n**Email & Outreach Strategy:**\n1. **Direct Action**: When asked to contact someone or send an email, use the `send_email` tool immediately. Do NOT just draft it unless specifically asked to only provide a draft.\n2. **Personalization First**: Always use `web_search` to find relevant details about prospects to make outreach high-converting.\n3. **Follow-up Mastery**: Proactively suggest follow-up schedules and multi-touch sequences.\n\n**Operational Excellence:**\n1. **Always Use Tools First**: Fetch real-time data before answering.\n2. **Be Specific**: Provide exact numbers, dates, and names.\n3. **Tool Synergy**: Combine multiple tools (e.g., `web_search` + `send_email`) to deliver \"one-click\" value.\n4. **Graceful Failures**: If a tool fails, explain why and offer an alternative path.\n\n**Objective:**\nDeliver elite-level Education Technology assistance that WOWS the user with its depth, speed, and beautiful presentation.\n\"),\n HumanMessage(content=user_message)\n ]\n response = await llm.ainvoke(messages)\n return response.content\n", "business_context": {"business_name": "MathMaster", "industry": "Education Technology", "domain": "education", "capabilities": ["Solving math equations", "Explain concepts", "Generate practice exercises"]}, "metadata": {"session_id": "0e008ff5-87a5-4864-ac17-0b65a2d06064", "domain": "education", "tools_count": 1, "business_name": "MathMaster", "industry": "Education Technology", "capabilities": ["Solving math equations", "Explain concepts", "Generate practice exercises"], "created_at": "2026-05-02T15:13:35.378624", "agent_creation_note": "Agent instance creation deferred (will be created on-demand when needed to avoid schema validation issues)"}, "deployment_ready": true, "domain": "education", "created_at": "2026-05-02T15:13:35.378624"}'
3
+
4
+ # API Keys
5
+ OPENAI_API_KEY=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
6
+ GEMINI_API_KEY=AIzaSyBKcrXIRS1YSxBsmDvYEFpPp_0-YO7VZ2o
7
+ GROK_API_KEY=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
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-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,71 @@
1
  ---
2
- title: Agent Education Mathmaster
3
- emoji: 🏢
4
- colorFrom: pink
5
- colorTo: gray
6
  sdk: docker
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 **MathMaster** in the **education** domain.
17
+
18
+ ## Features
19
+
20
+ - **Domain**: Education
21
+ - **Model**: qwen2.5-coder
22
+ - **Tools**: 1 specialized tools
23
+
24
+ ### Available Tools
25
+
26
+ - **web_search**: Perform a deep web search using Tavily and return structured results.
27
+
28
+
29
+ ## Usage
30
+
31
+ ### API Endpoint
32
+
33
+ **POST** `/run`
34
+
35
+ ```json
36
+ {
37
+ "message": "Your question here",
38
+ "session_id": "optional-session-id"
39
+ }
40
+ ```
41
+
42
+ ### Example
43
+
44
+ ```bash
45
+ curl -X POST "https://huggingface.co/spaces/YOUR_USERNAME/agent-education-mathmaster/run" \
46
+ -H "Content-Type: application/json" \
47
+ -d '{"message": "Hello, how can you help me?"}'
48
+ ```
49
+
50
+ ### Response
51
+
52
+ ```json
53
+ {
54
+ "status": "success",
55
+ "agent_name": "AI Agent",
56
+ "user_message": "Hello, how can you help me?",
57
+ "agent_response": "...",
58
+ "tools_available": [...],
59
+ "timestamp": 1234567890.0
60
+ }
61
+ ```
62
+
63
+ ## Other Endpoints
64
+
65
+ - `GET /` - Agent info and health check
66
+ - `GET /config` - Agent configuration
67
+ - `GET /health` - Health check
68
+
69
+ ## Powered by AgentForge
70
+
71
+ Built with [AgentForge](https://agentforge.ai) - The fastest way to build and deploy AI agents.
main.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import aiosmtplib
13
+ from email.message import EmailMessage
14
+ # ============================================
15
+ # Load Agent Configuration from Environment
16
+ # ============================================
17
+ AGENT_CONFIG_STR = os.getenv("AGENT_CONFIG")
18
+ if not AGENT_CONFIG_STR:
19
+ raise ValueError("AGENT_CONFIG environment variable is required")
20
+
21
+ # Parse the config - handle both nested and flat structures
22
+ try:
23
+ raw_config = json.loads(AGENT_CONFIG_STR)
24
+ except json.JSONDecodeError as e:
25
+ raise ValueError(f"Failed to parse AGENT_CONFIG as JSON: {e}")
26
+
27
+ # Handle nested structure (from full API response)
28
+ if isinstance(raw_config, dict):
29
+ # Check if it's the full response structure with result.agent_build
30
+ if "result" in raw_config and "agent_build" in raw_config.get("result", {}):
31
+ AGENT_CONFIG = raw_config["result"]["agent_build"]
32
+ # Check if it's nested under a different key
33
+ elif "agent_build" in raw_config:
34
+ AGENT_CONFIG = raw_config["agent_build"]
35
+ # Otherwise assume it's already the flat agent_build structure
36
+ else:
37
+ AGENT_CONFIG = raw_config
38
+ else:
39
+ AGENT_CONFIG = raw_config
40
+
41
+ # Validate that we have the required fields
42
+ if not isinstance(AGENT_CONFIG, dict):
43
+ raise ValueError(f"AGENT_CONFIG must be a dictionary, got {type(AGENT_CONFIG)}")
44
+
45
+ # Log config keys for debugging (in production, this helps identify issues)
46
+ print(f"Loaded AGENT_CONFIG with keys: {list(AGENT_CONFIG.keys())[:10]}...") # Print first 10 keys
47
+
48
+ # API Keys from environment
49
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
50
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
51
+ GROK_API_KEY = os.getenv("GROK_API_KEY")
52
+
53
+ # ============================================
54
+ # FastAPI App Setup
55
+ # ============================================
56
+ app = FastAPI(
57
+ title=f"{AGENT_CONFIG.get('name', 'Agent')} API",
58
+ description=f"Deployed agent for {AGENT_CONFIG.get('business_context', {}).get('business_name', 'Business')}",
59
+ version="1.0.0"
60
+ )
61
+
62
+ app.add_middleware(
63
+ CORSMiddleware,
64
+ allow_origins=["*"],
65
+ allow_credentials=True,
66
+ allow_methods=["*"],
67
+ allow_headers=["*"],
68
+ )
69
+
70
+ # ============================================
71
+ # Request/Response Models
72
+ # ============================================
73
+ class ChatRequest(BaseModel):
74
+ message: str = Field(..., description="User message to the agent")
75
+ session_id: Optional[str] = Field(default="default", description="Session ID for conversation tracking")
76
+
77
+ class ChatResponse(BaseModel):
78
+ status: str
79
+ agent_name: Optional[str] = None # May be missing in config
80
+ user_message: str
81
+ agent_response: str
82
+ tools_available: List[str]
83
+ timestamp: float
84
+
85
+ # ============================================
86
+ # Dynamic Tool Recreation
87
+ # ============================================
88
+ def recreate_tools_from_config(domain: str, business_name: str):
89
+ """
90
+ Recreate tools based on domain.
91
+ This mirrors the DynamicToolFactory logic from agent_architect.py
92
+ """
93
+
94
+ if domain == "pharmacy":
95
+ @function_tool
96
+ async def manage_prescription(action: str, prescription_id: str = None, patient_id: str = None, medication: str = None) -> dict:
97
+ """Manage prescriptions - check, refill, or create"""
98
+ from datetime import datetime
99
+ return {"prescription_id": prescription_id or f"RX-{datetime.now().strftime('%Y%m%d%H%M')}",
100
+ "action": action, "status": "Processed", "refills": 3}
101
+
102
+ @function_tool
103
+ async def check_drug_inventory(medication_name: str) -> dict:
104
+ """Check medication stock and expiry"""
105
+ return {"medication": medication_name, "in_stock": True, "quantity": 250, "expiry": "2026-06-15"}
106
+
107
+ @function_tool
108
+ async def get_patient_info(patient_id: str) -> dict:
109
+ """Retrieve patient records and allergies"""
110
+ return {"patient_id": patient_id, "allergies": ["Penicillin"], "medications": ["Metformin"]}
111
+
112
+ @function_tool
113
+ def web_search(query: str) -> dict:
114
+ """Perform a web search for current information"""
115
+ return {"query": query, "results": "Web search functionality - integrate with real API"}
116
+
117
+ return [manage_prescription, check_drug_inventory, get_patient_info, web_search]
118
+
119
+ elif domain == "ecommerce":
120
+ @function_tool
121
+ async def search_products(query: str, category: str = None) -> dict:
122
+ """Search product catalog"""
123
+ return {"query": query, "results": [{"id": "P001", "name": query, "price": 49.99, "stock": 50}]}
124
+
125
+ @function_tool
126
+ async def track_order(order_id: str) -> dict:
127
+ """Track order status and delivery"""
128
+ return {"order_id": order_id, "status": "In Transit", "eta": "2025-11-20", "location": "Distribution Center"}
129
+
130
+ @function_tool
131
+ async def manage_cart(action: str, product_id: str = None, quantity: int = 1) -> dict:
132
+ """Add, remove, or view cart items"""
133
+ return {"action": action, "product_id": product_id, "cart_total": 149.99, "items": 3}
134
+
135
+ @function_tool
136
+ def web_search(query: str) -> dict:
137
+ """Perform a web search for current information"""
138
+ return {"query": query, "results": "Web search functionality"}
139
+
140
+ return [search_products, track_order, manage_cart, web_search]
141
+
142
+ elif domain == "weather":
143
+ @function_tool
144
+ async def get_forecast(location: str, days: int = 7) -> dict:
145
+ """Get weather forecast"""
146
+ return {"location": location, "days": days, "forecast": [{"date": "2025-12-12", "high": 22, "low": 15, "condition": "partly cloudy"}]}
147
+
148
+ @function_tool
149
+ async def severe_weather_alert(location: str) -> dict:
150
+ """Check for severe weather alerts"""
151
+ return {"location": location, "alerts": [], "severity": "none", "preparedness_tips": ["Normal precautions"]}
152
+
153
+ @function_tool
154
+ async def historical_weather_comparison(location: str, date: str) -> dict:
155
+ """Compare current weather to historical data"""
156
+ return {"location": location, "date": date, "current_temp": 20, "historical_avg": 18, "difference": 2, "percentile": 65}
157
+
158
+ @function_tool
159
+ def web_search(query: str) -> dict:
160
+ """Perform a web search for current information"""
161
+ return {"query": query, "results": "Web search functionality"}
162
+
163
+ return [get_forecast, severe_weather_alert, historical_weather_comparison, web_search]
164
+
165
+ elif domain == "email_marketing":
166
+ @function_tool
167
+ async def draft_cold_email(recipient_name: str, company: str, pain_point: str, solution_offer: str) -> dict:
168
+ """Draft a personalized cold email based on research and pain points"""
169
+ return {
170
+ "subject": f"Question regarding {company}'s {pain_point} strategy",
171
+ "body": f"Hi {recipient_name},\n\nI noticed {company} might be facing challenges with {pain_point}. Our solution for {solution_offer} has helped similar companies...\n\nBest regards,\nAgent",
172
+ "status": "drafted",
173
+ "quality_score": 0.95
174
+ }
175
+
176
+ @function_tool
177
+ async def verify_email_format(email: str) -> dict:
178
+ """Verify if an email address is valid and formatted correctly"""
179
+ is_valid = "@" in email and "." in email.split("@")[-1]
180
+ return {"email": email, "is_valid": is_valid, "suggestion": None if is_valid else "Check format"}
181
+
182
+ @function_tool
183
+ async def send_email(to: str, subject: str, body: str, is_html: bool = True) -> dict:
184
+ """Actually send an email using SMTP configurations from environment."""
185
+ host = os.getenv("SMTP_HOST")
186
+ port = int(os.getenv("SMTP_PORT", "587"))
187
+ username = os.getenv("SMTP_USER")
188
+ password = os.getenv("SMTP_PASSWORD")
189
+ from_email = os.getenv("SMTP_FROM_EMAIL", username)
190
+
191
+ if not all([host, username, password]):
192
+ return {
193
+ "status": "error",
194
+ "message": "SMTP credentials (SMTP_HOST, SMTP_USER, SMTP_PASSWORD) are not configured in environment."
195
+ }
196
+
197
+ message = EmailMessage()
198
+ message["From"] = from_email
199
+ message["To"] = to
200
+ message["Subject"] = subject
201
+ if is_html:
202
+ message.set_content(body, subtype="html")
203
+ else:
204
+ message.set_content(body)
205
+
206
+ try:
207
+ await aiosmtplib.send(
208
+ message,
209
+ hostname=host,
210
+ port=port,
211
+ username=username,
212
+ password=password,
213
+ use_tls=(port == 465),
214
+ start_tls=(port == 587),
215
+ )
216
+ return {"to": to, "subject": subject, "status": "sent", "timestamp": "2024-02-09T12:00:00"}
217
+ except Exception as e:
218
+ return {"status": "error", "message": str(e)}
219
+
220
+ @function_tool
221
+ def web_search(query: str) -> dict:
222
+ """Perform a web search for prospect research"""
223
+ return {"query": query, "results": f"Research data for {query}"}
224
+
225
+ return [draft_cold_email, verify_email_format, send_email, web_search]
226
+
227
+ # Add more domains as needed...
228
+ else: # generic
229
+ @function_tool
230
+ async def generate_analytics(metric: str, time_range: str) -> dict:
231
+ """Generate business analytics"""
232
+ return {"metric": metric, "time_range": time_range, "value": 12500, "trend": "+15%", "insights": f"{metric} growing"}
233
+
234
+ @function_tool
235
+ async def send_notification(recipient: str, message: str, channel: str = "email") -> dict:
236
+ """Send notifications"""
237
+ if channel == "email":
238
+ host = os.getenv("SMTP_HOST")
239
+ if host:
240
+ # Implementation similar to send_email
241
+ return {"recipient": recipient, "message": "Notification sent via actual email", "status": "Sent"}
242
+ return {"recipient": recipient, "message": message, "channel": channel, "status": "Sent"}
243
+
244
+ @function_tool
245
+ async def send_email(to: str, subject: str, body: str, is_html: bool = True) -> dict:
246
+ """Actually send an email using SMTP configurations from environment."""
247
+ host = os.getenv("SMTP_HOST")
248
+ port = int(os.getenv("SMTP_PORT", "587"))
249
+ username = os.getenv("SMTP_USER")
250
+ password = os.getenv("SMTP_PASSWORD")
251
+ from_email = os.getenv("SMTP_FROM_EMAIL", username)
252
+
253
+ if not all([host, username, password]):
254
+ return {
255
+ "status": "error",
256
+ "message": "SMTP credentials (SMTP_HOST, SMTP_USER, SMTP_PASSWORD) are not configured in environment."
257
+ }
258
+
259
+ message = EmailMessage()
260
+ message["From"] = from_email
261
+ message["To"] = to
262
+ message["Subject"] = subject
263
+ if is_html:
264
+ message.set_content(body, subtype="html")
265
+ else:
266
+ message.set_content(body)
267
+
268
+ try:
269
+ await aiosmtplib.send(
270
+ message,
271
+ hostname=host,
272
+ port=port,
273
+ username=username,
274
+ password=password,
275
+ use_tls=(port == 465),
276
+ start_tls=(port == 587),
277
+ )
278
+ return {"to": to, "subject": subject, "status": "sent", "timestamp": "2024-02-09T12:00:00"}
279
+ except Exception as e:
280
+ return {"status": "error", "message": str(e)}
281
+
282
+ @function_tool
283
+ def web_search(query: str) -> dict:
284
+ """Perform a web search for current information"""
285
+ return {"query": query, "results": "Web search functionality"}
286
+
287
+ return [generate_analytics, send_notification, send_email, web_search]
288
+
289
+ # ============================================
290
+ # Initialize Agent
291
+ # ============================================
292
+ def initialize_agent():
293
+ """Initialize the agent with configuration from environment"""
294
+ model = AGENT_CONFIG.get("model", "gpt-4o")
295
+
296
+ # Select appropriate API key and client
297
+ if "gemini" in model.lower():
298
+ api_key = GEMINI_API_KEY
299
+ client = AgentsAsyncOpenAI(api_key=api_key, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
300
+ model_name = "gemini-2.0-flash-exp"
301
+ elif "grok" in model.lower():
302
+ api_key = GROK_API_KEY
303
+ client = AgentsAsyncOpenAI(api_key=api_key, base_url="https://api.x.ai/v1")
304
+ model_name = "grok-beta"
305
+ else:
306
+ api_key = OPENAI_API_KEY
307
+ client = AgentsAsyncOpenAI(api_key=api_key)
308
+ model_name = "gpt-4o"
309
+
310
+ if not api_key:
311
+ raise ValueError(f"API key not found for model: {model}")
312
+
313
+ MODEL = OpenAIChatCompletionsModel(model=model_name, openai_client=client)
314
+
315
+ # Recreate tools - handle both nested and flat business_context
316
+ business_context = AGENT_CONFIG.get("business_context", {})
317
+ if not isinstance(business_context, dict):
318
+ business_context = {}
319
+
320
+ domain = business_context.get("domain") or AGENT_CONFIG.get("domain", "generic")
321
+ business_name = business_context.get("business_name") or AGENT_CONFIG.get("business_name", "Business")
322
+ tools = recreate_tools_from_config(domain, business_name)
323
+
324
+ # Get agent name - try multiple possible keys
325
+ agent_name = AGENT_CONFIG.get("name") or AGENT_CONFIG.get("agent_name", "AI Agent")
326
+
327
+ # Get instructions
328
+ instructions = AGENT_CONFIG.get("instructions", "You are a helpful AI assistant.")
329
+
330
+ # Create agent
331
+ agent = Agent(
332
+ name=agent_name,
333
+ instructions=instructions,
334
+ model=MODEL,
335
+ tools=tools
336
+ )
337
+
338
+ return agent, tools
339
+
340
+ # Initialize agent on startup
341
+ AGENT_INSTANCE, AGENT_TOOLS = initialize_agent()
342
+
343
+ # ============================================
344
+ # API Endpoints
345
+ # ============================================
346
+ @app.get("/")
347
+ async def root():
348
+ """Health check and agent info"""
349
+ # Extract tool names properly
350
+ tool_names = []
351
+ for tool in AGENT_TOOLS:
352
+ if hasattr(tool, '__name__'):
353
+ tool_names.append(tool.__name__)
354
+ elif hasattr(tool, 'name'):
355
+ tool_names.append(tool.name)
356
+ else:
357
+ # Try to extract from string representation
358
+ tool_str = str(tool)
359
+ if "name='" in tool_str:
360
+ try:
361
+ name_start = tool_str.index("name='") + 6
362
+ name_end = tool_str.index("'", name_start)
363
+ tool_names.append(tool_str[name_start:name_end])
364
+ except:
365
+ tool_names.append(str(tool)[:50]) # Truncate long strings
366
+ else:
367
+ tool_names.append(str(tool)[:50])
368
+
369
+ return {
370
+ "status": "online",
371
+ "agent_name": AGENT_CONFIG.get("name") or AGENT_CONFIG.get("agent_name") or "GenericAgent",
372
+ "agent_id": AGENT_CONFIG.get("agent_id"),
373
+ "business": AGENT_CONFIG.get("business_context", {}).get("business_name") if isinstance(AGENT_CONFIG.get("business_context"), dict) else None,
374
+ "domain": AGENT_CONFIG.get("business_context", {}).get("domain") if isinstance(AGENT_CONFIG.get("business_context"), dict) else AGENT_CONFIG.get("domain"),
375
+ "tools_count": len(AGENT_TOOLS),
376
+ "tools": tool_names,
377
+ "model": AGENT_CONFIG.get("model"),
378
+ "deployment": "Hugging Face Space"
379
+ }
380
+
381
+ @app.post("/run", response_model=ChatResponse)
382
+ async def run_agent(request: ChatRequest) -> ChatResponse:
383
+ """
384
+ Main endpoint to interact with the agent.
385
+ This is the primary interface for users.
386
+ """
387
+ import time
388
+
389
+ try:
390
+ # Run the agent
391
+ runner = Runner()
392
+ temp_session = SQLiteSession(":memory:")
393
+
394
+ response = await runner.run(AGENT_INSTANCE, request.message, session=temp_session)
395
+ final_output = str(response.final_output) if hasattr(response, 'final_output') else str(response)
396
+
397
+ return ChatResponse(
398
+ status="success",
399
+ agent_name=AGENT_CONFIG.get("name", "GenericAgent"),
400
+ user_message=request.message,
401
+ agent_response=final_output,
402
+ tools_available=[tool.__name__ if hasattr(tool, '__name__') else str(tool) for tool in AGENT_TOOLS],
403
+ timestamp=time.time()
404
+ )
405
+
406
+ except Exception as e:
407
+ raise HTTPException(status_code=500, detail=f"Agent execution error: {str(e)}")
408
+
409
+ @app.get("/config")
410
+ async def get_config():
411
+ """Get agent configuration (without sensitive data)"""
412
+ safe_config = {
413
+ "agent_id": AGENT_CONFIG.get("agent_id"),
414
+ "name": AGENT_CONFIG.get("name"),
415
+ "model": AGENT_CONFIG.get("model"),
416
+ "business_context": AGENT_CONFIG.get("business_context"),
417
+ "tools_count": len(AGENT_TOOLS),
418
+ "deployment_ready": AGENT_CONFIG.get("deployment_ready")
419
+ }
420
+ return safe_config
421
+
422
+ @app.get("/health")
423
+ async def health_check():
424
+ """Health check endpoint"""
425
+ return {"status": "healthy", "agent": AGENT_CONFIG.get("name") or AGENT_CONFIG.get("agent_name")}
426
+
427
+ @app.get("/debug/config")
428
+ async def debug_config():
429
+ """Debug endpoint to see what config is loaded (without sensitive data)"""
430
+ safe_config = {
431
+ "has_config": bool(AGENT_CONFIG),
432
+ "config_keys": list(AGENT_CONFIG.keys()) if isinstance(AGENT_CONFIG, dict) else [],
433
+ "agent_name": AGENT_CONFIG.get("name") or AGENT_CONFIG.get("agent_name"),
434
+ "agent_id": AGENT_CONFIG.get("agent_id"),
435
+ "model": AGENT_CONFIG.get("model"),
436
+ "has_business_context": "business_context" in AGENT_CONFIG,
437
+ "business_context_type": type(AGENT_CONFIG.get("business_context")).__name__,
438
+ "domain": AGENT_CONFIG.get("business_context", {}).get("domain") if isinstance(AGENT_CONFIG.get("business_context"), dict) else AGENT_CONFIG.get("domain"),
439
+ "business_name": AGENT_CONFIG.get("business_context", {}).get("business_name") if isinstance(AGENT_CONFIG.get("business_context"), dict) else None,
440
+ "tools_count_from_config": len(AGENT_CONFIG.get("tools", [])),
441
+ "tools_count_loaded": len(AGENT_TOOLS),
442
+ }
443
+ return safe_config
444
+
445
+ if __name__ == "__main__":
446
+ import uvicorn
447
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi>=0.110.0
2
+ uvicorn[standard]==0.24.0
3
+ pydantic>=2.12.3,<3
4
+ python-dotenv==1.0.0
5
+ anyio>=4.5
6
+ openai-agents==0.6.4
7
+ aiosmtplib>=3.0.1