File size: 11,107 Bytes
846e6fc b256f32 178f0c6 846e6fc b256f32 846e6fc f30ae2e 846e6fc e4bbbc2 846e6fc b256f32 8b11159 b256f32 8b11159 b256f32 8b11159 178f0c6 b256f32 8b11159 |
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 |
# --- FastAPI imports ---
from fastapi import FastAPI, Request, Query, File, UploadFile, Form
from fastapi.responses import JSONResponse
import shutil
# Add interactive loop for user input with Ctrl+C to break
app = FastAPI()
import os
import json
import tempfile
from typing import TypedDict, Annotated, List, Dict, Any
from typing import Literal, Tuple
import operator
from pydantic import BaseModel
from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage, ToolMessage, AIMessage
from langchain.tools import BaseTool, StructuredTool, tool
from langgraph.graph import StateGraph, END
from langchain_mistralai import ChatMistralAI
from langchain_groq import ChatGroq
from langchain_google_genai import ChatGoogleGenerativeAI
from langgraph.checkpoint.memory import InMemorySaver
import requests
import base64
os.environ["GOOGLE_API_KEY"] = "AIzaSyD2DMFgcL0kWTQYhii8wseSHY3BRGWSebk"
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
# llm_text = ChatGoogleGenerativeAI(model="gemini-2.0-flash")
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash")
vision_llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash")
# llm = ChatGoogleGenerativeAI(model="gemini-2.5-pro")
memory = InMemorySaver()
class AgentState(TypedDict):
messages: Annotated[list[AnyMessage], operator.add]
agent_type: str
user_task: str
class OneWordOutput(BaseModel):
choice: Literal["Conversiton", "Movement"]
def decide_which_agent_to_go_node(state: AgentState) -> AgentState:
"""This node does nothing but pass state to conditional routing."""
return state
def route_based_on_agent_type(state: AgentState) -> str:
"""This function is only used for conditional routing."""
user_task = state.get('user_task', '')
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash")
llm_structured = llm.with_structured_output(OneWordOutput)
decide_prompt = f"""
Your job is to decide which agent node to use based on the user task.
you have 2 options:
1. Conversiton: Use this if the user just wants to chat, brainstorm, or discuss ideas.
2. Movement: Use this agent for tasks that require physical movement or navigation.
"""
decide_message = [
SystemMessage(content=decide_prompt),
HumanMessage(content=user_task)
]
try:
response = llm_structured.invoke(decide_message)
agent_type = response.choice
print(f"Agent type decision: {agent_type}")
except Exception as e:
print(f"Error in agent decision: {e}")
# agent_type = "main_agent"
state['agent_type'] = agent_type
# β
Map model output to graph routing key
if agent_type == "Conversiton":
return "Conversiton"
elif agent_type == "Movement":
return "Movement"
def call_llm_Conversiton(state: AgentState):
messages = state['messages']
# if system_prompt_Conversiton:
# messages = [SystemMessage(content=system_prompt_Conversiton)] + messages
message = llm.invoke(messages)
return {"messages": [message]}
system_prompt_Movement = """
You are Movement agent. Your task is to assist with physical movement or navigation-related tasks.
You must output ONLY valid JSON (without markdown, without ```json, without explanations).
Rules:
- Do not include extra text or explanations.
- Do not wrap the JSON inside code blocks.
- Output pure JSON only.
Here are valid examples:
{
"direction": "forward",
"4wheels": {
"FR": {"speed": 10, "Direction": "Forward"},
"FL": {"speed": 10, "Direction": "Forward"},
"BR": {"speed": 10, "Direction": "Forward"},
"BL": {"speed": 10, "Direction": "Forward"}
}
}
{
"direction": "left",
"4wheels": {
"FR": {"speed": 10, "Direction": "Forward"},
"FL": {"speed": 5, "Direction": "Forward"},
"BR": {"speed": 10, "Direction": "Forward"},
"BL": {"speed": 5, "Direction": "Forward"}
}
}
"""
def take_image_and_object():
url = "http://192.168.1.14:8080/photo.jpg"
r = requests.get(url)
with open("Taken_image.jpg", "wb") as f:
f.write(r.content)
def call_llm_Movement(state: AgentState):
# take_image_and_object()
file_path = "Taken_image.jpg"
base64_image = encode_image(file_path)
user_task = state.get('user_task', '')
messages = [
{"role": "system", "content": system_prompt_Movement},
{
"role": "user",
"content": [
{"type": "text", "text": user_task},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}},
],
}
]
message = vision_llm.invoke(messages)
return {"messages": [message]}
graph = StateGraph(AgentState)
graph.set_entry_point('decide_agent')
graph.add_node('Conversiton', call_llm_Conversiton)
graph.add_node('Movement', call_llm_Movement)
graph.add_node('decide_agent', decide_which_agent_to_go_node)
graph.add_conditional_edges(
'decide_agent',
route_based_on_agent_type,
{
'Conversiton': 'Conversiton',
'Movement': 'Movement'
}
)
graph.add_edge('Conversiton', END)
graph.add_edge('Movement', END)
compiled_graph = graph.compile(checkpointer=memory)
# compiled_graph.get_graph().draw_mermaid_png(output_file_path=r"Newgraph.png")
def query_agent_with_planning(message: str, thread_id: str = "default") -> str:
"""
Run the compiled agent graph with the given user message.
Handles both Conversiton and Movement flows.
"""
print(f"\nπ― TASK RECEIVED: {message}")
print("=" * 50)
# Initial state for the graph
initial_state = {
"messages": [HumanMessage(content=message)],
"user_task": message, # Save user input to state['user_task']
"agent_type": "",
}
config = {
"configurable": {"thread_id": thread_id},
"recursion_limit": 100
}
final_response = ""
try:
print("π RUNNING AGENT GRAPH...")
printed_messages = set()
for event in compiled_graph.stream(initial_state, config):
for node_name, node_output in event.items():
print(f"\nπ Executing Node: {node_name}")
if "messages" in node_output:
for msg in node_output["messages"]:
if hasattr(msg, "content") and msg.content not in printed_messages:
# Try to parse msg.content as JSON
try:
json_obj = json.loads(msg.content)
print(json.dumps(json_obj, indent=2))
final_response += json.dumps(json_obj) + "\n"
except Exception:
print(f"π {msg.content}")
final_response += msg.content + "\n"
printed_messages.add(msg.content)
# Show agent type decision
if "agent_type" in node_output and node_output["agent_type"]:
print(f"π€ Agent Selected: {node_output['agent_type']}")
except Exception as e:
error_msg = f"β Execution Error: {str(e)}"
print(error_msg)
final_response += error_msg
return final_response.strip()
# Accept user input as a query parameter (GET or POST)
import re
import asyncio
def extract_json_from_response(response: str):
# Try to find the first JSON object in the response string
match = re.search(r'(\{[\s\S]*\})', response)
if match:
try:
return json.loads(match.group(1))
except Exception:
return None
return None
@app.get("/ask")
async def ask(user_input: str = Query(...)):
if not user_input.strip():
return JSONResponse(content={"error": "user_input is required"}, status_code=400)
loop = asyncio.get_event_loop()
# response = await loop.run_in_executor(None, query_agent_with_planning, user_input)
try:
response = await loop.run_in_executor(None, query_agent_with_planning, user_input)
except asyncio.CancelledError:
return JSONResponse(content={"error": "Request was cancelled"}, status_code=499)
json_obj = extract_json_from_response(response)
if json_obj:
return JSONResponse(content=json_obj)
return JSONResponse(content={"error": "No valid JSON found", "raw": response}, status_code=422)
@app.post("/ask_image")
async def ask_image(user_input: str = Form(...), image: UploadFile = File(...)):
if not user_input.strip():
return JSONResponse(content={"error": "user_input is required"}, status_code=400)
# Save uploaded image in a safe temporary directory
tmp_dir = tempfile.gettempdir()
image_path = os.path.join(tmp_dir, "Taken_image.jpg")
with open(image_path, "wb") as buffer:
shutil.copyfileobj(image.file, buffer)
# Now call the agent as usual
loop = asyncio.get_event_loop()
try:
response = await loop.run_in_executor(None, query_agent_with_planning, user_input)
except asyncio.CancelledError:
return JSONResponse(content={"error": "Request was cancelled"}, status_code=499)
json_obj = extract_json_from_response(response)
if json_obj:
return JSONResponse(content=json_obj)
return JSONResponse(content={"error": "No valid JSON found", "raw": response}, status_code=422)
@app.post("/query")
async def query(user_input: str = Form(...), image: UploadFile = File(None)):
"""
General endpoint:
- If only text is provided -> behaves like /ask
- If text + image is provided -> behaves like /ask_image
"""
if not user_input.strip():
return JSONResponse(content={"error": "user_input is required"}, status_code=400)
loop = asyncio.get_event_loop()
# Case 1: text only -> call ask logic
if image is None:
try:
response = await loop.run_in_executor(None, query_agent_with_planning, user_input)
except asyncio.CancelledError:
return JSONResponse(content={"error": "Request was cancelled"}, status_code=499)
json_obj = extract_json_from_response(response)
if json_obj:
return JSONResponse(content=json_obj)
return JSONResponse(content={"error": "No valid JSON found", "raw": response}, status_code=422)
# Case 2: text + image -> call ask_image logic
tmp_dir = tempfile.gettempdir()
image_path = os.path.join(tmp_dir, "Taken_image.jpg")
with open(image_path, "wb") as buffer:
shutil.copyfileobj(image.file, buffer)
try:
response = await loop.run_in_executor(None, query_agent_with_planning, user_input)
except asyncio.CancelledError:
return JSONResponse(content={"error": "Request was cancelled"}, status_code=499)
json_obj = extract_json_from_response(response)
if json_obj:
return JSONResponse(content=json_obj)
return JSONResponse(content={"error": "No valid JSON found", "raw": response}, status_code=422) |