Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,22 @@
|
|
| 1 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import os
|
| 3 |
import json
|
| 4 |
import threading
|
| 5 |
import re
|
| 6 |
from typing import Dict, Any
|
| 7 |
|
| 8 |
-
# Web frameworks
|
| 9 |
import gradio as gr
|
| 10 |
from fastapi import FastAPI, Depends, HTTPException
|
| 11 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 12 |
import uvicorn
|
| 13 |
|
| 14 |
-
# Transformers pipeline
|
| 15 |
from transformers import pipeline
|
| 16 |
|
| 17 |
-
# ===== LangChain Imports
|
| 18 |
from langchain_community.llms import HuggingFacePipeline
|
| 19 |
from langchain_community.utilities import SerpAPIWrapper
|
| 20 |
from langchain_community.vectorstores import Chroma
|
|
@@ -26,5 +28,215 @@ from langchain.chains import LLMChain
|
|
| 26 |
from langchain.prompts import PromptTemplate
|
| 27 |
from langchain.docstore.document import Document
|
| 28 |
|
| 29 |
-
# ✅
|
| 30 |
from langchain.tools.python.tool import PythonAstREPLTool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===========================================
|
| 2 |
+
# Medini Autonomous Agent - app.py
|
| 3 |
+
# Compatible with LangChain 0.3.x + langchain-community
|
| 4 |
+
# ===========================================
|
| 5 |
+
|
| 6 |
import os
|
| 7 |
import json
|
| 8 |
import threading
|
| 9 |
import re
|
| 10 |
from typing import Dict, Any
|
| 11 |
|
|
|
|
| 12 |
import gradio as gr
|
| 13 |
from fastapi import FastAPI, Depends, HTTPException
|
| 14 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 15 |
import uvicorn
|
| 16 |
|
|
|
|
| 17 |
from transformers import pipeline
|
| 18 |
|
| 19 |
+
# ===== LangChain Community Imports =====
|
| 20 |
from langchain_community.llms import HuggingFacePipeline
|
| 21 |
from langchain_community.utilities import SerpAPIWrapper
|
| 22 |
from langchain_community.vectorstores import Chroma
|
|
|
|
| 28 |
from langchain.prompts import PromptTemplate
|
| 29 |
from langchain.docstore.document import Document
|
| 30 |
|
| 31 |
+
# ✅ Updated Python REPL tool import
|
| 32 |
from langchain.tools.python.tool import PythonAstREPLTool
|
| 33 |
+
|
| 34 |
+
# ===========================================
|
| 35 |
+
# ENVIRONMENT VARIABLES
|
| 36 |
+
# ===========================================
|
| 37 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 38 |
+
SERPAPI_KEY = os.getenv("SERPAPI_API_KEY")
|
| 39 |
+
JWT_SECRET = os.getenv("JWT_SECRET", "changeme123")
|
| 40 |
+
|
| 41 |
+
# ===========================================
|
| 42 |
+
# AUTH
|
| 43 |
+
# ===========================================
|
| 44 |
+
security = HTTPBearer()
|
| 45 |
+
|
| 46 |
+
def verify_jwt(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 47 |
+
token = credentials.credentials
|
| 48 |
+
if token != JWT_SECRET:
|
| 49 |
+
raise HTTPException(status_code=403, detail="Invalid token")
|
| 50 |
+
return True
|
| 51 |
+
|
| 52 |
+
# ===========================================
|
| 53 |
+
# MODEL LOADER
|
| 54 |
+
# ===========================================
|
| 55 |
+
MODEL_ID = "PuruAI/Medini_Intelligence"
|
| 56 |
+
FALLBACK_MODEL = "gpt2"
|
| 57 |
+
|
| 58 |
+
def load_llm():
|
| 59 |
+
pipeline_kwargs = {"max_new_tokens": 512, "temperature": 0.7}
|
| 60 |
+
try:
|
| 61 |
+
model_pipeline = pipeline("text-generation", model=MODEL_ID, use_auth_token=HF_TOKEN, **pipeline_kwargs)
|
| 62 |
+
except Exception:
|
| 63 |
+
print(f"Warning: Failed to load {MODEL_ID}. Falling back to {FALLBACK_MODEL}.")
|
| 64 |
+
model_pipeline = pipeline("text-generation", model=FALLBACK_MODEL, **pipeline_kwargs)
|
| 65 |
+
|
| 66 |
+
return HuggingFacePipeline(pipeline=model_pipeline)
|
| 67 |
+
|
| 68 |
+
llm = load_llm()
|
| 69 |
+
|
| 70 |
+
# ===========================================
|
| 71 |
+
# VECTOR MEMORY
|
| 72 |
+
# ===========================================
|
| 73 |
+
embeddings = HuggingFaceEmbeddings()
|
| 74 |
+
chroma_db = Chroma(persist_directory="./medini_memory", embedding_function=embeddings)
|
| 75 |
+
retriever = chroma_db.as_retriever()
|
| 76 |
+
|
| 77 |
+
qa_prompt_template = """
|
| 78 |
+
You are a question-answering system. Use the following context, which contains information retrieved from memory, to answer the user's question.
|
| 79 |
+
If the context is empty or does not contain the answer, state clearly that the information is not in memory.
|
| 80 |
+
Context:
|
| 81 |
+
{context}
|
| 82 |
+
Question: {question}
|
| 83 |
+
Answer:
|
| 84 |
+
"""
|
| 85 |
+
QA_PROMPT = PromptTemplate(template=qa_prompt_template, input_variables=["context", "question"])
|
| 86 |
+
qa_chain = LLMChain(llm=llm, prompt=QA_PROMPT)
|
| 87 |
+
|
| 88 |
+
def retrieve_and_answer(question: str) -> str:
|
| 89 |
+
docs = retriever.get_relevant_documents(question)
|
| 90 |
+
context = "\n---\n".join([d.page_content for d in docs])
|
| 91 |
+
return qa_chain.run(context=context, question=question)
|
| 92 |
+
|
| 93 |
+
# ===========================================
|
| 94 |
+
# TOOLS
|
| 95 |
+
# ===========================================
|
| 96 |
+
search = SerpAPIWrapper(serpapi_api_key=SERPAPI_KEY)
|
| 97 |
+
python_tool = PythonAstREPLTool()
|
| 98 |
+
|
| 99 |
+
tools = [
|
| 100 |
+
Tool(name="Knowledge Recall", func=retrieve_and_answer, description="Retrieve info from Medini memory (Chroma DB)."),
|
| 101 |
+
Tool(name="Web Search", func=search.run, description="Search the web for up-to-date information."),
|
| 102 |
+
Tool(name="Python REPL", func=python_tool.run, description="Execute Python code for math/data manipulation."),
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
TOOL_MAP = {tool.name.lower().replace(" ", ""): tool.func for tool in tools}
|
| 106 |
+
|
| 107 |
+
# ===========================================
|
| 108 |
+
# AGENT
|
| 109 |
+
# ===========================================
|
| 110 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 111 |
+
agent = initialize_agent(
|
| 112 |
+
tools=tools,
|
| 113 |
+
llm=llm,
|
| 114 |
+
agent="conversational-react-description",
|
| 115 |
+
memory=memory,
|
| 116 |
+
verbose=True
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# ===========================================
|
| 120 |
+
# PLANNER
|
| 121 |
+
# ===========================================
|
| 122 |
+
plan_prompt = PromptTemplate(
|
| 123 |
+
input_variables=["goal"],
|
| 124 |
+
template="""
|
| 125 |
+
You are Medini Planner. Decompose the high-level goal into a JSON object containing a 'steps' array (max 6 steps). Each step must have: id (integer), name (short string), description (detailed instruction), and tool_hint (either 'recall', 'search', 'python', or 'agent').
|
| 126 |
+
Return JSON only.
|
| 127 |
+
Goal: {goal}
|
| 128 |
+
"""
|
| 129 |
+
)
|
| 130 |
+
planner_chain = LLMChain(llm=llm, prompt=plan_prompt)
|
| 131 |
+
|
| 132 |
+
def create_plan(goal: str) -> Dict[str, Any]:
|
| 133 |
+
raw = planner_chain.run(goal=goal)
|
| 134 |
+
m = re.search(r"\{.*\}", raw, flags=re.DOTALL)
|
| 135 |
+
json_str = m.group(0) if m else raw
|
| 136 |
+
json_str = json_str.replace("```json", "").replace("```", "").strip()
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
plan = json.loads(json_str)
|
| 140 |
+
if 'steps' not in plan:
|
| 141 |
+
raise ValueError("Parsed JSON missing 'steps'.")
|
| 142 |
+
return plan
|
| 143 |
+
except json.JSONDecodeError as e:
|
| 144 |
+
print(f"JSON Parsing Error: {e} in string: {json_str[:200]}...")
|
| 145 |
+
raise ValueError("Planner returned malformed JSON.") from e
|
| 146 |
+
|
| 147 |
+
def execute_step(step: Dict[str, Any]) -> Dict[str, Any]:
|
| 148 |
+
hint = (step.get("tool_hint") or "").lower()
|
| 149 |
+
input_text = step.get("description")
|
| 150 |
+
output, status = "Execution skipped.", "error"
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
tool_func = None
|
| 154 |
+
if "recall" in hint:
|
| 155 |
+
tool_func = TOOL_MAP.get("knowledgerecall")
|
| 156 |
+
elif "search" in hint:
|
| 157 |
+
tool_func = TOOL_MAP.get("websearch")
|
| 158 |
+
elif "python" in hint:
|
| 159 |
+
tool_func = TOOL_MAP.get("pythonrepl")
|
| 160 |
+
|
| 161 |
+
if tool_func:
|
| 162 |
+
output = tool_func(input_text)
|
| 163 |
+
else:
|
| 164 |
+
output = agent.run(input_text)
|
| 165 |
+
|
| 166 |
+
status = "ok"
|
| 167 |
+
except Exception as e:
|
| 168 |
+
output = f"Execution Error: {str(e)}"
|
| 169 |
+
|
| 170 |
+
chroma_db.add_documents([Document(page_content=f"Step {step['id']} - {step['name']} Result: {output}")])
|
| 171 |
+
return {"id": step['id'], "name": step['name'], "status": status, "output": output}
|
| 172 |
+
|
| 173 |
+
def execute_plan(goal: str) -> Dict[str, Any]:
|
| 174 |
+
try:
|
| 175 |
+
plan = create_plan(goal)
|
| 176 |
+
except ValueError as e:
|
| 177 |
+
return {"goal": goal, "error": str(e)}
|
| 178 |
+
|
| 179 |
+
results = [execute_step(step) for step in plan.get("steps", [])]
|
| 180 |
+
return {"goal": goal, "plan": plan, "results": results}
|
| 181 |
+
|
| 182 |
+
# ===========================================
|
| 183 |
+
# FASTAPI BACKEND
|
| 184 |
+
# ===========================================
|
| 185 |
+
app = FastAPI(title="Medini Agent API")
|
| 186 |
+
|
| 187 |
+
@app.post("/chat")
|
| 188 |
+
def chat_endpoint(message: str, auth: bool = Depends(verify_jwt)):
|
| 189 |
+
response = agent.run(message)
|
| 190 |
+
return {"response": response}
|
| 191 |
+
|
| 192 |
+
@app.post("/goal")
|
| 193 |
+
def goal_endpoint(goal: str, auth: bool = Depends(verify_jwt)):
|
| 194 |
+
return execute_plan(goal)
|
| 195 |
+
|
| 196 |
+
# ===========================================
|
| 197 |
+
# GRADIO FRONTEND
|
| 198 |
+
# ===========================================
|
| 199 |
+
def gradio_chat(message, history):
|
| 200 |
+
try:
|
| 201 |
+
response = agent.run(message)
|
| 202 |
+
history.append((message, response))
|
| 203 |
+
except Exception as e:
|
| 204 |
+
history.append((message, f"Error: {str(e)}"))
|
| 205 |
+
return history, ""
|
| 206 |
+
|
| 207 |
+
def gradio_execute_plan(goal):
|
| 208 |
+
try:
|
| 209 |
+
return execute_plan(goal)
|
| 210 |
+
except Exception as e:
|
| 211 |
+
return {"error": f"Failed to execute plan: {str(e)}"}
|
| 212 |
+
|
| 213 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 214 |
+
gr.Markdown("# 🤖 Medini Autonomous Agent")
|
| 215 |
+
gr.Markdown("Chat or submit high-level goals. Agentic AI handles reasoning, memory, and tool use.")
|
| 216 |
+
|
| 217 |
+
with gr.Row():
|
| 218 |
+
with gr.Column(scale=2):
|
| 219 |
+
gr.Markdown("## Conversational Chat")
|
| 220 |
+
chatbot = gr.Chatbot(height=400)
|
| 221 |
+
msg = gr.Textbox(placeholder="Type your message...", label="Chat Input")
|
| 222 |
+
clear_btn = gr.Button("Clear Chat")
|
| 223 |
+
msg.submit(gradio_chat, [msg, chatbot], [chatbot, msg])
|
| 224 |
+
clear_btn.click(lambda: [], None, chatbot, queue=False)
|
| 225 |
+
|
| 226 |
+
with gr.Column(scale=1):
|
| 227 |
+
gr.Markdown("## Autonomous Goal Planner")
|
| 228 |
+
goal_input = gr.Textbox(placeholder="Enter high-level goal...", label="Goal")
|
| 229 |
+
run_goal_btn = gr.Button("Run Goal", variant="primary")
|
| 230 |
+
gr.Markdown("---")
|
| 231 |
+
gr.Markdown("### Execution Report")
|
| 232 |
+
goal_output = gr.JSON(label="Plan and Results")
|
| 233 |
+
run_goal_btn.click(gradio_execute_plan, [goal_input], goal_output)
|
| 234 |
+
|
| 235 |
+
# ===========================================
|
| 236 |
+
# LAUNCH
|
| 237 |
+
# ===========================================
|
| 238 |
+
if __name__ == "__main__":
|
| 239 |
+
def start_api():
|
| 240 |
+
uvicorn.run(app, host="0.0.0.0", port=8000, log_level="critical")
|
| 241 |
+
threading.Thread(target=start_api, daemon=True).start()
|
| 242 |
+
demo.launch(share=False)
|