Spaces:
Paused
Paused
Soham Waghmare
commited on
Commit
·
fd3de6a
1
Parent(s):
70f0982
feat: Re-Act autonomous agent minimal implementation
Browse files
langgraph_backend/agent_tools.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
from langchain_core.messages.ai import AIMessage
|
| 6 |
+
from langchain_core.tools import tool
|
| 7 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 8 |
+
from langgraph.checkpoint.memory import MemorySaver
|
| 9 |
+
from langgraph.prebuilt import create_react_agent
|
| 10 |
+
from langgraph.types import Command, interrupt
|
| 11 |
+
|
| 12 |
+
from tools_tools import calc
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
logging.basicConfig(level=logging.INFO)
|
| 16 |
+
load_dotenv()
|
| 17 |
+
|
| 18 |
+
checkpointer = MemorySaver()
|
| 19 |
+
tools = [calc]
|
| 20 |
+
|
| 21 |
+
# --- LangChain LLM setup (Gemini, correct usage) ---
|
| 22 |
+
model = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=os.getenv("GOOGLE_API_KEY"))
|
| 23 |
+
agent = create_react_agent(
|
| 24 |
+
model=model,
|
| 25 |
+
tools=tools,
|
| 26 |
+
checkpointer=checkpointer,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Usage example
|
| 30 |
+
config = {"configurable": {"thread_id": "research_session_1"}}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
async def invoke_agent(message: str, thread_id: str):
|
| 34 |
+
config = {"configurable": {"thread_id": thread_id}}
|
| 35 |
+
|
| 36 |
+
async for event in agent.astream({"messages": [{"role": "user", "content": message}]}, config=config):
|
| 37 |
+
print(event)
|
| 38 |
+
if "agent" in event:
|
| 39 |
+
response = [
|
| 40 |
+
{"type": "ai_msg", "content": m.content, "total_tokens": m.usage_metadata["total_tokens"], "tool_calls": m.tool_calls}
|
| 41 |
+
for m in event["agent"]["messages"]
|
| 42 |
+
]
|
| 43 |
+
elif "tools" in event:
|
| 44 |
+
response = [{"type": "tool_resp", "content": m.content} for m in event["tools"]["messages"]]
|
| 45 |
+
yield response
|
langgraph_backend/app_tools.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from typing import Annotated, Any, Dict, List, Literal, Optional, TypedDict
|
| 6 |
+
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
from fastapi import FastAPI, Request
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
from fastapi.responses import StreamingResponse
|
| 11 |
+
|
| 12 |
+
from agent_tools import invoke_agent
|
| 13 |
+
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
# Today's Date
|
| 17 |
+
DATE = datetime.now().strftime("%d %b, %Y")
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
logging.basicConfig(level=logging.INFO)
|
| 21 |
+
|
| 22 |
+
app = FastAPI()
|
| 23 |
+
CORS_ALLOWED_ORIGINS = os.getenv("ALLOWED_ORIGINS", ",").split(",")
|
| 24 |
+
app.add_middleware(
|
| 25 |
+
CORSMiddleware,
|
| 26 |
+
allow_origins=CORS_ALLOWED_ORIGINS,
|
| 27 |
+
allow_credentials=True,
|
| 28 |
+
allow_methods=["*"],
|
| 29 |
+
allow_headers=["*"],
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Session management (in-memory for now)
|
| 33 |
+
sessions: Dict[str, Dict[str, Any]] = {}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@app.get("/health")
|
| 37 |
+
async def health_check():
|
| 38 |
+
return {"status": "ok"}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@app.post("/chat")
|
| 42 |
+
async def chat(request: Request):
|
| 43 |
+
data = await request.json()
|
| 44 |
+
message = data.get("message")
|
| 45 |
+
thread_id = data.get("thread_id")
|
| 46 |
+
|
| 47 |
+
async def event_generator():
|
| 48 |
+
async for event in invoke_agent(message, thread_id):
|
| 49 |
+
# Format the event as SSE (Server-Sent Events)
|
| 50 |
+
event_data = json.dumps(event)
|
| 51 |
+
yield f"data: {event_data}\n\n"
|
| 52 |
+
|
| 53 |
+
return StreamingResponse(
|
| 54 |
+
event_generator(),
|
| 55 |
+
media_type="text/plain",
|
| 56 |
+
headers={
|
| 57 |
+
"Cache-Control": "no-cache",
|
| 58 |
+
"Connection": "keep-alive",
|
| 59 |
+
"Content-Type": "text/event-stream",
|
| 60 |
+
},
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@app.post("/abort")
|
| 65 |
+
async def abort(request: Request):
|
| 66 |
+
data = await request.json()
|
| 67 |
+
session_id = data.get("session_id")
|
| 68 |
+
if session_id in sessions:
|
| 69 |
+
scraper = sessions[session_id]["scraper"]
|
| 70 |
+
await scraper.close()
|
| 71 |
+
del sessions[session_id]
|
| 72 |
+
return {"status": "aborted"}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
logger.info("Starting KnowledgeNet server...")
|
| 77 |
+
import uvicorn
|
| 78 |
+
|
| 79 |
+
uvicorn.run(app, host="127.0.0.1", port=5000)
|
langgraph_backend/tools_tools.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.tools import tool
|
| 2 |
+
|
| 3 |
+
@tool
|
| 4 |
+
def calc(a: int, b: int) -> int:
|
| 5 |
+
"""
|
| 6 |
+
Takes in two integers and returns their integer sum.
|
| 7 |
+
"""
|
| 8 |
+
return str(a + b)
|