Spaces:
Runtime error
Runtime error
| from fastapi import FastAPI, Request, Header | |
| from fastapi.responses import HTMLResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import os, uuid | |
| from memory import MemoryVectorStore | |
| from auth import authorize | |
| from session import init_session_db, create_session, log_interaction, get_session_logs | |
| import gradio as gr | |
| from sentence_transformers import SentenceTransformer | |
| import faiss | |
| import numpy as np | |
| model = SentenceTransformer('all-MiniLM-L6-v2') | |
| index = faiss.IndexFlatL2(384) | |
| memory_text = [] | |
| def autonomous_agent(input_text): | |
| vec = model.encode([input_text]) | |
| index.add(vec) | |
| memory_text.append(input_text) | |
| if index.ntotal > 1: | |
| D, I = index.search(vec, k=2) | |
| related = memory_text[I[0][1]] | |
| response = f"🧠 Memory Match: {related}\n🤖 Working on: {input_text}" | |
| else: | |
| response = f"🤖 Received: {input_text}\n🧠 No prior memory yet." | |
| return response | |
| ui = gr.Interface(fn=autonomous_agent, inputs="text", outputs="text", title="Autonomous AI Agent", description="Self-enhancing chatbot with vector memory.") | |
| ui.launch(share=False, inbrowser=False) | |
| app = FastAPI() | |
| memory = MemoryVectorStore() | |
| init_session_db() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"] | |
| ) | |
| async def root(): | |
| return open("static/index.html").read() | |
| async def session_task(request: Request, x_api_key: str = Header(...)): | |
| data = await request.json() | |
| goal = data.get("goal", "") | |
| user = authorize(x_api_key) | |
| if not user: | |
| return {"error": "Unauthorized"} | |
| session_id = data.get("session_id", create_session(user)) | |
| memory.add(goal) | |
| ideas = memory.search(goal) | |
| result = f"[Goal]: {goal}\n[Related]: {ideas}\n[Response]: 🚧 working on it..." | |
| memory.add(result) | |
| log_interaction(session_id, goal, result) | |
| return {"session_id": session_id, "output": result} | |
| def logs(sid: str): | |
| return get_session_logs(sid) | |
| app.mount("/static", StaticFiles(directory="static"), name="static") | |