Spaces:
Sleeping
Sleeping
File size: 14,798 Bytes
fd1a435 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | import os
import uuid
import time
import json
import asyncio
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import Optional
import socketio
from firebase_admin import db, initialize_app, credentials, _apps
from dotenv import load_dotenv
from cryptography.fernet import Fernet
from validation_agent import run_validation_agent
from extractor_agent_runner import AgentOrchestrator
from agent_architect import LiveAgentArchitect, AgentDeployer
from agents import Runner, SQLiteSession, OpenAIChatCompletionsModel, Agent
from openai import AsyncOpenAI as AgentsAsyncOpenAI
load_dotenv()
# --- Encryption setup ---
ENCRYPTION_KEY = os.getenv("ENCRYPTION_KEY")
if not ENCRYPTION_KEY:
raise ValueError("ENCRYPTION_KEY not set in .env")
fernet = Fernet(ENCRYPTION_KEY.encode())
def encrypt_api_key(api_key: str) -> str:
return fernet.encrypt(api_key.encode()).decode()
def decrypt_api_key(encrypted_key: str) -> str:
return fernet.decrypt(encrypted_key.encode()).decode()
# --- Firebase initialization ---
cred = credentials.Certificate("firebase/serviceAccountKey.json")
if not _apps:
initialize_app(cred, {'databaseURL': os.getenv("FIREBASE_DB_URL")})
# --- FastAPI + Socket.IO setup ---
app = FastAPI(title="AgentForge API", version="1.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins="*", max_http_buffer_size=10**8)
socket_app = socketio.ASGIApp(sio, app)
# --- Request/Response Models ---
class ValidateRequest(BaseModel):
model: str = Field(..., description="Model name")
api_key: str = Field(..., description="API key to validate")
class ValidateResponse(BaseModel):
is_valid: bool
error: Optional[str] = None
model: str
class RunSessionRequest(BaseModel):
query: str = Field(..., description="User's business idea")
model: str = Field(default="gpt-4o", description="Model to use")
api_key: str = Field(default=os.getenv("OPENAI_API_KEY"), description="API key")
class SessionResponse(BaseModel):
session_id: str
status: str = "created"
class RunResponse(BaseModel):
status: str
result: dict
class ChatWithAgentRequest(BaseModel):
agent_id: str = Field(..., description="Agent ID from build result")
message: str = Field(..., description="User message to the agent")
session_id: str = Field(..., description="Session ID")
# --- Helper functions ---
async def emit_log(session_id: str, message: str, type: str = "log"):
"""Emit log to Firebase and Socket.IO"""
try:
ref = db.reference(f'sessions/{session_id}/logs')
ref.push({
'message': message,
'type': type,
'timestamp': time.time()
})
await sio.emit('log_update', {
'message': message,
'type': type,
'timestamp': time.time()
}, room=session_id)
except Exception as e:
print(f"Error emitting log: {e}")
async def save_session_result(session_id: str, result: dict):
"""Save session result to Firebase"""
try:
ref = db.reference(f'sessions/{session_id}/result')
ref.set(result)
except Exception as e:
print(f"Error saving session result: {e}")
# --- API Endpoints ---
@app.get("/", tags=["Health"])
async def root():
return {
"status": "AgentForge API Online",
"version": "1.0.0",
"features": ["validation", "extraction", "live_agent_builder"],
"socket_io": "initialized"
}
@app.post("/validate", response_model=ValidateResponse, tags=["Validation"])
async def validate_key(request: ValidateRequest) -> ValidateResponse:
try:
result = await run_validation_agent(request.model, request.api_key)
return ValidateResponse(
is_valid=result.is_valid,
error=result.error,
model=request.model
)
except Exception as e:
return ValidateResponse(
is_valid=False,
error=f"Validation error: {str(e)}",
model=request.model
)
@app.post("/start", response_model=SessionResponse, tags=["Sessions"])
async def start_session() -> SessionResponse:
session_id = str(uuid.uuid4())
try:
db.reference(f'sessions/{session_id}').set({
'status': 'awaiting_query',
'created_at': time.time(),
'logs': [],
'api_keys': {}
})
await emit_log(session_id, "Session started. Ready to receive query.", "system")
return SessionResponse(session_id=session_id, status="created")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to create session: {str(e)}")
@app.post("/session/{sid}/run", response_model=RunResponse, tags=["Sessions"])
async def run_agents(sid: str, request_data: RunSessionRequest) -> RunResponse:
"""
Complete pipeline: Validation β Extraction β Live Agent Build
"""
query = request_data.query
model = request_data.model.lower()
api_key = request_data.api_key
if not query or not model or not api_key:
await emit_log(sid, "Error: Missing required fields", "error")
raise HTTPException(status_code=400, detail="query, model, and api_key are required")
try:
# Step 1: Log start
await emit_log(sid, f"π¬ User Query: {query}", "user")
await emit_log(sid, f"π€ Model: {model}", "system")
# Step 2: Encrypt & store key
encrypted_key = encrypt_api_key(api_key)
db.reference(f'sessions/{sid}/api_keys/{model}').set(encrypted_key)
await emit_log(sid, f"π API key encrypted", "success")
api_key_decrypted = decrypt_api_key(encrypted_key)
# Step 3: Validate API key
await emit_log(sid, "π Validating API key...", "system")
validation = await run_validation_agent(model, api_key_decrypted)
if not validation.is_valid:
await emit_log(sid, f"β Validation failed: {validation.error}", "error")
return RunResponse(
status="error",
result={"stage": "validation", "message": validation.error}
)
await emit_log(sid, "β
API key validated", "success")
# Step 4: Run extraction
await emit_log(sid, "π Starting extraction...", "system")
orchestrator = AgentOrchestrator(session_id=sid)
extraction_result = await orchestrator.run(query, model, api_key_decrypted)
if extraction_result["status"] != "success":
await emit_log(sid, f"β Extraction failed", "error")
db.reference(f'sessions/{sid}').update({'status': 'error'})
return RunResponse(status="error", result=extraction_result)
await emit_log(sid, "β
Extraction complete!", "success")
# Step 5: BUILD LIVE AGENT (This is the missing part!)
await emit_log(sid, "ποΈ Building live OpenAI agent...", "system")
await emit_log(sid, "βοΈ Mapping features to tools...", "system")
architect = LiveAgentArchitect(session_id=sid)
extraction_data = extraction_result.get('extraction', {})
# Build the agent
agent_result = await architect.build_agent(extraction_data, model, api_key_decrypted)
# Add agent build results to response
if agent_result.status == "success":
# Save to Firebase
await AgentDeployer.save_to_firebase(sid, agent_result.agent_config)
# Deployment code is already in agent_result
deployment_code = agent_result.deployment_code
# Add to result
extraction_result["agent_build"] = {
"status": "success",
"agent_id": agent_result.agent_config.agent_id,
"agent_name": agent_result.agent_config.name,
"model": agent_result.agent_config.model,
"tools": [
{
"name": tool.name,
"description": tool.description,
"parameters": tool.parameters
} for tool in agent_result.agent_config.tools
],
"tools_count": len(agent_result.agent_config.tools),
"tone": agent_result.agent_config.tone,
"instructions": agent_result.agent_config.instructions,
"test_response": agent_result.agent_test_response,
"deployment_code": deployment_code,
"business_context": agent_result.agent_config.business_context
}
await emit_log(sid, f"β
Agent '{agent_result.agent_config.name}' built!", "success")
await emit_log(sid, f"π Agent ID: {agent_result.agent_config.agent_id}", "info")
await emit_log(sid, f"π§ Tools: {len(agent_result.agent_config.tools)}", "info")
await emit_log(sid, f"π Tone: {agent_result.agent_config.tone}", "info")
await emit_log(sid, f"\n㪠Test: {agent_result.agent_test_response[:100]}...", "info")
await emit_log(sid, "\nπ LIVE AGENT READY FOR DEPLOYMENT!", "success")
else:
await emit_log(sid, f"β οΈ Agent build failed: {agent_result.error}", "warning")
extraction_result["agent_build"] = {
"status": "error",
"error": agent_result.error
}
# Save final result
await save_session_result(sid, extraction_result)
# Summary logs
business = extraction_data.get('business', {})
await emit_log(sid, f"\nπ Business: {business.get('business_name')}", "result")
await emit_log(sid, f"π Industry: {business.get('industry')}", "result")
if extraction_result.get("agent_build", {}).get("status") == "success":
agent_build = extraction_result["agent_build"]
await emit_log(sid, f"\nπ€ Live Agent: {agent_build['agent_name']}", "success")
await emit_log(sid, f"π§ Tools Available: {agent_build['tools_count']}", "success")
await emit_log(sid, "\nβ
Complete! Agent is live and ready.", "success")
db.reference(f'sessions/{sid}').update({'status': 'completed'})
return RunResponse(status="success", result=extraction_result)
except Exception as e:
error_msg = str(e)
await emit_log(sid, f"π₯ Error: {error_msg}", "error")
db.reference(f'sessions/{sid}').update({'status': 'error'})
raise HTTPException(status_code=500, detail=error_msg)
@app.post("/agent/chat", tags=["Agent Execution"])
async def chat_with_agent(request: ChatWithAgentRequest):
try:
agent_id = request.agent_id
user_message = request.message
session_id = request.session_id
# Get agent configuration from Firebase
agent_ref = db.reference(f'agents/{agent_id}')
agent_data = agent_ref.get()
if not agent_data:
raise HTTPException(status_code=404, detail="Agent not found")
# Get encrypted API key from session
session_ref = db.reference(f'sessions/{session_id}/api_keys')
api_keys = session_ref.get()
model = agent_data.get('model', 'gpt-4o')
model_key = model.split('-')[0] if '-' in model else model
encrypted_key = None
for key_name, key_value in (api_keys or {}).items():
if model_key in key_name:
encrypted_key = key_value
break
if not encrypted_key:
raise HTTPException(status_code=400, detail="API key not found for this model")
api_key = decrypt_api_key(encrypted_key)
# Setup OpenAI client
if "gemini" in model.lower():
client = AgentsAsyncOpenAI(api_key=api_key, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
model_name = "gemini-2.0-flash-exp"
elif "grok" in model.lower():
client = AgentsAsyncOpenAI(api_key=api_key, base_url="https://api.x.ai/v1")
model_name = "grok-beta"
else:
client = AgentsAsyncOpenAI(api_key=api_key)
model_name = "gpt-4o"
MODEL = OpenAIChatCompletionsModel(model=model_name, openai_client=client)
# === FIXED PART: Recreate tools safely using domain ===
from agent_architect import DynamicToolFactory
domain = agent_data['business_context']['domain']
business_name = agent_data['business_context'].get('business_name', 'Agent')
tools, _ = DynamicToolFactory.create_tools_for_domain(domain, business_name)
agent = Agent(
name=agent_data['name'],
instructions=agent_data['instructions'],
model=MODEL,
tools=tools
)
# ======================================================
runner = Runner()
temp_session = SQLiteSession(f":memory:")
response = await runner.run(agent, user_message, session=temp_session)
final_output = str(response.final_output) if hasattr(response, 'final_output') else str(response)
await emit_log(session_id, f"User: {user_message}", "user")
await emit_log(session_id, f"{agent_data['name']}: {final_output[:200]}...", "agent")
return {
"status": "success",
"agent_id": agent_id,
"agent_name": agent_data['name'],
"user_message": user_message,
"agent_response": final_output,
"tools_used": [tool['name'] for tool in agent_data.get('tools', [])],
"timestamp": time.time()
}
except Exception as e:
error_msg = str(e)
await emit_log(session_id, f"Agent error: {error_msg}", "error")
raise HTTPException(status_code=500, detail=error_msg)
# --- Socket.IO Events ---
@sio.event
async def connect(sid, environ):
print(f"β
Client connected: {sid}")
@sio.event
async def disconnect(sid):
print(f"β Client disconnected: {sid}")
@sio.event
async def join(sid, data):
session_id = data.get('session_id')
if session_id:
await sio.enter_room(sid, session_id)
print(f"π₯ Client {sid} joined room: {session_id}")
await sio.emit('joined', {'session_id': session_id}, room=sid)
# Mount Socket.IO - IMPORTANT: Do this LAST
app.mount("/", socket_app)
|