updated and integrated backedn apis

This commit is contained in:
OwusuBlessing
2025-08-15 17:33:43 +01:00
parent bab442e955
commit 093c212928
17 changed files with 509 additions and 123 deletions
+32 -78
View File
@@ -1,90 +1,44 @@
import os
import json
import asyncio
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
from src.prompts.templates.flght_prompt import flight_prompt
from src.config.llm_config import LlmConfig
from config import Config
from src.components.data_extraction.weather_data import DroneWeatherDataExtractor
from logger import logger
# terminal_chat.py
from src.llm.orchestrator import DroneBot, Message # Adjust import path as needed
def terminal_chat():
print("🚁 DroneBot Terminal Chat")
print("Type 'exit' to quit.\n")
class DroneAssessmentAgent:
def __init__(self):
self.llm = ChatOpenAI(
api_key=Config.OPENAI_API_KEY,
model=LlmConfig.openai.models.gpt_4o,
temperature=0.3
)
self.weather_extractor = DroneWeatherDataExtractor()
# Initial conversation history
history = []
async def run(self, booking_form: str) -> dict:
"""
Run the drone environmental & safety assessment agent.
# Initialize the bot
customer_metadata = {
"customer_name": "John Doe",
"customer_email": "john.doe@example.com",
"customer_phone": "+1-555-0123",
"user_id": "12345"
}
bot = DroneBot(history=[], use_openai_as_fallback=True, customer_metadata=customer_metadata)
Args:
booking_form (str): Structured booking form input
# Get initial user input
while True:
user_input = input("👤 You: ")
if user_input.lower() in ("exit", "quit"):
print("👋 Exiting DroneBot. Goodbye!")
break
Returns:
dict: AI-generated structured output
"""
logger.info("Starting DroneAssessmentAgent run...")
# Add user message to history
history.append(Message(role="human", content=user_input))
try:
# Step 1: Fetch weather data
weather_data = await self.weather_extractor.extract_booking_weather_data(booking_form)
booking_form_text = json.dumps(booking_form)
# Update bot's history
bot.history = history
# Step 2: Generate prompt
prompt = flight_prompt(booking_form_text, weather_data)
messages = [
SystemMessage(content=prompt),
HumanMessage(content=booking_form_text)
]
# Get bot response
response = bot.chat(user_input)
# Step 3: Invoke LLM
logger.debug("Sending prompt to LLM...")
response = self.llm.invoke(messages)
# Add bot response to history
history.append(Message(role="ai", content=response["final_message"]))
if hasattr(response, "content"):
response_text = response.content.strip()
logger.info("Received LLM response.")
logger.debug(f"LLM Raw Output (first 300 chars):\n{response_text[:300]}")
# Extract JSON block
start_idx = response_text.find('{')
end_idx = response_text.rfind('}') + 1
if start_idx == -1 or end_idx == -1:
raise ValueError("No JSON object found in output")
json_str = response_text[start_idx:end_idx]
return json.loads(json_str)
else:
raise ValueError("LLM returned no usable content")
except Exception as e:
logger.exception("Error in DroneAssessmentAgent")
return {
"error": str(e),
"raw_response": response.content if 'response' in locals() and hasattr(response, "content") else None
}
async def main():
"""Async main function to test the drone assessment agent."""
from test2 import booking_form_input
logger.info("Launching DroneAssessmentAgent from main()...")
agent = DroneAssessmentAgent()
result = await agent.run(booking_form_input)
logger.info("Drone assessment completed.")
logger.debug("Final structured output:")
logger.debug(json.dumps(result, indent=2))
# Print bot response
print(f"🤖 DroneBot: {response['final_message']}\n")
if __name__ == "__main__":
asyncio.run(main())
terminal_chat()