Spaces:
Sleeping
Sleeping
| import sys | |
| import os | |
| sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) | |
| from fastapi import FastAPI, Request, Form | |
| from fastapi.responses import PlainTextResponse | |
| from pydantic import BaseModel, Field | |
| from agents.session import ask_jarvis, reset_cache | |
| from enums.core_enums import ModelEnum | |
| from config import DEFAULT_MODEL | |
| import uvicorn | |
| app = FastAPI( | |
| title="Jarvis API", | |
| description="API backend for Jarvis, an intelligent chatbot with support for multiple models and conversation memory.", | |
| version="1.0.0" | |
| ) | |
| class AskInput(BaseModel): | |
| """ | |
| Input data to make a query to the Jarvis assistant. | |
| """ | |
| message: str = Field(..., description="Text message sent to Jarvis.") | |
| model_name: str = Field(default=DEFAULT_MODEL.name, description="Name of the model to use. Must match a valid value from the ModelEnum.") | |
| thread_id: str = Field(..., description="Conversation thread identifier to maintain context.") | |
| async def ask_json(input_data: AskInput): | |
| """ | |
| Send a question or message to Jarvis. | |
| This route processes a textual query and returns the response generated by the assistant. | |
| """ | |
| model_enum = ModelEnum[input_data.model_name] | |
| answer = ask_jarvis(input_data.message, model_enum, input_data.thread_id) | |
| return {"response": answer} | |
| async def whatsapp_webhook( | |
| request: Request, | |
| Body: str = Form(..., description="Message received from WhatsApp."), | |
| From: str = Form(..., description="Sender's phone number."), | |
| ProfileName: str = Form(None, description="User profile name (optional).") | |
| ): | |
| """ | |
| Incoming webhook for messages from WhatsApp. | |
| Uses the sender's number as the thread identifier to maintain the conversation. | |
| """ | |
| model_enum = DEFAULT_MODEL | |
| thread_id = From | |
| responses = ask_jarvis(Body, model_enum, thread_id) | |
| response_text = "\n".join(responses) | |
| return PlainTextResponse(response_text) | |
| async def reset_memory(): | |
| """ | |
| Clears the assistant's temporary memory. | |
| Useful to restart the context or begin a new conversation from scratch. | |
| """ | |
| reset_cache() | |
| return {"status": "ok", "message": "Memory reset"} | |
| if __name__ == "__main__": | |
| uvicorn.run("api.main_api:app", host="0.0.0.0", port=8000, reload=True) | |