Spaces:
Sleeping
Sleeping
Commit ·
1ef3cc9
1
Parent(s): cdf90a8
Add application file
Browse files- Dockerfile +18 -0
- app.log +0 -0
- app.py +1893 -0
- chatbot/__pycache__/chatbot_agent.cpython-312.pyc +0 -0
- chatbot/chatbot_agent.py +13 -0
- config/__pycache__/agent_patch.cpython-312.pyc +0 -0
- config/__pycache__/chabot_config.cpython-312.pyc +0 -0
- config/chabot_config.py +38 -0
- data.docx +0 -0
- guardrails/__pycache__/guardrails_input_function.cpython-312.pyc +0 -0
- guardrails/__pycache__/input_guardrails.cpython-312.pyc +0 -0
- guardrails/guardrails_input_function.py +44 -0
- guardrails/input_guardrails.py +28 -0
- instructions/__pycache__/chatbot_instructions.cpython-312.pyc +0 -0
- instructions/chatbot_instructions.py +539 -0
- main.py +238 -0
- requirements.txt +9 -0
- schema/__pycache__/chatbot_schema.cpython-312.pyc +0 -0
- schema/chatbot_schema.py +5 -0
- serviceAccount.json +13 -0
- sessions/__init__.py +1 -0
- sessions/__pycache__/__init__.cpython-312.pyc +0 -0
- sessions/__pycache__/session_manager.cpython-312.pyc +0 -0
- sessions/session_manager.py +181 -0
- tools/README.md +169 -0
- tools/__init__.py +1 -0
- tools/__pycache__/__init__.cpython-312.pyc +0 -0
- tools/__pycache__/document_reader_tool.cpython-312.pyc +0 -0
- tools/__pycache__/firebase_config.cpython-312.pyc +0 -0
- tools/document_reader_tool.py +212 -0
- tools/example_usage.py +53 -0
- tools/firebase_config.py +27 -0
Dockerfile
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Base image
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Set work directory
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
|
| 7 |
+
# Install dependencies
|
| 8 |
+
COPY requirements.txt .
|
| 9 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 10 |
+
|
| 11 |
+
# Copy project files
|
| 12 |
+
COPY . .
|
| 13 |
+
|
| 14 |
+
# Expose the port Hugging Face expects
|
| 15 |
+
EXPOSE 7860
|
| 16 |
+
|
| 17 |
+
# Command to run FastAPI with uvicorn
|
| 18 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app.py
ADDED
|
@@ -0,0 +1,1893 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# """
|
| 2 |
+
# FastAPI application for Launchlabs Chatbot API
|
| 3 |
+
# Provides /chat and /chat-stream endpoints with rate limiting, CORS, and error handling
|
| 4 |
+
# Updated with language context support
|
| 5 |
+
# """
|
| 6 |
+
# import os
|
| 7 |
+
# import logging
|
| 8 |
+
# import time
|
| 9 |
+
# from typing import Optional
|
| 10 |
+
# from collections import defaultdict
|
| 11 |
+
# import resend
|
| 12 |
+
|
| 13 |
+
# from fastapi import FastAPI, Request, HTTPException, status, Depends, Header
|
| 14 |
+
# from fastapi.responses import StreamingResponse, JSONResponse
|
| 15 |
+
# from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
+
# from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 17 |
+
# from pydantic import BaseModel
|
| 18 |
+
# from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 19 |
+
# from slowapi.util import get_remote_address
|
| 20 |
+
# from slowapi.errors import RateLimitExceeded
|
| 21 |
+
# from slowapi.middleware import SlowAPIMiddleware
|
| 22 |
+
# from dotenv import load_dotenv
|
| 23 |
+
|
| 24 |
+
# from agents import Runner, RunContextWrapper
|
| 25 |
+
# from agents.exceptions import InputGuardrailTripwireTriggered
|
| 26 |
+
# from openai.types.responses import ResponseTextDeltaEvent
|
| 27 |
+
# from chatbot.chatbot_agent import launchlabs_assistant
|
| 28 |
+
# from sessions.session_manager import session_manager
|
| 29 |
+
|
| 30 |
+
# # Load environment variables
|
| 31 |
+
# load_dotenv()
|
| 32 |
+
|
| 33 |
+
# # Configure Resend
|
| 34 |
+
# resend.api_key = os.getenv("RESEND_API_KEY")
|
| 35 |
+
|
| 36 |
+
# # Configure logging
|
| 37 |
+
# logging.basicConfig(
|
| 38 |
+
# level=logging.INFO,
|
| 39 |
+
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 40 |
+
# handlers=[
|
| 41 |
+
# logging.FileHandler('app.log'),
|
| 42 |
+
# logging.StreamHandler()
|
| 43 |
+
# ]
|
| 44 |
+
# )
|
| 45 |
+
# logger = logging.getLogger(__name__)
|
| 46 |
+
|
| 47 |
+
# # Initialize rate limiter with enhanced security
|
| 48 |
+
# limiter = Limiter(key_func=get_remote_address, default_limits=["100/day", "20/hour", "3/minute"])
|
| 49 |
+
|
| 50 |
+
# # Create FastAPI app
|
| 51 |
+
# app = FastAPI(
|
| 52 |
+
# title="Launchlabs Chatbot API",
|
| 53 |
+
# description="AI-powered chatbot API for Launchlabs services",
|
| 54 |
+
# version="1.0.0"
|
| 55 |
+
# )
|
| 56 |
+
|
| 57 |
+
# # Add rate limiter middleware
|
| 58 |
+
# app.state.limiter = limiter
|
| 59 |
+
# app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 60 |
+
# app.add_middleware(SlowAPIMiddleware)
|
| 61 |
+
|
| 62 |
+
# # Configure CORS from environment variable
|
| 63 |
+
# allowed_origins = os.getenv("ALLOWED_ORIGINS", "").split(",")
|
| 64 |
+
# allowed_origins = [origin.strip() for origin in allowed_origins if origin.strip()]
|
| 65 |
+
|
| 66 |
+
# if allowed_origins:
|
| 67 |
+
# app.add_middleware(
|
| 68 |
+
# CORSMiddleware,
|
| 69 |
+
# allow_origins=["*"] + allowed_origins,
|
| 70 |
+
# allow_credentials=True,
|
| 71 |
+
# allow_methods=["*"],
|
| 72 |
+
# allow_headers=["*"],
|
| 73 |
+
# )
|
| 74 |
+
# logger.info(f"CORS enabled for origins: {allowed_origins}")
|
| 75 |
+
# else:
|
| 76 |
+
# logger.warning("No ALLOWED_ORIGINS set in .env - CORS disabled")
|
| 77 |
+
|
| 78 |
+
# # Security setup
|
| 79 |
+
# security = HTTPBearer()
|
| 80 |
+
|
| 81 |
+
# # Enhanced rate limiting dictionaries
|
| 82 |
+
# request_counts = defaultdict(list) # Track requests per IP
|
| 83 |
+
# TICKET_RATE_LIMIT = 5 # Max 5 tickets per hour per IP
|
| 84 |
+
# TICKET_TIME_WINDOW = 3600 # 1 hour in seconds
|
| 85 |
+
# MEETING_RATE_LIMIT = 3 # Max 3 meetings per hour per IP
|
| 86 |
+
# MEETING_TIME_WINDOW = 3600 # 1 hour in seconds
|
| 87 |
+
|
| 88 |
+
# # Request/Response models
|
| 89 |
+
# class ChatRequest(BaseModel):
|
| 90 |
+
# message: str
|
| 91 |
+
# language: Optional[str] = "english" # Default to English if not specified
|
| 92 |
+
# session_id: Optional[str] = None # Session ID for chat history
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# class ChatResponse(BaseModel):
|
| 96 |
+
# response: str
|
| 97 |
+
# success: bool
|
| 98 |
+
# session_id: str # Include session ID in response
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# class ErrorResponse(BaseModel):
|
| 102 |
+
# error: str
|
| 103 |
+
# detail: Optional[str] = None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# class TicketRequest(BaseModel):
|
| 107 |
+
# name: str
|
| 108 |
+
# email: str
|
| 109 |
+
# message: str
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# class TicketResponse(BaseModel):
|
| 113 |
+
# success: bool
|
| 114 |
+
# message: str
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# class MeetingRequest(BaseModel):
|
| 118 |
+
# name: str
|
| 119 |
+
# email: str
|
| 120 |
+
# date: str # ISO format date string
|
| 121 |
+
# time: str # Time in HH:MM format
|
| 122 |
+
# timezone: str # Timezone identifier
|
| 123 |
+
# duration: int # Duration in minutes
|
| 124 |
+
# topic: str # Meeting topic/title
|
| 125 |
+
# attendees: list[str] # List of attendee emails
|
| 126 |
+
# description: Optional[str] = None # Optional meeting description
|
| 127 |
+
# location: Optional[str] = "Google Meet" # Meeting location/platform
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# class MeetingResponse(BaseModel):
|
| 131 |
+
# success: bool
|
| 132 |
+
# message: str
|
| 133 |
+
# meeting_id: Optional[str] = None # Unique identifier for the meeting
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# # Security dependency for API key validation
|
| 137 |
+
# async def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 138 |
+
# """Verify API key for protected endpoints"""
|
| 139 |
+
# # In production, you would check against a database of valid keys
|
| 140 |
+
# # For now, we'll use an environment variable
|
| 141 |
+
# expected_key = os.getenv("API_KEY")
|
| 142 |
+
# if not expected_key or credentials.credentials != expected_key:
|
| 143 |
+
# raise HTTPException(
|
| 144 |
+
# status_code=status.HTTP_401_UNAUTHORIZED,
|
| 145 |
+
# detail="Invalid or missing API key",
|
| 146 |
+
# )
|
| 147 |
+
# return credentials.credentials
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# def is_ticket_rate_limited(ip_address: str) -> bool:
|
| 151 |
+
# """Check if an IP address has exceeded ticket submission rate limits"""
|
| 152 |
+
# current_time = time.time()
|
| 153 |
+
# # Clean old requests outside the time window
|
| 154 |
+
# request_counts[ip_address] = [
|
| 155 |
+
# req_time for req_time in request_counts[ip_address]
|
| 156 |
+
# if current_time - req_time < TICKET_TIME_WINDOW
|
| 157 |
+
# ]
|
| 158 |
+
|
| 159 |
+
# # Check if limit exceeded
|
| 160 |
+
# if len(request_counts[ip_address]) >= TICKET_RATE_LIMIT:
|
| 161 |
+
# return True
|
| 162 |
+
|
| 163 |
+
# # Add current request
|
| 164 |
+
# request_counts[ip_address].append(current_time)
|
| 165 |
+
# return False
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# def is_meeting_rate_limited(ip_address: str) -> bool:
|
| 169 |
+
# """Check if an IP address has exceeded meeting scheduling rate limits"""
|
| 170 |
+
# current_time = time.time()
|
| 171 |
+
# # Clean old requests outside the time window
|
| 172 |
+
# request_counts[ip_address] = [
|
| 173 |
+
# req_time for req_time in request_counts[ip_address]
|
| 174 |
+
# if current_time - req_time < MEETING_TIME_WINDOW
|
| 175 |
+
# ]
|
| 176 |
+
|
| 177 |
+
# # Check if limit exceeded
|
| 178 |
+
# if len(request_counts[ip_address]) >= MEETING_RATE_LIMIT:
|
| 179 |
+
# return True
|
| 180 |
+
|
| 181 |
+
# # Add current request
|
| 182 |
+
# request_counts[ip_address].append(current_time)
|
| 183 |
+
# return False
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# def query_launchlabs_bot_stream(user_message: str, language: str = "english", session_id: Optional[str] = None):
|
| 187 |
+
# """
|
| 188 |
+
# Query the Launchlabs bot with streaming - returns async generator.
|
| 189 |
+
# Now includes language context and session history.
|
| 190 |
+
# Implements fallback to non-streaming when streaming fails (e.g., with Gemini models).
|
| 191 |
+
# """
|
| 192 |
+
# logger.info(f"AGENT STREAM CALL: query_launchlabs_bot_stream called with message='{user_message}', language='{language}', session_id='{session_id}'")
|
| 193 |
+
|
| 194 |
+
# # Get session history if session_id is provided
|
| 195 |
+
# history = []
|
| 196 |
+
# if session_id:
|
| 197 |
+
# history = session_manager.get_session_history(session_id)
|
| 198 |
+
# logger.info(f"Retrieved {len(history)} history messages for session {session_id}")
|
| 199 |
+
|
| 200 |
+
# try:
|
| 201 |
+
# # Create context with language preference and history
|
| 202 |
+
# context_data = {"language": language}
|
| 203 |
+
# if history:
|
| 204 |
+
# context_data["history"] = history
|
| 205 |
+
|
| 206 |
+
# ctx = RunContextWrapper(context=context_data)
|
| 207 |
+
|
| 208 |
+
# result = Runner.run_streamed(
|
| 209 |
+
# launchlabs_assistant,
|
| 210 |
+
# input=user_message,
|
| 211 |
+
# context=ctx.context
|
| 212 |
+
# )
|
| 213 |
+
|
| 214 |
+
# async def generate_stream():
|
| 215 |
+
# try:
|
| 216 |
+
# previous = ""
|
| 217 |
+
# has_streamed = True
|
| 218 |
+
|
| 219 |
+
# try:
|
| 220 |
+
# # Attempt streaming with error handling for each event
|
| 221 |
+
# async for event in result.stream_events():
|
| 222 |
+
# try:
|
| 223 |
+
# if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
|
| 224 |
+
# delta = event.data.delta or ""
|
| 225 |
+
|
| 226 |
+
# # ---- Spacing Fix ----
|
| 227 |
+
# if (
|
| 228 |
+
# previous
|
| 229 |
+
# and not previous.endswith((" ", "\n"))
|
| 230 |
+
# and not delta.startswith((" ", ".", ",", "?", "!", ":", ";"))
|
| 231 |
+
# ):
|
| 232 |
+
# delta = " " + delta
|
| 233 |
+
|
| 234 |
+
# previous = delta
|
| 235 |
+
# # ---- End Fix ----
|
| 236 |
+
|
| 237 |
+
# yield f"data: {delta}\n\n"
|
| 238 |
+
# has_streamed = True
|
| 239 |
+
# except Exception as event_error:
|
| 240 |
+
# # Handle individual event errors (e.g., missing logprobs field)
|
| 241 |
+
# logger.warning(f"Event processing error: {event_error}")
|
| 242 |
+
# continue
|
| 243 |
+
|
| 244 |
+
# yield "data: [DONE]\n\n"
|
| 245 |
+
# logger.info("AGENT STREAM RESULT: query_launchlabs_bot_stream completed successfully")
|
| 246 |
+
|
| 247 |
+
# except Exception as stream_error:
|
| 248 |
+
# # Fallback to non-streaming if streaming fails
|
| 249 |
+
# logger.warning(f"Streaming failed, falling back to non-streaming: {stream_error}")
|
| 250 |
+
|
| 251 |
+
# if not has_streamed:
|
| 252 |
+
# # Get final output using the streaming result's final_output property
|
| 253 |
+
# # Wait for the stream to complete to get final output
|
| 254 |
+
# try:
|
| 255 |
+
# # Use the non-streaming API as fallback
|
| 256 |
+
# fallback_response = await Runner.run(
|
| 257 |
+
# launchlabs_assistant,
|
| 258 |
+
# input=user_message,
|
| 259 |
+
# context=ctx.context
|
| 260 |
+
# )
|
| 261 |
+
|
| 262 |
+
# if hasattr(fallback_response, 'final_output'):
|
| 263 |
+
# final_output = fallback_response.final_output
|
| 264 |
+
# else:
|
| 265 |
+
# final_output = fallback_response
|
| 266 |
+
|
| 267 |
+
# if hasattr(final_output, 'content'):
|
| 268 |
+
# response_text = final_output.content
|
| 269 |
+
# elif isinstance(final_output, str):
|
| 270 |
+
# response_text = final_output
|
| 271 |
+
# else:
|
| 272 |
+
# response_text = str(final_output)
|
| 273 |
+
|
| 274 |
+
# yield f"data: {response_text}\n\n"
|
| 275 |
+
# yield "data: [DONE]\n\n"
|
| 276 |
+
# logger.info("AGENT STREAM RESULT: query_launchlabs_bot_stream fallback completed successfully")
|
| 277 |
+
# except Exception as fallback_error:
|
| 278 |
+
# logger.error(f"Fallback also failed: {fallback_error}", exc_info=True)
|
| 279 |
+
# yield f"data: [ERROR] Unable to complete request.\n\n"
|
| 280 |
+
# else:
|
| 281 |
+
# # Already streamed some content, just end gracefully
|
| 282 |
+
# yield "data: [DONE]\n\n"
|
| 283 |
+
|
| 284 |
+
# except InputGuardrailTripwireTriggered as e:
|
| 285 |
+
# logger.warning(f"Guardrail blocked query during streaming: {e}")
|
| 286 |
+
# yield f"data: [ERROR] Query was blocked by content guardrail.\n\n"
|
| 287 |
+
|
| 288 |
+
# except Exception as e:
|
| 289 |
+
# logger.error(f"Streaming error: {e}", exc_info=True)
|
| 290 |
+
# yield f"data: [ERROR] {str(e)}\n\n"
|
| 291 |
+
|
| 292 |
+
# return generate_stream()
|
| 293 |
+
|
| 294 |
+
# except Exception as e:
|
| 295 |
+
# logger.error(f"Error setting up stream: {e}", exc_info=True)
|
| 296 |
+
|
| 297 |
+
# async def error_stream():
|
| 298 |
+
# yield f"data: [ERROR] Failed to initialize stream.\n\n"
|
| 299 |
+
|
| 300 |
+
# return error_stream()
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
# async def query_launchlabs_bot(user_message: str, language: str = "english", session_id: Optional[str] = None):
|
| 304 |
+
# """
|
| 305 |
+
# Query the Launchlabs bot - returns complete response.
|
| 306 |
+
# Now includes language context and session history.
|
| 307 |
+
# """
|
| 308 |
+
# logger.info(f"AGENT CALL: query_launchlabs_bot called with message='{user_message}', language='{language}', session_id='{session_id}'")
|
| 309 |
+
|
| 310 |
+
# # Get session history if session_id is provided
|
| 311 |
+
# history = []
|
| 312 |
+
# if session_id:
|
| 313 |
+
# history = session_manager.get_session_history(session_id)
|
| 314 |
+
# logger.info(f"Retrieved {len(history)} history messages for session {session_id}")
|
| 315 |
+
|
| 316 |
+
# try:
|
| 317 |
+
# # Create context with language preference and history
|
| 318 |
+
# context_data = {"language": language}
|
| 319 |
+
# if history:
|
| 320 |
+
# context_data["history"] = history
|
| 321 |
+
|
| 322 |
+
# ctx = RunContextWrapper(context=context_data)
|
| 323 |
+
|
| 324 |
+
# response = await Runner.run(
|
| 325 |
+
# launchlabs_assistant,
|
| 326 |
+
# input=user_message,
|
| 327 |
+
# context=ctx.context
|
| 328 |
+
# )
|
| 329 |
+
# logger.info("AGENT RESULT: query_launchlabs_bot completed successfully")
|
| 330 |
+
# return response.final_output
|
| 331 |
+
|
| 332 |
+
# except InputGuardrailTripwireTriggered as e:
|
| 333 |
+
# logger.warning(f"Guardrail blocked query: {e}")
|
| 334 |
+
# raise HTTPException(
|
| 335 |
+
# status_code=status.HTTP_403_FORBIDDEN,
|
| 336 |
+
# detail="Query was blocked by content guardrail. Please ensure your query is related to Launchlabs services."
|
| 337 |
+
# )
|
| 338 |
+
# except Exception as e:
|
| 339 |
+
# logger.error(f"Error in query_launchlabs_bot: {e}", exc_info=True)
|
| 340 |
+
# raise HTTPException(
|
| 341 |
+
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 342 |
+
# detail="An internal error occurred while processing your request."
|
| 343 |
+
# )
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
# @app.get("/")
|
| 347 |
+
# async def root():
|
| 348 |
+
# return {"status": "ok", "service": "Launchlabs Chatbot API"}
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# @app.get("/health")
|
| 352 |
+
# async def health():
|
| 353 |
+
# return {"status": "healthy"}
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# @app.post("/session")
|
| 357 |
+
# async def create_session():
|
| 358 |
+
# """
|
| 359 |
+
# Create a new chat session
|
| 360 |
+
# Returns a session ID that can be used to maintain chat history
|
| 361 |
+
# """
|
| 362 |
+
# try:
|
| 363 |
+
# session_id = session_manager.create_session()
|
| 364 |
+
# logger.info(f"Created new session: {session_id}")
|
| 365 |
+
# return {"session_id": session_id, "message": "Session created successfully"}
|
| 366 |
+
# except Exception as e:
|
| 367 |
+
# logger.error(f"Error creating session: {e}", exc_info=True)
|
| 368 |
+
# raise HTTPException(
|
| 369 |
+
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 370 |
+
# detail="Failed to create session"
|
| 371 |
+
# )
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
# @app.post("/chat", response_model=ChatResponse)
|
| 375 |
+
# @limiter.limit("10/minute") # Limit to 10 requests per minute per IP
|
| 376 |
+
# async def chat(request: Request, chat_request: ChatRequest):
|
| 377 |
+
# """
|
| 378 |
+
# Standard chat endpoint with language support and session history.
|
| 379 |
+
# Accepts: {"message": "...", "language": "norwegian", "session_id": "optional-session-id"}
|
| 380 |
+
# """
|
| 381 |
+
# try:
|
| 382 |
+
# # Create or use existing session
|
| 383 |
+
# session_id = chat_request.session_id
|
| 384 |
+
# if not session_id:
|
| 385 |
+
# session_id = session_manager.create_session()
|
| 386 |
+
# logger.info(f"Created new session for chat: {session_id}")
|
| 387 |
+
|
| 388 |
+
# logger.info(
|
| 389 |
+
# f"Chat request from {get_remote_address(request)}: "
|
| 390 |
+
# f"language={chat_request.language}, message={chat_request.message[:50]}..., session_id={session_id}"
|
| 391 |
+
# )
|
| 392 |
+
|
| 393 |
+
# # Add user message to session history
|
| 394 |
+
# session_manager.add_message_to_history(session_id, "user", chat_request.message)
|
| 395 |
+
|
| 396 |
+
# # Pass language and session to the bot
|
| 397 |
+
# response = await query_launchlabs_bot(
|
| 398 |
+
# chat_request.message,
|
| 399 |
+
# language=chat_request.language,
|
| 400 |
+
# session_id=session_id
|
| 401 |
+
# )
|
| 402 |
+
|
| 403 |
+
# if hasattr(response, 'content'):
|
| 404 |
+
# response_text = response.content
|
| 405 |
+
# elif isinstance(response, str):
|
| 406 |
+
# response_text = response
|
| 407 |
+
# else:
|
| 408 |
+
# response_text = str(response)
|
| 409 |
+
|
| 410 |
+
# # Add bot response to session history
|
| 411 |
+
# session_manager.add_message_to_history(session_id, "assistant", response_text)
|
| 412 |
+
|
| 413 |
+
# logger.info(f"Chat response generated successfully in {chat_request.language} for session {session_id}")
|
| 414 |
+
|
| 415 |
+
# return ChatResponse(
|
| 416 |
+
# response=response_text,
|
| 417 |
+
# success=True,
|
| 418 |
+
# session_id=session_id
|
| 419 |
+
# )
|
| 420 |
+
|
| 421 |
+
# except HTTPException:
|
| 422 |
+
# raise
|
| 423 |
+
# except Exception as e:
|
| 424 |
+
# logger.error(f"Unexpected error in /chat: {e}", exc_info=True)
|
| 425 |
+
# raise HTTPException(
|
| 426 |
+
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 427 |
+
# detail="An internal error occurred while processing your request."
|
| 428 |
+
# )
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
# @app.post("/api/messages", response_model=ChatResponse)
|
| 432 |
+
# @limiter.limit("10/minute") # Same rate limit as /chat
|
| 433 |
+
# async def api_messages(request: Request, chat_request: ChatRequest):
|
| 434 |
+
# """
|
| 435 |
+
# Frontend-friendly chat endpoint at /api/messages.
|
| 436 |
+
# Exactly mirrors /chat logic for session/history support.
|
| 437 |
+
# Expects: {"message": "...", "language": "english", "session_id": "optional"}
|
| 438 |
+
# """
|
| 439 |
+
# client_ip = get_remote_address(request)
|
| 440 |
+
# logger.info(f"API Messages request from {client_ip}: message='{chat_request.message[:50]}...', lang='{chat_request.language}', session='{chat_request.session_id}'")
|
| 441 |
+
|
| 442 |
+
# try:
|
| 443 |
+
# # Create/use session (Firestore-backed)
|
| 444 |
+
# session_id = chat_request.session_id
|
| 445 |
+
# if not session_id:
|
| 446 |
+
# session_id = session_manager.create_session()
|
| 447 |
+
# logger.info(f"New session created for /api/messages: {session_id}")
|
| 448 |
+
|
| 449 |
+
# # Save user message to history
|
| 450 |
+
# session_manager.add_message_to_history(session_id, "user", chat_request.message)
|
| 451 |
+
|
| 452 |
+
# # Call your existing bot query function
|
| 453 |
+
# response = await query_launchlabs_bot(
|
| 454 |
+
# user_message=chat_request.message,
|
| 455 |
+
# language=chat_request.language,
|
| 456 |
+
# session_id=session_id
|
| 457 |
+
# )
|
| 458 |
+
|
| 459 |
+
# # Extract response text
|
| 460 |
+
# response_text = (
|
| 461 |
+
# response.content if hasattr(response, 'content')
|
| 462 |
+
# else response if isinstance(response, str)
|
| 463 |
+
# else str(response)
|
| 464 |
+
# )
|
| 465 |
+
|
| 466 |
+
# # Save AI response to history
|
| 467 |
+
# session_manager.add_message_to_history(session_id, "assistant", response_text)
|
| 468 |
+
|
| 469 |
+
# logger.info(f"API Messages success: Response sent for session {session_id}")
|
| 470 |
+
|
| 471 |
+
# return ChatResponse(
|
| 472 |
+
# response=response_text,
|
| 473 |
+
# success=True,
|
| 474 |
+
# session_id=session_id
|
| 475 |
+
# )
|
| 476 |
+
|
| 477 |
+
# except InputGuardrailTripwireTriggered as e:
|
| 478 |
+
# logger.warning(f"Guardrail blocked /api/messages: {e}")
|
| 479 |
+
# raise HTTPException(
|
| 480 |
+
# status_code=403,
|
| 481 |
+
# detail="Query blocked – please ask about Launchlabs services."
|
| 482 |
+
# )
|
| 483 |
+
# except Exception as e:
|
| 484 |
+
# logger.error(f"Error in /api/messages: {e}", exc_info=True)
|
| 485 |
+
# raise HTTPException(
|
| 486 |
+
# status_code=500,
|
| 487 |
+
# detail="Internal error – try again."
|
| 488 |
+
# )
|
| 489 |
+
|
| 490 |
+
# @app.post("/chat-stream")
|
| 491 |
+
# @limiter.limit("10/minute") # Limit to 10 requests per minute per IP
|
| 492 |
+
# async def chat_stream(request: Request, chat_request: ChatRequest):
|
| 493 |
+
# """
|
| 494 |
+
# Streaming chat endpoint with language support and session history.
|
| 495 |
+
# Accepts: {"message": "...", "language": "norwegian", "session_id": "optional-session-id"}
|
| 496 |
+
# """
|
| 497 |
+
# try:
|
| 498 |
+
# # Create or use existing session
|
| 499 |
+
# session_id = chat_request.session_id
|
| 500 |
+
# if not session_id:
|
| 501 |
+
# session_id = session_manager.create_session()
|
| 502 |
+
# logger.info(f"Created new session for streaming chat: {session_id}")
|
| 503 |
+
|
| 504 |
+
# logger.info(
|
| 505 |
+
# f"Stream request from {get_remote_address(request)}: "
|
| 506 |
+
# f"language={chat_request.language}, message={chat_request.message[:50]}..., session_id={session_id}"
|
| 507 |
+
# )
|
| 508 |
+
|
| 509 |
+
# # Add user message to session history
|
| 510 |
+
# session_manager.add_message_to_history(session_id, "user", chat_request.message)
|
| 511 |
+
|
| 512 |
+
# # Pass language and session to the streaming bot
|
| 513 |
+
# stream_generator = query_launchlabs_bot_stream(
|
| 514 |
+
# chat_request.message,
|
| 515 |
+
# language=chat_request.language,
|
| 516 |
+
# session_id=session_id
|
| 517 |
+
# )
|
| 518 |
+
|
| 519 |
+
# # Note: For streaming, we add the response to history after the stream completes
|
| 520 |
+
# # This would need to be handled in the frontend by making a separate call or
|
| 521 |
+
# # by modifying the stream generator to add the complete response to history
|
| 522 |
+
|
| 523 |
+
# return StreamingResponse(
|
| 524 |
+
# stream_generator,
|
| 525 |
+
# media_type="text/event-stream",
|
| 526 |
+
# headers={
|
| 527 |
+
# "Cache-Control": "no-cache",
|
| 528 |
+
# "Connection": "keep-alive",
|
| 529 |
+
# "X-Accel-Buffering": "no",
|
| 530 |
+
# "Session-ID": session_id # Include session ID in headers
|
| 531 |
+
# }
|
| 532 |
+
# )
|
| 533 |
+
|
| 534 |
+
# except HTTPException:
|
| 535 |
+
# raise
|
| 536 |
+
# except Exception as e:
|
| 537 |
+
# logger.error(f"Unexpected error in /chat-stream: {e}", exc_info=True)
|
| 538 |
+
# raise HTTPException(
|
| 539 |
+
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 540 |
+
# detail="An internal error occurred while processing your request."
|
| 541 |
+
# )
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
# @app.post("/ticket", response_model=TicketResponse)
|
| 545 |
+
# @limiter.limit("5/hour") # Limit to 5 tickets per hour per IP
|
| 546 |
+
# async def submit_ticket(request: Request, ticket_request: TicketRequest):
|
| 547 |
+
# """
|
| 548 |
+
# Submit a support ticket via email using Resend API.
|
| 549 |
+
# Accepts: {"name": "John Doe", "email": "john@example.com", "message": "Issue description"}
|
| 550 |
+
# """
|
| 551 |
+
# try:
|
| 552 |
+
# client_ip = get_remote_address(request)
|
| 553 |
+
# logger.info(f"Ticket submission request from {ticket_request.name} ({ticket_request.email}) - IP: {client_ip}")
|
| 554 |
+
|
| 555 |
+
# # Additional rate limiting for tickets
|
| 556 |
+
# if is_ticket_rate_limited(client_ip):
|
| 557 |
+
# logger.warning(f"Rate limit exceeded for ticket submission from IP: {client_ip}")
|
| 558 |
+
# raise HTTPException(
|
| 559 |
+
# status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
| 560 |
+
# detail="Too many ticket submissions. Please try again later."
|
| 561 |
+
# )
|
| 562 |
+
|
| 563 |
+
# # Get admin email from environment variables or use a default
|
| 564 |
+
# admin_email = os.getenv("ADMIN_EMAIL", "admin@yourcompany.com")
|
| 565 |
+
|
| 566 |
+
# # Use a verified sender email (you need to verify this in your Resend account)
|
| 567 |
+
# # For testing purposes, you can use your Resend account's verified domain
|
| 568 |
+
# sender_email = os.getenv("SENDER_EMAIL", "onboarding@resend.dev")
|
| 569 |
+
|
| 570 |
+
# # Prepare the email using Resend
|
| 571 |
+
# params = {
|
| 572 |
+
# "from": sender_email,
|
| 573 |
+
# "to": [admin_email],
|
| 574 |
+
# "subject": f"Support Ticket from {ticket_request.name}",
|
| 575 |
+
# "html": f"""
|
| 576 |
+
# <p>Hello Admin,</p>
|
| 577 |
+
# <p>A new support ticket has been submitted:</p>
|
| 578 |
+
# <p><strong>Name:</strong> {ticket_request.name}</p>
|
| 579 |
+
# <p><strong>Email:</strong> {ticket_request.email}</p>
|
| 580 |
+
# <p><strong>Message:</strong></p>
|
| 581 |
+
# <p>{ticket_request.message}</p>
|
| 582 |
+
# <p><strong>IP Address:</strong> {client_ip}</p>
|
| 583 |
+
# <br>
|
| 584 |
+
# <p>Best regards,<br>Launchlabs Support Team</p>
|
| 585 |
+
# """
|
| 586 |
+
# }
|
| 587 |
+
|
| 588 |
+
# # Send the email
|
| 589 |
+
# email = resend.Emails.send(params)
|
| 590 |
+
|
| 591 |
+
# logger.info(f"Ticket submitted successfully by {ticket_request.name} from IP: {client_ip}")
|
| 592 |
+
|
| 593 |
+
# return TicketResponse(
|
| 594 |
+
# success=True,
|
| 595 |
+
# message="Ticket submitted successfully. We'll get back to you soon."
|
| 596 |
+
# )
|
| 597 |
+
|
| 598 |
+
# except HTTPException:
|
| 599 |
+
# raise
|
| 600 |
+
# except Exception as e:
|
| 601 |
+
# logger.error(f"Error submitting ticket: {e}", exc_info=True)
|
| 602 |
+
# raise HTTPException(
|
| 603 |
+
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 604 |
+
# detail="Failed to submit ticket. Please try again later."
|
| 605 |
+
# )
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
# @app.post("/schedule-meeting", response_model=MeetingResponse)
|
| 609 |
+
# @limiter.limit("3/hour") # Limit to 3 meetings per hour per IP
|
| 610 |
+
# async def schedule_meeting(request: Request, meeting_request: MeetingRequest):
|
| 611 |
+
# """
|
| 612 |
+
# Schedule a meeting and send email invitations using Resend API.
|
| 613 |
+
# Accepts meeting details and sends professional email invitations to organizer and attendees.
|
| 614 |
+
# """
|
| 615 |
+
# try:
|
| 616 |
+
# client_ip = get_remote_address(request)
|
| 617 |
+
# logger.info(f"Meeting scheduling request from {meeting_request.name} ({meeting_request.email}) - IP: {client_ip}")
|
| 618 |
+
|
| 619 |
+
# # Additional rate limiting for meetings
|
| 620 |
+
# if is_meeting_rate_limited(client_ip):
|
| 621 |
+
# logger.warning(f"Rate limit exceeded for meeting scheduling from IP: {client_ip}")
|
| 622 |
+
# raise HTTPException(
|
| 623 |
+
# status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
| 624 |
+
# detail="Too many meeting requests. Please try again later."
|
| 625 |
+
# )
|
| 626 |
+
|
| 627 |
+
# # Generate a unique meeting ID
|
| 628 |
+
# meeting_id = f"mtg_{int(time.time())}"
|
| 629 |
+
|
| 630 |
+
# # Get admin email from environment variables or use a default
|
| 631 |
+
# admin_email = os.getenv("ADMIN_EMAIL", "admin@yourcompany.com")
|
| 632 |
+
|
| 633 |
+
# # Use a verified sender email (you need to verify this in your Resend account)
|
| 634 |
+
# sender_email = os.getenv("SENDER_EMAIL", "onboarding@resend.dev")
|
| 635 |
+
|
| 636 |
+
# # For Resend testing limitations, we can only send to the owner's email
|
| 637 |
+
# # In production, you would verify a domain and use that instead
|
| 638 |
+
# owner_email = os.getenv("ADMIN_EMAIL", "admin@yourcompany.com")
|
| 639 |
+
|
| 640 |
+
# # Format date and time for display
|
| 641 |
+
# formatted_datetime = f"{meeting_request.date} at {meeting_request.time} {meeting_request.timezone}"
|
| 642 |
+
|
| 643 |
+
# # Create calendar link (Google Calendar link example)
|
| 644 |
+
# calendar_link = f"https://calendar.google.com/calendar/render?action=TEMPLATE&text={meeting_request.topic}&dates={meeting_request.date.replace('-', '')}T{meeting_request.time.replace(':', '')}00Z/{meeting_request.date.replace('-', '')}T{meeting_request.time.replace(':', '')}00Z&details={meeting_request.description or 'Meeting scheduled via Launchlabs'}&location={meeting_request.location}"
|
| 645 |
+
|
| 646 |
+
# # Combine all attendees (organizer + additional attendees)
|
| 647 |
+
# # Validate and format email addresses
|
| 648 |
+
# all_attendees = [meeting_request.email]
|
| 649 |
+
|
| 650 |
+
# # Validate additional attendees - they must be valid email addresses
|
| 651 |
+
# for attendee in meeting_request.attendees:
|
| 652 |
+
# # Simple email validation
|
| 653 |
+
# if "@" in attendee and "." in attendee:
|
| 654 |
+
# all_attendees.append(attendee)
|
| 655 |
+
# else:
|
| 656 |
+
# # If not a valid email, skip or treat as name only
|
| 657 |
+
# logger.warning(f"Invalid email format for attendee: {attendee}. Skipping.")
|
| 658 |
+
|
| 659 |
+
# # Remove duplicates while preserving order
|
| 660 |
+
# seen = set()
|
| 661 |
+
# unique_attendees = []
|
| 662 |
+
# for email in all_attendees:
|
| 663 |
+
# if email not in seen:
|
| 664 |
+
# seen.add(email)
|
| 665 |
+
# unique_attendees.append(email)
|
| 666 |
+
# all_attendees = unique_attendees
|
| 667 |
+
|
| 668 |
+
# # Prepare the professional HTML email template
|
| 669 |
+
# html_template = f"""
|
| 670 |
+
# <!DOCTYPE html>
|
| 671 |
+
# <html>
|
| 672 |
+
# <head>
|
| 673 |
+
# <meta charset="UTF-8">
|
| 674 |
+
# <meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 675 |
+
# <title>Meeting Scheduled - {meeting_request.topic}</title>
|
| 676 |
+
# </head>
|
| 677 |
+
# <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
|
| 678 |
+
# <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
|
| 679 |
+
# <h1 style="margin: 0; font-size: 28px;">Meeting Confirmed!</h1>
|
| 680 |
+
# <p style="font-size: 18px; margin-top: 10px;">Your meeting has been successfully scheduled</p>
|
| 681 |
+
# </div>
|
| 682 |
+
|
| 683 |
+
# <div style="background-color: #ffffff; padding: 30px; border: 1px solid #eaeaea; border-top: none; border-radius: 0 0 10px 10px;">
|
| 684 |
+
# <h2 style="color: #333;">Meeting Details</h2>
|
| 685 |
+
|
| 686 |
+
# <div style="background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
|
| 687 |
+
# <table style="width: 100%; border-collapse: collapse;">
|
| 688 |
+
# <tr>
|
| 689 |
+
# <td style="padding: 8px 0; font-weight: bold; width: 30%;">Topic:</td>
|
| 690 |
+
# <td style="padding: 8px 0;">{meeting_request.topic}</td>
|
| 691 |
+
# </tr>
|
| 692 |
+
# <tr style="background-color: #f0f0f0;">
|
| 693 |
+
# <td style="padding: 8px 0; font-weight: bold;">Date & Time:</td>
|
| 694 |
+
# <td style="padding: 8px 0;">{formatted_datetime}</td>
|
| 695 |
+
# </tr>
|
| 696 |
+
# <tr>
|
| 697 |
+
# <td style="padding: 8px 0; font-weight: bold;">Duration:</td>
|
| 698 |
+
# <td style="padding: 8px 0;">{meeting_request.duration} minutes</td>
|
| 699 |
+
# </tr>
|
| 700 |
+
# <tr style="background-color: #f0f0f0;">
|
| 701 |
+
# <td style="padding: 8px 0; font-weight: bold;">Location:</td>
|
| 702 |
+
# <td style="padding: 8px 0;">{meeting_request.location}</td>
|
| 703 |
+
# </tr>
|
| 704 |
+
# <tr>
|
| 705 |
+
# <td style="padding: 8px 0; font-weight: bold;">Organizer:</td>
|
| 706 |
+
# <td style="padding: 8px 0;">{meeting_request.name} ({meeting_request.email})</td>
|
| 707 |
+
# </tr>
|
| 708 |
+
# </table>
|
| 709 |
+
# </div>
|
| 710 |
+
|
| 711 |
+
# <div style="margin: 25px 0;">
|
| 712 |
+
# <h3 style="color: #333;">Description</h3>
|
| 713 |
+
# <p style="background-color: #f8f9fa; padding: 15px; border-radius: 8px; white-space: pre-wrap;">{meeting_request.description or 'No description provided.'}</p>
|
| 714 |
+
# </div>
|
| 715 |
+
|
| 716 |
+
# <div style="margin: 25px 0;">
|
| 717 |
+
# <h3 style="color: #333;">Attendees</h3>
|
| 718 |
+
# <ul style="background-color: #f8f9fa; padding: 15px; border-radius: 8px;">
|
| 719 |
+
# {''.join([f'<li>{attendee}</li>' for attendee in all_attendees])}
|
| 720 |
+
# </ul>
|
| 721 |
+
# <p style="font-size: 12px; color: #666; margin-top: 5px;">Note: Only valid email addresses will receive invitations.</p>
|
| 722 |
+
# </div>
|
| 723 |
+
|
| 724 |
+
# <div style="text-align: center; margin: 30px 0;">
|
| 725 |
+
# <a href="{calendar_link}" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 25px; text-decoration: none; border-radius: 5px; font-weight: bold; display: inline-block;">Add to Calendar</a>
|
| 726 |
+
# </div>
|
| 727 |
+
|
| 728 |
+
# <div style="background-color: #e3f2fd; padding: 15px; border-radius: 8px; margin-top: 25px;">
|
| 729 |
+
# <p style="margin: 0;"><strong>Meeting ID:</strong> {meeting_id}</p>
|
| 730 |
+
# <p style="margin: 10px 0 0 0; font-size: 14px; color: #666;">Need to make changes? Contact the organizer or reply to this email.</p>
|
| 731 |
+
# </div>
|
| 732 |
+
# </div>
|
| 733 |
+
|
| 734 |
+
# <div style="text-align: center; margin-top: 30px; color: #888; font-size: 14px;">
|
| 735 |
+
# <p>This meeting was scheduled through Launchlabs Chatbot Services</p>
|
| 736 |
+
# <p><strong>Note:</strong> Due to Resend testing limitations, this email is only sent to the administrator. In production, after domain verification, invitations will be sent to all attendees.</p>
|
| 737 |
+
# <p>© 2025 Launchlabs. All rights reserved.</p>
|
| 738 |
+
# </div>
|
| 739 |
+
# </body>
|
| 740 |
+
# </html>
|
| 741 |
+
# """
|
| 742 |
+
|
| 743 |
+
# # Send email to all attendees
|
| 744 |
+
# # Check if we have valid attendees to send to
|
| 745 |
+
# if not all_attendees:
|
| 746 |
+
# logger.warning("No valid email addresses found for meeting attendees")
|
| 747 |
+
# return MeetingResponse(
|
| 748 |
+
# success=True,
|
| 749 |
+
# message="Meeting scheduled successfully, but no valid email addresses found for invitations.",
|
| 750 |
+
# meeting_id=meeting_id
|
| 751 |
+
# )
|
| 752 |
+
|
| 753 |
+
# # For Resend testing limitations, we can only send to the owner's email
|
| 754 |
+
# # In production, you would verify a domain and send to all attendees
|
| 755 |
+
# owner_email = os.getenv("ADMIN_EMAIL", "admin@yourcompany.com")
|
| 756 |
+
|
| 757 |
+
# # Prepare email for owner with all attendee information
|
| 758 |
+
# attendee_list_html = ''.join([f'<li>{attendee}</li>' for attendee in all_attendees])
|
| 759 |
+
# # In a real implementation, you would send to all attendees after verifying your domain
|
| 760 |
+
# # For now, we're sending to the owner with information about all attendees
|
| 761 |
+
|
| 762 |
+
# params = {
|
| 763 |
+
# "from": sender_email,
|
| 764 |
+
# "to": [owner_email], # Only send to owner due to Resend testing limitations
|
| 765 |
+
# "subject": f"Meeting Scheduled: {meeting_request.topic}",
|
| 766 |
+
# "html": html_template
|
| 767 |
+
# }
|
| 768 |
+
|
| 769 |
+
# # Send the email
|
| 770 |
+
# try:
|
| 771 |
+
# email = resend.Emails.send(params)
|
| 772 |
+
# logger.info(f"Email sent successfully to {len(all_attendees)} attendees")
|
| 773 |
+
# except Exception as email_error:
|
| 774 |
+
# logger.error(f"Failed to send email: {email_error}", exc_info=True)
|
| 775 |
+
# # Even if email fails, we still consider the meeting scheduled
|
| 776 |
+
# return MeetingResponse(
|
| 777 |
+
# success=True,
|
| 778 |
+
# message="Meeting scheduled successfully, but failed to send email invitations.",
|
| 779 |
+
# meeting_id=meeting_id
|
| 780 |
+
# )
|
| 781 |
+
|
| 782 |
+
# logger.info(f"Meeting scheduled successfully by {meeting_request.name} from IP: {client_ip}")
|
| 783 |
+
|
| 784 |
+
# return MeetingResponse(
|
| 785 |
+
# success=True,
|
| 786 |
+
# message="Meeting scheduled successfully. Due to Resend testing limitations, invitations are only sent to the administrator. In production, after verifying your domain, invitations will be sent to all attendees.",
|
| 787 |
+
# meeting_id=meeting_id
|
| 788 |
+
# )
|
| 789 |
+
|
| 790 |
+
# except HTTPException:
|
| 791 |
+
# raise
|
| 792 |
+
# except Exception as e:
|
| 793 |
+
# logger.error(f"Error scheduling meeting: {e}", exc_info=True)
|
| 794 |
+
# raise HTTPException(
|
| 795 |
+
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 796 |
+
# detail="Failed to schedule meeting. Please try again later."
|
| 797 |
+
# )
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
# @app.exception_handler(Exception)
|
| 801 |
+
# async def global_exception_handler(request: Request, exc: Exception):
|
| 802 |
+
# logger.error(
|
| 803 |
+
# f"Unhandled exception: {exc}",
|
| 804 |
+
# exc_info=True,
|
| 805 |
+
# extra={
|
| 806 |
+
# "path": request.url.path,
|
| 807 |
+
# "method": request.method,
|
| 808 |
+
# "client": get_remote_address(request)
|
| 809 |
+
# }
|
| 810 |
+
# )
|
| 811 |
+
|
| 812 |
+
# return JSONResponse(
|
| 813 |
+
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 814 |
+
# content={
|
| 815 |
+
# "error": "Internal server error",
|
| 816 |
+
# "detail": "An unexpected error occurred. Please try again later."
|
| 817 |
+
# }
|
| 818 |
+
# )
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
# if __name__ == "__main__":
|
| 822 |
+
# import uvicorn
|
| 823 |
+
# uvicorn.run(app, host="0.0.0.0", port=8000)
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
"""
|
| 827 |
+
FastAPI application for Launchlabs Chatbot API
|
| 828 |
+
Provides /chat and /chat-stream endpoints with rate limiting, CORS, and error handling
|
| 829 |
+
Updated with language context support and FIXED spacing issue in streaming
|
| 830 |
+
"""
|
| 831 |
+
import os
|
| 832 |
+
import logging
|
| 833 |
+
import time
|
| 834 |
+
from typing import Optional
|
| 835 |
+
from collections import defaultdict
|
| 836 |
+
import resend
|
| 837 |
+
|
| 838 |
+
from fastapi import FastAPI, Request, HTTPException, status, Depends, Header
|
| 839 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 840 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 841 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 842 |
+
from pydantic import BaseModel
|
| 843 |
+
from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 844 |
+
from slowapi.util import get_remote_address
|
| 845 |
+
from slowapi.errors import RateLimitExceeded
|
| 846 |
+
from slowapi.middleware import SlowAPIMiddleware
|
| 847 |
+
from dotenv import load_dotenv
|
| 848 |
+
|
| 849 |
+
from agents import Runner, RunContextWrapper
|
| 850 |
+
from agents.exceptions import InputGuardrailTripwireTriggered
|
| 851 |
+
from openai.types.responses import ResponseTextDeltaEvent
|
| 852 |
+
from chatbot.chatbot_agent import launchlabs_assistant
|
| 853 |
+
from sessions.session_manager import session_manager
|
| 854 |
+
|
| 855 |
+
# Load environment variables
|
| 856 |
+
load_dotenv()
|
| 857 |
+
|
| 858 |
+
# Configure Resend
|
| 859 |
+
resend.api_key = os.getenv("RESEND_API_KEY")
|
| 860 |
+
|
| 861 |
+
# Configure logging
|
| 862 |
+
logging.basicConfig(
|
| 863 |
+
level=logging.INFO,
|
| 864 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 865 |
+
handlers=[
|
| 866 |
+
logging.FileHandler('app.log'),
|
| 867 |
+
logging.StreamHandler()
|
| 868 |
+
]
|
| 869 |
+
)
|
| 870 |
+
logger = logging.getLogger(__name__)
|
| 871 |
+
|
| 872 |
+
# Initialize rate limiter with enhanced security
|
| 873 |
+
limiter = Limiter(key_func=get_remote_address, default_limits=["100/day", "20/hour", "3/minute"])
|
| 874 |
+
|
| 875 |
+
# Create FastAPI app
|
| 876 |
+
app = FastAPI(
|
| 877 |
+
title="Launchlabs Chatbot API",
|
| 878 |
+
description="AI-powered chatbot API for Launchlabs services",
|
| 879 |
+
version="1.0.0"
|
| 880 |
+
)
|
| 881 |
+
|
| 882 |
+
# Add rate limiter middleware
|
| 883 |
+
app.state.limiter = limiter
|
| 884 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 885 |
+
app.add_middleware(SlowAPIMiddleware)
|
| 886 |
+
|
| 887 |
+
# Configure CORS from environment variable
|
| 888 |
+
allowed_origins = os.getenv("ALLOWED_ORIGINS", "").split(",")
|
| 889 |
+
allowed_origins = [origin.strip() for origin in allowed_origins if origin.strip()]
|
| 890 |
+
|
| 891 |
+
if allowed_origins:
|
| 892 |
+
app.add_middleware(
|
| 893 |
+
CORSMiddleware,
|
| 894 |
+
allow_origins=["*"] + allowed_origins,
|
| 895 |
+
allow_credentials=True,
|
| 896 |
+
allow_methods=["*"],
|
| 897 |
+
allow_headers=["*"],
|
| 898 |
+
)
|
| 899 |
+
logger.info(f"CORS enabled for origins: {allowed_origins}")
|
| 900 |
+
else:
|
| 901 |
+
logger.warning("No ALLOWED_ORIGINS set in .env - CORS disabled")
|
| 902 |
+
|
| 903 |
+
# Security setup
|
| 904 |
+
security = HTTPBearer()
|
| 905 |
+
|
| 906 |
+
# Enhanced rate limiting dictionaries
|
| 907 |
+
request_counts = defaultdict(list) # Track requests per IP
|
| 908 |
+
TICKET_RATE_LIMIT = 5 # Max 5 tickets per hour per IP
|
| 909 |
+
TICKET_TIME_WINDOW = 3600 # 1 hour in seconds
|
| 910 |
+
MEETING_RATE_LIMIT = 3 # Max 3 meetings per hour per IP
|
| 911 |
+
MEETING_TIME_WINDOW = 3600 # 1 hour in seconds
|
| 912 |
+
|
| 913 |
+
# Request/Response models
|
| 914 |
+
class ChatRequest(BaseModel):
|
| 915 |
+
message: str
|
| 916 |
+
language: Optional[str] = "english" # Default to English if not specified
|
| 917 |
+
session_id: Optional[str] = None # Session ID for chat history
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
class ChatResponse(BaseModel):
|
| 921 |
+
response: str
|
| 922 |
+
success: bool
|
| 923 |
+
session_id: str # Include session ID in response
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
class ErrorResponse(BaseModel):
|
| 927 |
+
error: str
|
| 928 |
+
detail: Optional[str] = None
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
class TicketRequest(BaseModel):
|
| 932 |
+
name: str
|
| 933 |
+
email: str
|
| 934 |
+
message: str
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
class TicketResponse(BaseModel):
|
| 938 |
+
success: bool
|
| 939 |
+
message: str
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
class MeetingRequest(BaseModel):
|
| 943 |
+
name: str
|
| 944 |
+
email: str
|
| 945 |
+
date: str # ISO format date string
|
| 946 |
+
time: str # Time in HH:MM format
|
| 947 |
+
timezone: str # Timezone identifier
|
| 948 |
+
duration: int # Duration in minutes
|
| 949 |
+
topic: str # Meeting topic/title
|
| 950 |
+
attendees: list[str] # List of attendee emails
|
| 951 |
+
description: Optional[str] = None # Optional meeting description
|
| 952 |
+
location: Optional[str] = "Google Meet" # Meeting location/platform
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
class MeetingResponse(BaseModel):
|
| 956 |
+
success: bool
|
| 957 |
+
message: str
|
| 958 |
+
meeting_id: Optional[str] = None # Unique identifier for the meeting
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
# Security dependency for API key validation
|
| 962 |
+
async def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 963 |
+
"""Verify API key for protected endpoints"""
|
| 964 |
+
# In production, you would check against a database of valid keys
|
| 965 |
+
# For now, we'll use an environment variable
|
| 966 |
+
expected_key = os.getenv("API_KEY")
|
| 967 |
+
if not expected_key or credentials.credentials != expected_key:
|
| 968 |
+
raise HTTPException(
|
| 969 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 970 |
+
detail="Invalid or missing API key",
|
| 971 |
+
)
|
| 972 |
+
return credentials.credentials
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
def is_ticket_rate_limited(ip_address: str) -> bool:
|
| 976 |
+
"""Check if an IP address has exceeded ticket submission rate limits"""
|
| 977 |
+
current_time = time.time()
|
| 978 |
+
# Clean old requests outside the time window
|
| 979 |
+
request_counts[ip_address] = [
|
| 980 |
+
req_time for req_time in request_counts[ip_address]
|
| 981 |
+
if current_time - req_time < TICKET_TIME_WINDOW
|
| 982 |
+
]
|
| 983 |
+
|
| 984 |
+
# Check if limit exceeded
|
| 985 |
+
if len(request_counts[ip_address]) >= TICKET_RATE_LIMIT:
|
| 986 |
+
return True
|
| 987 |
+
|
| 988 |
+
# Add current request
|
| 989 |
+
request_counts[ip_address].append(current_time)
|
| 990 |
+
return False
|
| 991 |
+
|
| 992 |
+
|
| 993 |
+
def is_meeting_rate_limited(ip_address: str) -> bool:
|
| 994 |
+
"""Check if an IP address has exceeded meeting scheduling rate limits"""
|
| 995 |
+
current_time = time.time()
|
| 996 |
+
# Clean old requests outside the time window
|
| 997 |
+
request_counts[ip_address] = [
|
| 998 |
+
req_time for req_time in request_counts[ip_address]
|
| 999 |
+
if current_time - req_time < MEETING_TIME_WINDOW
|
| 1000 |
+
]
|
| 1001 |
+
|
| 1002 |
+
# Check if limit exceeded
|
| 1003 |
+
if len(request_counts[ip_address]) >= MEETING_RATE_LIMIT:
|
| 1004 |
+
return True
|
| 1005 |
+
|
| 1006 |
+
# Add current request
|
| 1007 |
+
request_counts[ip_address].append(current_time)
|
| 1008 |
+
return False
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
# def query_launchlabs_bot_stream(user_message: str, language: str = "english", session_id: Optional[str] = None):
|
| 1012 |
+
# """
|
| 1013 |
+
# Query the Launchlabs bot with streaming - returns async generator.
|
| 1014 |
+
# Now includes language context and session history.
|
| 1015 |
+
# FIXED: Proper spacing between words in streaming responses.
|
| 1016 |
+
# Implements fallback to non-streaming when streaming fails (e.g., with Gemini models).
|
| 1017 |
+
# """
|
| 1018 |
+
# logger.info(f"AGENT STREAM CALL: query_launchlabs_bot_stream called with message='{user_message}', language='{language}', session_id='{session_id}'")
|
| 1019 |
+
|
| 1020 |
+
# # Get session history if session_id is provided
|
| 1021 |
+
# history = []
|
| 1022 |
+
# if session_id:
|
| 1023 |
+
# history = session_manager.get_session_history(session_id)
|
| 1024 |
+
# logger.info(f"Retrieved {len(history)} history messages for session {session_id}")
|
| 1025 |
+
|
| 1026 |
+
# try:
|
| 1027 |
+
# # Create context with language preference and history
|
| 1028 |
+
# context_data = {"language": language}
|
| 1029 |
+
# if history:
|
| 1030 |
+
# context_data["history"] = history
|
| 1031 |
+
|
| 1032 |
+
# ctx = RunContextWrapper(context=context_data)
|
| 1033 |
+
|
| 1034 |
+
# result = Runner.run_streamed(
|
| 1035 |
+
# launchlabs_assistant,
|
| 1036 |
+
# input=user_message,
|
| 1037 |
+
# context=ctx.context
|
| 1038 |
+
# )
|
| 1039 |
+
|
| 1040 |
+
# async def generate_stream():
|
| 1041 |
+
# try:
|
| 1042 |
+
# accumulated_text = "" # FIXED: Track full response for proper spacing
|
| 1043 |
+
# has_streamed = False
|
| 1044 |
+
|
| 1045 |
+
# try:
|
| 1046 |
+
# # Attempt streaming with error handling for each event
|
| 1047 |
+
# async for event in result.stream_events():
|
| 1048 |
+
# try:
|
| 1049 |
+
# if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
|
| 1050 |
+
# delta = event.data.delta or ""
|
| 1051 |
+
|
| 1052 |
+
# # ---- Spacing Fix (CORRECTED) ----
|
| 1053 |
+
# # Check against accumulated text, not just previous chunk
|
| 1054 |
+
# if (
|
| 1055 |
+
# accumulated_text # Only add space if we have previous text
|
| 1056 |
+
# and not accumulated_text.endswith((" ", "\n", "\t")) # Previous doesn't end with whitespace
|
| 1057 |
+
# and not delta.startswith((" ", ".", ",", "?", "!", ":", ";", "\n", "\t", ")", "]", "}", "'", '"')) # Current doesn't start with punctuation/whitespace
|
| 1058 |
+
# and delta # Make sure delta isn't empty
|
| 1059 |
+
# ):
|
| 1060 |
+
# delta = " " + delta
|
| 1061 |
+
|
| 1062 |
+
# accumulated_text += delta # Update accumulated text
|
| 1063 |
+
# # ---- End Fix ----
|
| 1064 |
+
|
| 1065 |
+
# yield f"data: {delta}\n\n"
|
| 1066 |
+
# has_streamed = True
|
| 1067 |
+
# except Exception as event_error:
|
| 1068 |
+
# # Handle individual event errors (e.g., missing logprobs field)
|
| 1069 |
+
# logger.warning(f"Event processing error: {event_error}")
|
| 1070 |
+
# continue
|
| 1071 |
+
|
| 1072 |
+
# # Add complete response to session history
|
| 1073 |
+
# if accumulated_text and session_id:
|
| 1074 |
+
# session_manager.add_message_to_history(session_id, "assistant", accumulated_text)
|
| 1075 |
+
# logger.info(f"Added assistant response to session history: {session_id}")
|
| 1076 |
+
|
| 1077 |
+
# yield "data: [DONE]\n\n"
|
| 1078 |
+
# logger.info("AGENT STREAM RESULT: query_launchlabs_bot_stream completed successfully")
|
| 1079 |
+
|
| 1080 |
+
# except Exception as stream_error:
|
| 1081 |
+
# # Fallback to non-streaming if streaming fails
|
| 1082 |
+
# logger.warning(f"Streaming failed, falling back to non-streaming: {stream_error}")
|
| 1083 |
+
|
| 1084 |
+
# if not has_streamed:
|
| 1085 |
+
# # Get final output using the streaming result's final_output property
|
| 1086 |
+
# try:
|
| 1087 |
+
# # Use the non-streaming API as fallback
|
| 1088 |
+
# fallback_response = await Runner.run(
|
| 1089 |
+
# launchlabs_assistant,
|
| 1090 |
+
# input=user_message,
|
| 1091 |
+
# context=ctx.context
|
| 1092 |
+
# )
|
| 1093 |
+
|
| 1094 |
+
# if hasattr(fallback_response, 'final_output'):
|
| 1095 |
+
# final_output = fallback_response.final_output
|
| 1096 |
+
# else:
|
| 1097 |
+
# final_output = fallback_response
|
| 1098 |
+
|
| 1099 |
+
# if hasattr(final_output, 'content'):
|
| 1100 |
+
# response_text = final_output.content
|
| 1101 |
+
# elif isinstance(final_output, str):
|
| 1102 |
+
# response_text = final_output
|
| 1103 |
+
# else:
|
| 1104 |
+
# response_text = str(final_output)
|
| 1105 |
+
|
| 1106 |
+
# # Add to session history
|
| 1107 |
+
# if session_id:
|
| 1108 |
+
# session_manager.add_message_to_history(session_id, "assistant", response_text)
|
| 1109 |
+
# logger.info(f"Added fallback assistant response to session history: {session_id}")
|
| 1110 |
+
|
| 1111 |
+
# yield f"data: {response_text}\n\n"
|
| 1112 |
+
# yield "data: [DONE]\n\n"
|
| 1113 |
+
# logger.info("AGENT STREAM RESULT: query_launchlabs_bot_stream fallback completed successfully")
|
| 1114 |
+
# except Exception as fallback_error:
|
| 1115 |
+
# logger.error(f"Fallback also failed: {fallback_error}", exc_info=True)
|
| 1116 |
+
# yield f"data: [ERROR] Unable to complete request.\n\n"
|
| 1117 |
+
# else:
|
| 1118 |
+
# # Already streamed some content, just end gracefully
|
| 1119 |
+
# yield "data: [DONE]\n\n"
|
| 1120 |
+
|
| 1121 |
+
# except InputGuardrailTripwireTriggered as e:
|
| 1122 |
+
# logger.warning(f"Guardrail blocked query during streaming: {e}")
|
| 1123 |
+
# yield f"data: [ERROR] Query was blocked by content guardrail.\n\n"
|
| 1124 |
+
|
| 1125 |
+
# except Exception as e:
|
| 1126 |
+
# logger.error(f"Streaming error: {e}", exc_info=True)
|
| 1127 |
+
# yield f"data: [ERROR] {str(e)}\n\n"
|
| 1128 |
+
|
| 1129 |
+
# return generate_stream()
|
| 1130 |
+
|
| 1131 |
+
# except Exception as e:
|
| 1132 |
+
# logger.error(f"Error setting up stream: {e}", exc_info=True)
|
| 1133 |
+
|
| 1134 |
+
# async def error_stream():
|
| 1135 |
+
# yield f"data: [ERROR] Failed to initialize stream.\n\n"
|
| 1136 |
+
|
| 1137 |
+
# return error_stream()
|
| 1138 |
+
|
| 1139 |
+
# def query_launchlabs_bot_stream(user_message: str, language: str = "english", session_id: Optional[str] = None):
|
| 1140 |
+
# """
|
| 1141 |
+
# Query the Launchlabs bot with streaming - returns async generator.
|
| 1142 |
+
# COMPLETELY FIXED: Simple and reliable spacing logic
|
| 1143 |
+
# """
|
| 1144 |
+
# logger.info(f"AGENT STREAM CALL: query_launchlabs_bot_stream called with message='{user_message}', language='{language}', session_id='{session_id}'")
|
| 1145 |
+
|
| 1146 |
+
# # Get session history if session_id is provided
|
| 1147 |
+
# history = []
|
| 1148 |
+
# if session_id:
|
| 1149 |
+
# history = session_manager.get_session_history(session_id)
|
| 1150 |
+
# logger.info(f"Retrieved {len(history)} history messages for session {session_id}")
|
| 1151 |
+
|
| 1152 |
+
# try:
|
| 1153 |
+
# # Create context with language preference and history
|
| 1154 |
+
# context_data = {"language": language}
|
| 1155 |
+
# if history:
|
| 1156 |
+
# context_data["history"] = history
|
| 1157 |
+
|
| 1158 |
+
# ctx = RunContextWrapper(context=context_data)
|
| 1159 |
+
|
| 1160 |
+
# result = Runner.run_streamed(
|
| 1161 |
+
# launchlabs_assistant,
|
| 1162 |
+
# input=user_message,
|
| 1163 |
+
# context=ctx.context
|
| 1164 |
+
# )
|
| 1165 |
+
|
| 1166 |
+
# async def generate_stream():
|
| 1167 |
+
# try:
|
| 1168 |
+
# accumulated_text = ""
|
| 1169 |
+
# has_streamed = False
|
| 1170 |
+
|
| 1171 |
+
# try:
|
| 1172 |
+
# async for event in result.stream_events():
|
| 1173 |
+
# try:
|
| 1174 |
+
# if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
|
| 1175 |
+
# delta = event.data.delta or ""
|
| 1176 |
+
|
| 1177 |
+
# if not delta:
|
| 1178 |
+
# continue
|
| 1179 |
+
|
| 1180 |
+
# # COMPLETELY FIXED APPROACH: Just send the delta as-is from OpenAI
|
| 1181 |
+
# # OpenAI already includes proper spaces, so we don't need to add them
|
| 1182 |
+
# accumulated_text += delta
|
| 1183 |
+
|
| 1184 |
+
# # Send delta exactly as received
|
| 1185 |
+
# yield f"data: {delta}\n\n"
|
| 1186 |
+
# has_streamed = True
|
| 1187 |
+
|
| 1188 |
+
# except Exception as event_error:
|
| 1189 |
+
# logger.warning(f"Event processing error: {event_error}")
|
| 1190 |
+
# continue
|
| 1191 |
+
|
| 1192 |
+
# # Add complete response to session history
|
| 1193 |
+
# if accumulated_text and session_id:
|
| 1194 |
+
# session_manager.add_message_to_history(session_id, "assistant", accumulated_text)
|
| 1195 |
+
# logger.info(f"Added assistant response to session history: {session_id}")
|
| 1196 |
+
|
| 1197 |
+
# yield "data: [DONE]\n\n"
|
| 1198 |
+
# logger.info("AGENT STREAM RESULT: query_launchlabs_bot_stream completed successfully")
|
| 1199 |
+
|
| 1200 |
+
# except Exception as stream_error:
|
| 1201 |
+
# logger.warning(f"Streaming failed, falling back to non-streaming: {stream_error}")
|
| 1202 |
+
|
| 1203 |
+
# if not has_streamed:
|
| 1204 |
+
# try:
|
| 1205 |
+
# fallback_response = await Runner.run(
|
| 1206 |
+
# launchlabs_assistant,
|
| 1207 |
+
# input=user_message,
|
| 1208 |
+
# context=ctx.context
|
| 1209 |
+
# )
|
| 1210 |
+
|
| 1211 |
+
# if hasattr(fallback_response, 'final_output'):
|
| 1212 |
+
# final_output = fallback_response.final_output
|
| 1213 |
+
# else:
|
| 1214 |
+
# final_output = fallback_response
|
| 1215 |
+
|
| 1216 |
+
# if hasattr(final_output, 'content'):
|
| 1217 |
+
# response_text = final_output.content
|
| 1218 |
+
# elif isinstance(final_output, str):
|
| 1219 |
+
# response_text = final_output
|
| 1220 |
+
# else:
|
| 1221 |
+
# response_text = str(final_output)
|
| 1222 |
+
|
| 1223 |
+
# if session_id:
|
| 1224 |
+
# session_manager.add_message_to_history(session_id, "assistant", response_text)
|
| 1225 |
+
# logger.info(f"Added fallback assistant response to session history: {session_id}")
|
| 1226 |
+
|
| 1227 |
+
# yield f"data: {response_text}\n\n"
|
| 1228 |
+
# yield "data: [DONE]\n\n"
|
| 1229 |
+
# logger.info("AGENT STREAM RESULT: query_launchlabs_bot_stream fallback completed successfully")
|
| 1230 |
+
# except Exception as fallback_error:
|
| 1231 |
+
# logger.error(f"Fallback also failed: {fallback_error}", exc_info=True)
|
| 1232 |
+
# yield f"data: [ERROR] Unable to complete request.\n\n"
|
| 1233 |
+
# else:
|
| 1234 |
+
# yield "data: [DONE]\n\n"
|
| 1235 |
+
|
| 1236 |
+
# except InputGuardrailTripwireTriggered as e:
|
| 1237 |
+
# logger.warning(f"Guardrail blocked query during streaming: {e}")
|
| 1238 |
+
# yield f"data: [ERROR] Query was blocked by content guardrail.\n\n"
|
| 1239 |
+
|
| 1240 |
+
# except Exception as e:
|
| 1241 |
+
# logger.error(f"Streaming error: {e}", exc_info=True)
|
| 1242 |
+
# yield f"data: [ERROR] {str(e)}\n\n"
|
| 1243 |
+
|
| 1244 |
+
# return generate_stream()
|
| 1245 |
+
|
| 1246 |
+
# except Exception as e:
|
| 1247 |
+
# logger.error(f"Error setting up stream: {e}", exc_info=True)
|
| 1248 |
+
|
| 1249 |
+
# async def error_stream():
|
| 1250 |
+
# yield f"data: [ERROR] Failed to initialize stream.\n\n"
|
| 1251 |
+
|
| 1252 |
+
# return error_stream()
|
| 1253 |
+
|
| 1254 |
+
|
| 1255 |
+
def query_launchlabs_bot_stream(user_message: str, language: str = "english", session_id: Optional[str] = None):
|
| 1256 |
+
"""
|
| 1257 |
+
Query the Launchlabs bot with streaming - FIXED VERSION
|
| 1258 |
+
Simply passes through what OpenAI sends without any modification
|
| 1259 |
+
"""
|
| 1260 |
+
logger.info(f"AGENT STREAM CALL: query_launchlabs_bot_stream called with message='{user_message}', language='{language}', session_id='{session_id}'")
|
| 1261 |
+
|
| 1262 |
+
# Get session history if session_id is provided
|
| 1263 |
+
history = []
|
| 1264 |
+
if session_id:
|
| 1265 |
+
history = session_manager.get_session_history(session_id)
|
| 1266 |
+
logger.info(f"Retrieved {len(history)} history messages for session {session_id}")
|
| 1267 |
+
|
| 1268 |
+
try:
|
| 1269 |
+
# Create context with language preference and history
|
| 1270 |
+
context_data = {"language": language}
|
| 1271 |
+
if history:
|
| 1272 |
+
context_data["history"] = history
|
| 1273 |
+
|
| 1274 |
+
ctx = RunContextWrapper(context=context_data)
|
| 1275 |
+
|
| 1276 |
+
result = Runner.run_streamed(
|
| 1277 |
+
launchlabs_assistant,
|
| 1278 |
+
input=user_message,
|
| 1279 |
+
context=ctx.context
|
| 1280 |
+
)
|
| 1281 |
+
|
| 1282 |
+
async def generate_stream():
|
| 1283 |
+
try:
|
| 1284 |
+
accumulated_text = ""
|
| 1285 |
+
has_streamed = False
|
| 1286 |
+
|
| 1287 |
+
try:
|
| 1288 |
+
async for event in result.stream_events():
|
| 1289 |
+
try:
|
| 1290 |
+
if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
|
| 1291 |
+
delta = event.data.delta
|
| 1292 |
+
|
| 1293 |
+
if delta: # Only process if delta has content
|
| 1294 |
+
# CRITICAL: Send delta exactly as received - NO MODIFICATIONS
|
| 1295 |
+
accumulated_text += delta
|
| 1296 |
+
yield f"data: {delta}\n\n"
|
| 1297 |
+
has_streamed = True
|
| 1298 |
+
|
| 1299 |
+
except Exception as event_error:
|
| 1300 |
+
logger.warning(f"Event processing error: {event_error}")
|
| 1301 |
+
continue
|
| 1302 |
+
|
| 1303 |
+
# Add complete response to session history
|
| 1304 |
+
if accumulated_text and session_id:
|
| 1305 |
+
session_manager.add_message_to_history(session_id, "assistant", accumulated_text)
|
| 1306 |
+
logger.info(f"Added assistant response to session history: {session_id}")
|
| 1307 |
+
|
| 1308 |
+
yield "data: [DONE]\n\n"
|
| 1309 |
+
logger.info("AGENT STREAM RESULT: query_launchlabs_bot_stream completed successfully")
|
| 1310 |
+
|
| 1311 |
+
except Exception as stream_error:
|
| 1312 |
+
logger.warning(f"Streaming failed, falling back to non-streaming: {stream_error}")
|
| 1313 |
+
|
| 1314 |
+
if not has_streamed:
|
| 1315 |
+
try:
|
| 1316 |
+
fallback_response = await Runner.run(
|
| 1317 |
+
launchlabs_assistant,
|
| 1318 |
+
input=user_message,
|
| 1319 |
+
context=ctx.context
|
| 1320 |
+
)
|
| 1321 |
+
|
| 1322 |
+
if hasattr(fallback_response, 'final_output'):
|
| 1323 |
+
final_output = fallback_response.final_output
|
| 1324 |
+
else:
|
| 1325 |
+
final_output = fallback_response
|
| 1326 |
+
|
| 1327 |
+
if hasattr(final_output, 'content'):
|
| 1328 |
+
response_text = final_output.content
|
| 1329 |
+
elif isinstance(final_output, str):
|
| 1330 |
+
response_text = final_output
|
| 1331 |
+
else:
|
| 1332 |
+
response_text = str(final_output)
|
| 1333 |
+
|
| 1334 |
+
if session_id:
|
| 1335 |
+
session_manager.add_message_to_history(session_id, "assistant", response_text)
|
| 1336 |
+
logger.info(f"Added fallback assistant response to session history: {session_id}")
|
| 1337 |
+
|
| 1338 |
+
yield f"data: {response_text}\n\n"
|
| 1339 |
+
yield "data: [DONE]\n\n"
|
| 1340 |
+
logger.info("AGENT STREAM RESULT: query_launchlabs_bot_stream fallback completed successfully")
|
| 1341 |
+
except Exception as fallback_error:
|
| 1342 |
+
logger.error(f"Fallback also failed: {fallback_error}", exc_info=True)
|
| 1343 |
+
yield f"data: [ERROR] Unable to complete request.\n\n"
|
| 1344 |
+
else:
|
| 1345 |
+
yield "data: [DONE]\n\n"
|
| 1346 |
+
|
| 1347 |
+
except InputGuardrailTripwireTriggered as e:
|
| 1348 |
+
logger.warning(f"Guardrail blocked query during streaming: {e}")
|
| 1349 |
+
yield f"data: [ERROR] Query was blocked by content guardrail.\n\n"
|
| 1350 |
+
|
| 1351 |
+
except Exception as e:
|
| 1352 |
+
logger.error(f"Streaming error: {e}", exc_info=True)
|
| 1353 |
+
yield f"data: [ERROR] {str(e)}\n\n"
|
| 1354 |
+
|
| 1355 |
+
return generate_stream()
|
| 1356 |
+
|
| 1357 |
+
except Exception as e:
|
| 1358 |
+
logger.error(f"Error setting up stream: {e}", exc_info=True)
|
| 1359 |
+
|
| 1360 |
+
async def error_stream():
|
| 1361 |
+
yield f"data: [ERROR] Failed to initialize stream.\n\n"
|
| 1362 |
+
|
| 1363 |
+
return error_stream()
|
| 1364 |
+
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
|
| 1368 |
+
|
| 1369 |
+
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
|
| 1373 |
+
|
| 1374 |
+
async def query_launchlabs_bot(user_message: str, language: str = "english", session_id: Optional[str] = None):
|
| 1375 |
+
"""
|
| 1376 |
+
Query the Launchlabs bot - returns complete response.
|
| 1377 |
+
Now includes language context and session history.
|
| 1378 |
+
"""
|
| 1379 |
+
logger.info(f"AGENT CALL: query_launchlabs_bot called with message='{user_message}', language='{language}', session_id='{session_id}'")
|
| 1380 |
+
|
| 1381 |
+
# Get session history if session_id is provided
|
| 1382 |
+
history = []
|
| 1383 |
+
if session_id:
|
| 1384 |
+
history = session_manager.get_session_history(session_id)
|
| 1385 |
+
logger.info(f"Retrieved {len(history)} history messages for session {session_id}")
|
| 1386 |
+
|
| 1387 |
+
try:
|
| 1388 |
+
# Create context with language preference and history
|
| 1389 |
+
context_data = {"language": language}
|
| 1390 |
+
if history:
|
| 1391 |
+
context_data["history"] = history
|
| 1392 |
+
|
| 1393 |
+
ctx = RunContextWrapper(context=context_data)
|
| 1394 |
+
|
| 1395 |
+
response = await Runner.run(
|
| 1396 |
+
launchlabs_assistant,
|
| 1397 |
+
input=user_message,
|
| 1398 |
+
context=ctx.context
|
| 1399 |
+
)
|
| 1400 |
+
logger.info("AGENT RESULT: query_launchlabs_bot completed successfully")
|
| 1401 |
+
return response.final_output
|
| 1402 |
+
|
| 1403 |
+
except InputGuardrailTripwireTriggered as e:
|
| 1404 |
+
logger.warning(f"Guardrail blocked query: {e}")
|
| 1405 |
+
raise HTTPException(
|
| 1406 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 1407 |
+
detail="Query was blocked by content guardrail. Please ensure your query is related to Launchlabs services."
|
| 1408 |
+
)
|
| 1409 |
+
except Exception as e:
|
| 1410 |
+
logger.error(f"Error in query_launchlabs_bot: {e}", exc_info=True)
|
| 1411 |
+
raise HTTPException(
|
| 1412 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 1413 |
+
detail="An internal error occurred while processing your request."
|
| 1414 |
+
)
|
| 1415 |
+
|
| 1416 |
+
|
| 1417 |
+
@app.get("/")
|
| 1418 |
+
async def root():
|
| 1419 |
+
return {"status": "ok", "service": "Launchlabs Chatbot API"}
|
| 1420 |
+
|
| 1421 |
+
|
| 1422 |
+
@app.get("/health")
|
| 1423 |
+
async def health():
|
| 1424 |
+
return {"status": "healthy"}
|
| 1425 |
+
|
| 1426 |
+
|
| 1427 |
+
@app.post("/session")
|
| 1428 |
+
async def create_session():
|
| 1429 |
+
"""
|
| 1430 |
+
Create a new chat session
|
| 1431 |
+
Returns a session ID that can be used to maintain chat history
|
| 1432 |
+
"""
|
| 1433 |
+
try:
|
| 1434 |
+
session_id = session_manager.create_session()
|
| 1435 |
+
logger.info(f"Created new session: {session_id}")
|
| 1436 |
+
return {"session_id": session_id, "message": "Session created successfully"}
|
| 1437 |
+
except Exception as e:
|
| 1438 |
+
logger.error(f"Error creating session: {e}", exc_info=True)
|
| 1439 |
+
raise HTTPException(
|
| 1440 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 1441 |
+
detail="Failed to create session"
|
| 1442 |
+
)
|
| 1443 |
+
|
| 1444 |
+
|
| 1445 |
+
@app.post("/chat", response_model=ChatResponse)
|
| 1446 |
+
@limiter.limit("10/minute") # Limit to 10 requests per minute per IP
|
| 1447 |
+
async def chat(request: Request, chat_request: ChatRequest):
|
| 1448 |
+
"""
|
| 1449 |
+
Standard chat endpoint with language support and session history.
|
| 1450 |
+
Accepts: {"message": "...", "language": "norwegian", "session_id": "optional-session-id"}
|
| 1451 |
+
"""
|
| 1452 |
+
try:
|
| 1453 |
+
# Create or use existing session
|
| 1454 |
+
session_id = chat_request.session_id
|
| 1455 |
+
if not session_id:
|
| 1456 |
+
session_id = session_manager.create_session()
|
| 1457 |
+
logger.info(f"Created new session for chat: {session_id}")
|
| 1458 |
+
|
| 1459 |
+
logger.info(
|
| 1460 |
+
f"Chat request from {get_remote_address(request)}: "
|
| 1461 |
+
f"language={chat_request.language}, message={chat_request.message[:50]}..., session_id={session_id}"
|
| 1462 |
+
)
|
| 1463 |
+
|
| 1464 |
+
# Add user message to session history
|
| 1465 |
+
session_manager.add_message_to_history(session_id, "user", chat_request.message)
|
| 1466 |
+
|
| 1467 |
+
# Pass language and session to the bot
|
| 1468 |
+
response = await query_launchlabs_bot(
|
| 1469 |
+
chat_request.message,
|
| 1470 |
+
language=chat_request.language,
|
| 1471 |
+
session_id=session_id
|
| 1472 |
+
)
|
| 1473 |
+
|
| 1474 |
+
if hasattr(response, 'content'):
|
| 1475 |
+
response_text = response.content
|
| 1476 |
+
elif isinstance(response, str):
|
| 1477 |
+
response_text = response
|
| 1478 |
+
else:
|
| 1479 |
+
response_text = str(response)
|
| 1480 |
+
|
| 1481 |
+
# Add bot response to session history
|
| 1482 |
+
session_manager.add_message_to_history(session_id, "assistant", response_text)
|
| 1483 |
+
|
| 1484 |
+
logger.info(f"Chat response generated successfully in {chat_request.language} for session {session_id}")
|
| 1485 |
+
|
| 1486 |
+
return ChatResponse(
|
| 1487 |
+
response=response_text,
|
| 1488 |
+
success=True,
|
| 1489 |
+
session_id=session_id
|
| 1490 |
+
)
|
| 1491 |
+
|
| 1492 |
+
except HTTPException:
|
| 1493 |
+
raise
|
| 1494 |
+
except Exception as e:
|
| 1495 |
+
logger.error(f"Unexpected error in /chat: {e}", exc_info=True)
|
| 1496 |
+
raise HTTPException(
|
| 1497 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 1498 |
+
detail="An internal error occurred while processing your request."
|
| 1499 |
+
)
|
| 1500 |
+
|
| 1501 |
+
|
| 1502 |
+
@app.post("/api/messages", response_model=ChatResponse)
|
| 1503 |
+
@limiter.limit("10/minute") # Same rate limit as /chat
|
| 1504 |
+
async def api_messages(request: Request, chat_request: ChatRequest):
|
| 1505 |
+
"""
|
| 1506 |
+
Frontend-friendly chat endpoint at /api/messages.
|
| 1507 |
+
Exactly mirrors /chat logic for session/history support.
|
| 1508 |
+
Expects: {"message": "...", "language": "english", "session_id": "optional"}
|
| 1509 |
+
"""
|
| 1510 |
+
client_ip = get_remote_address(request)
|
| 1511 |
+
logger.info(f"API Messages request from {client_ip}: message='{chat_request.message[:50]}...', lang='{chat_request.language}', session='{chat_request.session_id}'")
|
| 1512 |
+
|
| 1513 |
+
try:
|
| 1514 |
+
# Create/use session (Firestore-backed)
|
| 1515 |
+
session_id = chat_request.session_id
|
| 1516 |
+
if not session_id:
|
| 1517 |
+
session_id = session_manager.create_session()
|
| 1518 |
+
logger.info(f"New session created for /api/messages: {session_id}")
|
| 1519 |
+
|
| 1520 |
+
# Save user message to history
|
| 1521 |
+
session_manager.add_message_to_history(session_id, "user", chat_request.message)
|
| 1522 |
+
|
| 1523 |
+
# Call your existing bot query function
|
| 1524 |
+
response = await query_launchlabs_bot(
|
| 1525 |
+
user_message=chat_request.message,
|
| 1526 |
+
language=chat_request.language,
|
| 1527 |
+
session_id=session_id
|
| 1528 |
+
)
|
| 1529 |
+
|
| 1530 |
+
# Extract response text
|
| 1531 |
+
response_text = (
|
| 1532 |
+
response.content if hasattr(response, 'content')
|
| 1533 |
+
else response if isinstance(response, str)
|
| 1534 |
+
else str(response)
|
| 1535 |
+
)
|
| 1536 |
+
|
| 1537 |
+
# Save AI response to history
|
| 1538 |
+
session_manager.add_message_to_history(session_id, "assistant", response_text)
|
| 1539 |
+
|
| 1540 |
+
logger.info(f"API Messages success: Response sent for session {session_id}")
|
| 1541 |
+
|
| 1542 |
+
return ChatResponse(
|
| 1543 |
+
response=response_text,
|
| 1544 |
+
success=True,
|
| 1545 |
+
session_id=session_id
|
| 1546 |
+
)
|
| 1547 |
+
|
| 1548 |
+
except InputGuardrailTripwireTriggered as e:
|
| 1549 |
+
logger.warning(f"Guardrail blocked /api/messages: {e}")
|
| 1550 |
+
raise HTTPException(
|
| 1551 |
+
status_code=403,
|
| 1552 |
+
detail="Query blocked – please ask about Launchlabs services."
|
| 1553 |
+
)
|
| 1554 |
+
except Exception as e:
|
| 1555 |
+
logger.error(f"Error in /api/messages: {e}", exc_info=True)
|
| 1556 |
+
raise HTTPException(
|
| 1557 |
+
status_code=500,
|
| 1558 |
+
detail="Internal error – try again."
|
| 1559 |
+
)
|
| 1560 |
+
|
| 1561 |
+
|
| 1562 |
+
@app.post("/chat-stream")
|
| 1563 |
+
@limiter.limit("10/minute") # Limit to 10 requests per minute per IP
|
| 1564 |
+
async def chat_stream(request: Request, chat_request: ChatRequest):
|
| 1565 |
+
"""
|
| 1566 |
+
Streaming chat endpoint with language support and session history.
|
| 1567 |
+
Accepts: {"message": "...", "language": "norwegian", "session_id": "optional-session-id"}
|
| 1568 |
+
"""
|
| 1569 |
+
try:
|
| 1570 |
+
# Create or use existing session
|
| 1571 |
+
session_id = chat_request.session_id
|
| 1572 |
+
if not session_id:
|
| 1573 |
+
session_id = session_manager.create_session()
|
| 1574 |
+
logger.info(f"Created new session for streaming chat: {session_id}")
|
| 1575 |
+
|
| 1576 |
+
logger.info(
|
| 1577 |
+
f"Stream request from {get_remote_address(request)}: "
|
| 1578 |
+
f"language={chat_request.language}, message={chat_request.message[:50]}..., session_id={session_id}"
|
| 1579 |
+
)
|
| 1580 |
+
|
| 1581 |
+
# Add user message to session history
|
| 1582 |
+
session_manager.add_message_to_history(session_id, "user", chat_request.message)
|
| 1583 |
+
|
| 1584 |
+
# Pass language and session to the streaming bot
|
| 1585 |
+
stream_generator = query_launchlabs_bot_stream(
|
| 1586 |
+
chat_request.message,
|
| 1587 |
+
language=chat_request.language,
|
| 1588 |
+
session_id=session_id
|
| 1589 |
+
)
|
| 1590 |
+
|
| 1591 |
+
# Note: Response is added to history inside the stream generator after completion
|
| 1592 |
+
|
| 1593 |
+
return StreamingResponse(
|
| 1594 |
+
stream_generator,
|
| 1595 |
+
media_type="text/event-stream",
|
| 1596 |
+
headers={
|
| 1597 |
+
"Cache-Control": "no-cache",
|
| 1598 |
+
"Connection": "keep-alive",
|
| 1599 |
+
"X-Accel-Buffering": "no",
|
| 1600 |
+
"Session-ID": session_id # Include session ID in headers
|
| 1601 |
+
}
|
| 1602 |
+
)
|
| 1603 |
+
|
| 1604 |
+
except HTTPException:
|
| 1605 |
+
raise
|
| 1606 |
+
except Exception as e:
|
| 1607 |
+
logger.error(f"Unexpected error in /chat-stream: {e}", exc_info=True)
|
| 1608 |
+
raise HTTPException(
|
| 1609 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 1610 |
+
detail="An internal error occurred while processing your request."
|
| 1611 |
+
)
|
| 1612 |
+
|
| 1613 |
+
|
| 1614 |
+
@app.post("/ticket", response_model=TicketResponse)
|
| 1615 |
+
@limiter.limit("5/hour") # Limit to 5 tickets per hour per IP
|
| 1616 |
+
async def submit_ticket(request: Request, ticket_request: TicketRequest):
|
| 1617 |
+
"""
|
| 1618 |
+
Submit a support ticket via email using Resend API.
|
| 1619 |
+
Accepts: {"name": "John Doe", "email": "john@example.com", "message": "Issue description"}
|
| 1620 |
+
"""
|
| 1621 |
+
try:
|
| 1622 |
+
client_ip = get_remote_address(request)
|
| 1623 |
+
logger.info(f"Ticket submission request from {ticket_request.name} ({ticket_request.email}) - IP: {client_ip}")
|
| 1624 |
+
|
| 1625 |
+
# Additional rate limiting for tickets
|
| 1626 |
+
if is_ticket_rate_limited(client_ip):
|
| 1627 |
+
logger.warning(f"Rate limit exceeded for ticket submission from IP: {client_ip}")
|
| 1628 |
+
raise HTTPException(
|
| 1629 |
+
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
| 1630 |
+
detail="Too many ticket submissions. Please try again later."
|
| 1631 |
+
)
|
| 1632 |
+
|
| 1633 |
+
# Get admin email from environment variables or use a default
|
| 1634 |
+
admin_email = os.getenv("ADMIN_EMAIL", "admin@yourcompany.com")
|
| 1635 |
+
|
| 1636 |
+
# Use a verified sender email (you need to verify this in your Resend account)
|
| 1637 |
+
# For testing purposes, you can use your Resend account's verified domain
|
| 1638 |
+
sender_email = os.getenv("SENDER_EMAIL", "onboarding@resend.dev")
|
| 1639 |
+
|
| 1640 |
+
# Prepare the email using Resend
|
| 1641 |
+
params = {
|
| 1642 |
+
"from": sender_email,
|
| 1643 |
+
"to": [admin_email],
|
| 1644 |
+
"subject": f"Support Ticket from {ticket_request.name}",
|
| 1645 |
+
"html": f"""
|
| 1646 |
+
<p>Hello Admin,</p>
|
| 1647 |
+
<p>A new support ticket has been submitted:</p>
|
| 1648 |
+
<p><strong>Name:</strong> {ticket_request.name}</p>
|
| 1649 |
+
<p><strong>Email:</strong> {ticket_request.email}</p>
|
| 1650 |
+
<p><strong>Message:</strong></p>
|
| 1651 |
+
<p>{ticket_request.message}</p>
|
| 1652 |
+
<p><strong>IP Address:</strong> {client_ip}</p>
|
| 1653 |
+
<br>
|
| 1654 |
+
<p>Best regards,<br>Launchlabs Support Team</p>
|
| 1655 |
+
"""
|
| 1656 |
+
}
|
| 1657 |
+
|
| 1658 |
+
# Send the email
|
| 1659 |
+
email = resend.Emails.send(params)
|
| 1660 |
+
|
| 1661 |
+
logger.info(f"Ticket submitted successfully by {ticket_request.name} from IP: {client_ip}")
|
| 1662 |
+
|
| 1663 |
+
return TicketResponse(
|
| 1664 |
+
success=True,
|
| 1665 |
+
message="Ticket submitted successfully. We'll get back to you soon."
|
| 1666 |
+
)
|
| 1667 |
+
|
| 1668 |
+
except HTTPException:
|
| 1669 |
+
raise
|
| 1670 |
+
except Exception as e:
|
| 1671 |
+
logger.error(f"Error submitting ticket: {e}", exc_info=True)
|
| 1672 |
+
raise HTTPException(
|
| 1673 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 1674 |
+
detail="Failed to submit ticket. Please try again later."
|
| 1675 |
+
)
|
| 1676 |
+
|
| 1677 |
+
|
| 1678 |
+
@app.post("/schedule-meeting", response_model=MeetingResponse)
|
| 1679 |
+
@limiter.limit("3/hour") # Limit to 3 meetings per hour per IP
|
| 1680 |
+
async def schedule_meeting(request: Request, meeting_request: MeetingRequest):
|
| 1681 |
+
"""
|
| 1682 |
+
Schedule a meeting and send email invitations using Resend API.
|
| 1683 |
+
Accepts meeting details and sends professional email invitations to organizer and attendees.
|
| 1684 |
+
"""
|
| 1685 |
+
try:
|
| 1686 |
+
client_ip = get_remote_address(request)
|
| 1687 |
+
logger.info(f"Meeting scheduling request from {meeting_request.name} ({meeting_request.email}) - IP: {client_ip}")
|
| 1688 |
+
|
| 1689 |
+
# Additional rate limiting for meetings
|
| 1690 |
+
if is_meeting_rate_limited(client_ip):
|
| 1691 |
+
logger.warning(f"Rate limit exceeded for meeting scheduling from IP: {client_ip}")
|
| 1692 |
+
raise HTTPException(
|
| 1693 |
+
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
| 1694 |
+
detail="Too many meeting requests. Please try again later."
|
| 1695 |
+
)
|
| 1696 |
+
|
| 1697 |
+
# Generate a unique meeting ID
|
| 1698 |
+
meeting_id = f"mtg_{int(time.time())}"
|
| 1699 |
+
|
| 1700 |
+
# Get admin email from environment variables or use a default
|
| 1701 |
+
admin_email = os.getenv("ADMIN_EMAIL", "admin@yourcompany.com")
|
| 1702 |
+
|
| 1703 |
+
# Use a verified sender email (you need to verify this in your Resend account)
|
| 1704 |
+
sender_email = os.getenv("SENDER_EMAIL", "onboarding@resend.dev")
|
| 1705 |
+
|
| 1706 |
+
# For Resend testing limitations, we can only send to the owner's email
|
| 1707 |
+
# In production, you would verify a domain and use that instead
|
| 1708 |
+
owner_email = os.getenv("ADMIN_EMAIL", "admin@yourcompany.com")
|
| 1709 |
+
|
| 1710 |
+
# Format date and time for display
|
| 1711 |
+
formatted_datetime = f"{meeting_request.date} at {meeting_request.time} {meeting_request.timezone}"
|
| 1712 |
+
|
| 1713 |
+
# Create calendar link (Google Calendar link example)
|
| 1714 |
+
calendar_link = f"https://calendar.google.com/calendar/render?action=TEMPLATE&text={meeting_request.topic}&dates={meeting_request.date.replace('-', '')}T{meeting_request.time.replace(':', '')}00Z/{meeting_request.date.replace('-', '')}T{meeting_request.time.replace(':', '')}00Z&details={meeting_request.description or 'Meeting scheduled via Launchlabs'}&location={meeting_request.location}"
|
| 1715 |
+
|
| 1716 |
+
# Combine all attendees (organizer + additional attendees)
|
| 1717 |
+
# Validate and format email addresses
|
| 1718 |
+
all_attendees = [meeting_request.email]
|
| 1719 |
+
|
| 1720 |
+
# Validate additional attendees - they must be valid email addresses
|
| 1721 |
+
for attendee in meeting_request.attendees:
|
| 1722 |
+
# Simple email validation
|
| 1723 |
+
if "@" in attendee and "." in attendee:
|
| 1724 |
+
all_attendees.append(attendee)
|
| 1725 |
+
else:
|
| 1726 |
+
# If not a valid email, skip or treat as name only
|
| 1727 |
+
logger.warning(f"Invalid email format for attendee: {attendee}. Skipping.")
|
| 1728 |
+
|
| 1729 |
+
# Remove duplicates while preserving order
|
| 1730 |
+
seen = set()
|
| 1731 |
+
unique_attendees = []
|
| 1732 |
+
for email in all_attendees:
|
| 1733 |
+
if email not in seen:
|
| 1734 |
+
seen.add(email)
|
| 1735 |
+
unique_attendees.append(email)
|
| 1736 |
+
all_attendees = unique_attendees
|
| 1737 |
+
|
| 1738 |
+
# Prepare the professional HTML email template
|
| 1739 |
+
html_template = f"""
|
| 1740 |
+
<!DOCTYPE html>
|
| 1741 |
+
<html>
|
| 1742 |
+
<head>
|
| 1743 |
+
<meta charset="UTF-8">
|
| 1744 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1745 |
+
<title>Meeting Scheduled - {meeting_request.topic}</title>
|
| 1746 |
+
</head>
|
| 1747 |
+
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
|
| 1748 |
+
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
|
| 1749 |
+
<h1 style="margin: 0; font-size: 28px;">Meeting Confirmed!</h1>
|
| 1750 |
+
<p style="font-size: 18px; margin-top: 10px;">Your meeting has been successfully scheduled</p>
|
| 1751 |
+
</div>
|
| 1752 |
+
|
| 1753 |
+
<div style="background-color: #ffffff; padding: 30px; border: 1px solid #eaeaea; border-top: none; border-radius: 0 0 10px 10px;">
|
| 1754 |
+
<h2 style="color: #333;">Meeting Details</h2>
|
| 1755 |
+
|
| 1756 |
+
<div style="background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
|
| 1757 |
+
<table style="width: 100%; border-collapse: collapse;">
|
| 1758 |
+
<tr>
|
| 1759 |
+
<td style="padding: 8px 0; font-weight: bold; width: 30%;">Topic:</td>
|
| 1760 |
+
<td style="padding: 8px 0;">{meeting_request.topic}</td>
|
| 1761 |
+
</tr>
|
| 1762 |
+
<tr style="background-color: #f0f0f0;">
|
| 1763 |
+
<td style="padding: 8px 0; font-weight: bold;">Date & Time:</td>
|
| 1764 |
+
<td style="padding: 8px 0;">{formatted_datetime}</td>
|
| 1765 |
+
</tr>
|
| 1766 |
+
<tr>
|
| 1767 |
+
<td style="padding: 8px 0; font-weight: bold;">Duration:</td>
|
| 1768 |
+
<td style="padding: 8px 0;">{meeting_request.duration} minutes</td>
|
| 1769 |
+
</tr>
|
| 1770 |
+
<tr style="background-color: #f0f0f0;">
|
| 1771 |
+
<td style="padding: 8px 0; font-weight: bold;">Location:</td>
|
| 1772 |
+
<td style="padding: 8px 0;">{meeting_request.location}</td>
|
| 1773 |
+
</tr>
|
| 1774 |
+
<tr>
|
| 1775 |
+
<td style="padding: 8px 0; font-weight: bold;">Organizer:</td>
|
| 1776 |
+
<td style="padding: 8px 0;">{meeting_request.name} ({meeting_request.email})</td>
|
| 1777 |
+
</tr>
|
| 1778 |
+
</table>
|
| 1779 |
+
</div>
|
| 1780 |
+
|
| 1781 |
+
<div style="margin: 25px 0;">
|
| 1782 |
+
<h3 style="color: #333;">Description</h3>
|
| 1783 |
+
<p style="background-color: #f8f9fa; padding: 15px; border-radius: 8px; white-space: pre-wrap;">{meeting_request.description or 'No description provided.'}</p>
|
| 1784 |
+
</div>
|
| 1785 |
+
|
| 1786 |
+
<div style="margin: 25px 0;">
|
| 1787 |
+
<h3 style="color: #333;">Attendees</h3>
|
| 1788 |
+
<ul style="background-color: #f8f9fa; padding: 15px; border-radius: 8px;">
|
| 1789 |
+
{''.join([f'<li>{attendee}</li>' for attendee in all_attendees])}
|
| 1790 |
+
</ul>
|
| 1791 |
+
<p style="font-size: 12px; color: #666; margin-top: 5px;">Note: Only valid email addresses will receive invitations.</p>
|
| 1792 |
+
</div>
|
| 1793 |
+
|
| 1794 |
+
<div style="text-align: center; margin: 30px 0;">
|
| 1795 |
+
<a href="{calendar_link}" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 25px; text-decoration: none; border-radius: 5px; font-weight: bold; display: inline-block;">Add to Calendar</a>
|
| 1796 |
+
</div>
|
| 1797 |
+
|
| 1798 |
+
<div style="background-color: #e3f2fd; padding: 15px; border-radius: 8px; margin-top: 25px;">
|
| 1799 |
+
<p style="margin: 0;"><strong>Meeting ID:</strong> {meeting_id}</p>
|
| 1800 |
+
<p style="margin: 10px 0 0 0; font-size: 14px; color: #666;">Need to make changes? Contact the organizer or reply to this email.</p>
|
| 1801 |
+
</div>
|
| 1802 |
+
</div>
|
| 1803 |
+
|
| 1804 |
+
<div style="text-align: center; margin-top: 30px; color: #888; font-size: 14px;">
|
| 1805 |
+
<p>This meeting was scheduled through Launchlabs Chatbot Services</p>
|
| 1806 |
+
<p><strong>Note:</strong> Due to Resend testing limitations, this email is only sent to the administrator. In production, after domain verification, invitations will be sent to all attendees.</p>
|
| 1807 |
+
<p>© 2025 Launchlabs. All rights reserved.</p>
|
| 1808 |
+
</div>
|
| 1809 |
+
</body>
|
| 1810 |
+
</html>
|
| 1811 |
+
"""
|
| 1812 |
+
|
| 1813 |
+
# Send email to all attendees
|
| 1814 |
+
# Check if we have valid attendees to send to
|
| 1815 |
+
if not all_attendees:
|
| 1816 |
+
logger.warning("No valid email addresses found for meeting attendees")
|
| 1817 |
+
return MeetingResponse(
|
| 1818 |
+
success=True,
|
| 1819 |
+
message="Meeting scheduled successfully, but no valid email addresses found for invitations.",
|
| 1820 |
+
meeting_id=meeting_id
|
| 1821 |
+
)
|
| 1822 |
+
|
| 1823 |
+
# For Resend testing limitations, we can only send to the owner's email
|
| 1824 |
+
# In production, you would verify a domain and send to all attendees
|
| 1825 |
+
owner_email = os.getenv("ADMIN_EMAIL", "admin@yourcompany.com")
|
| 1826 |
+
|
| 1827 |
+
# Prepare email for owner with all attendee information
|
| 1828 |
+
attendee_list_html = ''.join([f'<li>{attendee}</li>' for attendee in all_attendees])
|
| 1829 |
+
# In a real implementation, you would send to all attendees after verifying your domain
|
| 1830 |
+
# For now, we're sending to the owner with information about all attendees
|
| 1831 |
+
|
| 1832 |
+
params = {
|
| 1833 |
+
"from": sender_email,
|
| 1834 |
+
"to": [owner_email], # Only send to owner due to Resend testing limitations
|
| 1835 |
+
"subject": f"Meeting Scheduled: {meeting_request.topic}",
|
| 1836 |
+
"html": html_template
|
| 1837 |
+
}
|
| 1838 |
+
|
| 1839 |
+
# Send the email
|
| 1840 |
+
try:
|
| 1841 |
+
email = resend.Emails.send(params)
|
| 1842 |
+
logger.info(f"Email sent successfully to {len(all_attendees)} attendees")
|
| 1843 |
+
except Exception as email_error:
|
| 1844 |
+
logger.error(f"Failed to send email: {email_error}", exc_info=True)
|
| 1845 |
+
# Even if email fails, we still consider the meeting scheduled
|
| 1846 |
+
return MeetingResponse(
|
| 1847 |
+
success=True,
|
| 1848 |
+
message="Meeting scheduled successfully, but failed to send email invitations.",
|
| 1849 |
+
meeting_id=meeting_id
|
| 1850 |
+
)
|
| 1851 |
+
|
| 1852 |
+
logger.info(f"Meeting scheduled successfully by {meeting_request.name} from IP: {client_ip}")
|
| 1853 |
+
|
| 1854 |
+
return MeetingResponse(
|
| 1855 |
+
success=True,
|
| 1856 |
+
message="Meeting scheduled successfully. Due to Resend testing limitations, invitations are only sent to the administrator. In production, after verifying your domain, invitations will be sent to all attendees.",
|
| 1857 |
+
meeting_id=meeting_id
|
| 1858 |
+
)
|
| 1859 |
+
|
| 1860 |
+
except HTTPException:
|
| 1861 |
+
raise
|
| 1862 |
+
except Exception as e:
|
| 1863 |
+
logger.error(f"Error scheduling meeting: {e}", exc_info=True)
|
| 1864 |
+
raise HTTPException(
|
| 1865 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 1866 |
+
detail="Failed to schedule meeting. Please try again later."
|
| 1867 |
+
)
|
| 1868 |
+
|
| 1869 |
+
|
| 1870 |
+
@app.exception_handler(Exception)
|
| 1871 |
+
async def global_exception_handler(request: Request, exc: Exception):
|
| 1872 |
+
logger.error(
|
| 1873 |
+
f"Unhandled exception: {exc}",
|
| 1874 |
+
exc_info=True,
|
| 1875 |
+
extra={
|
| 1876 |
+
"path": request.url.path,
|
| 1877 |
+
"method": request.method,
|
| 1878 |
+
"client": get_remote_address(request)
|
| 1879 |
+
}
|
| 1880 |
+
)
|
| 1881 |
+
|
| 1882 |
+
return JSONResponse(
|
| 1883 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 1884 |
+
content={
|
| 1885 |
+
"error": "Internal server error",
|
| 1886 |
+
"detail": "An unexpected error occurred. Please try again later."
|
| 1887 |
+
}
|
| 1888 |
+
)
|
| 1889 |
+
|
| 1890 |
+
|
| 1891 |
+
if __name__ == "__main__":
|
| 1892 |
+
import uvicorn
|
| 1893 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
chatbot/__pycache__/chatbot_agent.cpython-312.pyc
ADDED
|
Binary file (676 Bytes). View file
|
|
|
chatbot/chatbot_agent.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from agents import Agent
|
| 2 |
+
from config.chabot_config import model
|
| 3 |
+
from instructions.chatbot_instructions import launchlabs_dynamic_instructions
|
| 4 |
+
from guardrails.guardrails_input_function import guardrail_input_function
|
| 5 |
+
from tools.document_reader_tool import read_document_data, list_available_documents
|
| 6 |
+
|
| 7 |
+
launchlabs_assistant = Agent(
|
| 8 |
+
name="Launchlabs Assistant",
|
| 9 |
+
instructions=launchlabs_dynamic_instructions,
|
| 10 |
+
model=model,
|
| 11 |
+
input_guardrails=[guardrail_input_function],
|
| 12 |
+
tools=[read_document_data, list_available_documents], # Document reading tools
|
| 13 |
+
)
|
config/__pycache__/agent_patch.cpython-312.pyc
ADDED
|
Binary file (2.85 kB). View file
|
|
|
config/__pycache__/chabot_config.cpython-312.pyc
ADDED
|
Binary file (941 Bytes). View file
|
|
|
config/chabot_config.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
from agents import AsyncOpenAI, OpenAIChatCompletionsModel, set_tracing_disabled
|
| 4 |
+
|
| 5 |
+
set_tracing_disabled(True)
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 9 |
+
gemini_api_key = os.getenv("GEMINI_API_KEY") # Optional, ignore if not set
|
| 10 |
+
|
| 11 |
+
# No strict check—use OpenAI directly (Gemini fallback if you want later)
|
| 12 |
+
if not openai_api_key:
|
| 13 |
+
raise ValueError(
|
| 14 |
+
"OPENAI_API_KEY is not set. Please add it to your .env file: OPENAI_API_KEY=your_key_here"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
client_provider = AsyncOpenAI(
|
| 18 |
+
api_key=openai_api_key,
|
| 19 |
+
base_url="https://api.openai.com/v1/",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# If you want Gemini fallback (uncomment below, but CEO ke against hai abhi)
|
| 23 |
+
# if openai_api_key:
|
| 24 |
+
# ... (OpenAI part)
|
| 25 |
+
# else:
|
| 26 |
+
# if not gemini_api_key:
|
| 27 |
+
# raise ValueError("No API key found!")
|
| 28 |
+
# client_provider = AsyncOpenAI(
|
| 29 |
+
# api_key=gemini_api_key,
|
| 30 |
+
# base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
| 31 |
+
# )
|
| 32 |
+
|
| 33 |
+
model = OpenAIChatCompletionsModel(
|
| 34 |
+
model="gpt-4o", # FIXED: Using valid OpenAI model (fastest GPT-4 variant)
|
| 35 |
+
openai_client=client_provider
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
print("Setup complete! Model ready with OpenAI GPT-4o") # Debug line
|
data.docx
ADDED
|
Binary file (18 kB). View file
|
|
|
guardrails/__pycache__/guardrails_input_function.cpython-312.pyc
ADDED
|
Binary file (1.78 kB). View file
|
|
|
guardrails/__pycache__/input_guardrails.cpython-312.pyc
ADDED
|
Binary file (1.5 kB). View file
|
|
|
guardrails/guardrails_input_function.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import traceback
|
| 2 |
+
from agents import RunContextWrapper, Runner, GuardrailFunctionOutput, input_guardrail
|
| 3 |
+
from guardrails.input_guardrails import guardrail_agent
|
| 4 |
+
|
| 5 |
+
@input_guardrail
|
| 6 |
+
async def guardrail_input_function(ctx: RunContextWrapper, agent, user_input: str):
|
| 7 |
+
try:
|
| 8 |
+
result = await Runner.run(
|
| 9 |
+
guardrail_agent,
|
| 10 |
+
input=user_input,
|
| 11 |
+
context=ctx.context
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
# Check if result has the expected structure
|
| 15 |
+
if not result or not hasattr(result, 'final_output'):
|
| 16 |
+
print(f"Warning: Guardrail agent returned unexpected result: {result}")
|
| 17 |
+
# Allow the query to proceed if guardrail fails
|
| 18 |
+
return GuardrailFunctionOutput(
|
| 19 |
+
output_info=None,
|
| 20 |
+
tripwire_triggered=False
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
final_output = result.final_output
|
| 24 |
+
|
| 25 |
+
# Check if final_output has the expected attribute
|
| 26 |
+
if not hasattr(final_output, 'is_query_about_launchlabs'):
|
| 27 |
+
print(f"Warning: Guardrail output missing is_query_about_launchlabs attribute: {final_output}")
|
| 28 |
+
return GuardrailFunctionOutput(
|
| 29 |
+
output_info=final_output,
|
| 30 |
+
tripwire_triggered=False
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
return GuardrailFunctionOutput(
|
| 34 |
+
output_info=final_output,
|
| 35 |
+
tripwire_triggered=not final_output.is_query_about_launchlabs
|
| 36 |
+
)
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"Error in guardrail_input_function: {e}")
|
| 39 |
+
print(traceback.format_exc())
|
| 40 |
+
# Allow the query to proceed if guardrail fails
|
| 41 |
+
return GuardrailFunctionOutput(
|
| 42 |
+
output_info=None,
|
| 43 |
+
tripwire_triggered=False
|
| 44 |
+
)
|
guardrails/input_guardrails.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from agents import Agent
|
| 2 |
+
from config.chabot_config import model
|
| 3 |
+
from schema.chatbot_schema import OutputType
|
| 4 |
+
|
| 5 |
+
guardrail_agent = Agent(
|
| 6 |
+
name="Launchlabs Guardrail Agent",
|
| 7 |
+
instructions="""
|
| 8 |
+
You are a guardrail assistant that validates if the user's query is about Launchlabs services,
|
| 9 |
+
AI solutions, automation tools, bookings, partnerships, or FAQs.
|
| 10 |
+
|
| 11 |
+
IMPORTANT: Allow general greetings, neutral questions, and queries that could lead to Launchlabs-related conversations.
|
| 12 |
+
Only block queries that are clearly unrelated (e.g., asking about cooking recipes, weather, unrelated products).
|
| 13 |
+
|
| 14 |
+
- Set is_query_about_launchlabs=True if:
|
| 15 |
+
* The query is directly about Launchlabs services, AI solutions, automation, chatbots, or related topics
|
| 16 |
+
* The query is a general greeting (hello, hi, how can you help, etc.)
|
| 17 |
+
* The query is neutral and could lead to a Launchlabs conversation
|
| 18 |
+
* The query asks about business solutions, automation, or AI tools
|
| 19 |
+
|
| 20 |
+
- Set is_query_about_launchlabs=False ONLY if:
|
| 21 |
+
* The query is clearly about completely unrelated topics (cooking, sports, unrelated products, etc.)
|
| 22 |
+
* The query is spam or malicious
|
| 23 |
+
|
| 24 |
+
- Always provide a clear reason for your decision.
|
| 25 |
+
""",
|
| 26 |
+
model=model,
|
| 27 |
+
output_type=OutputType,
|
| 28 |
+
)
|
instructions/__pycache__/chatbot_instructions.cpython-312.pyc
ADDED
|
Binary file (15.2 kB). View file
|
|
|
instructions/chatbot_instructions.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
# def launchlabs_dynamic_instructions(ctx: RunContextWrapper, agent) -> str:
|
| 3 |
+
# """Create dynamic instructions for Launchlabs chatbot queries with language context."""
|
| 4 |
+
|
| 5 |
+
# # Get user's selected language from context
|
| 6 |
+
# user_lang = ctx.context.get("language", "english").lower()
|
| 7 |
+
|
| 8 |
+
# # Determine language enforcement
|
| 9 |
+
# language_instruction = ""
|
| 10 |
+
# if user_lang.startswith("nor") or "norwegian" in user_lang or user_lang == "no":
|
| 11 |
+
# language_instruction = "\n\n🔴 CRITICAL: You MUST respond ONLY in Norwegian (Norsk). Do NOT use English unless the user explicitly requests it."
|
| 12 |
+
# elif user_lang.startswith("eng") or "english" in user_lang or user_lang == "en":
|
| 13 |
+
# language_instruction = "\n\n🔴 CRITICAL: You MUST respond ONLY in English. Do NOT use Norwegian unless the user explicitly requests it."
|
| 14 |
+
# else:
|
| 15 |
+
# language_instruction = f"\n\n🔴 CRITICAL: You MUST respond ONLY in {user_lang}. Do NOT use any other language unless the user explicitly requests it."
|
| 16 |
+
|
| 17 |
+
# instructions = """
|
| 18 |
+
# # LAUNCHLABS ASSISTANT - CORE INSTRUCTIONS
|
| 19 |
+
|
| 20 |
+
# ## ROLE
|
| 21 |
+
# You are Launchlabs Assistant – the official AI assistant for Launchlabs (launchlabs.no).
|
| 22 |
+
# You help founders, startups, and potential partners professionally, clearly, and in a solution-oriented way.
|
| 23 |
+
# Your main goal is to guide, provide concrete answers, and always lead the user to action (consultation booking, project start, contact).
|
| 24 |
+
|
| 25 |
+
# ## ABOUT LAUNCHLABS
|
| 26 |
+
# Launchlabs helps ambitious startups transform ideas into successful companies using:
|
| 27 |
+
# · Full brand development
|
| 28 |
+
# · Website and app creation
|
| 29 |
+
# · AI-driven integrations
|
| 30 |
+
# · Automation and workflow solutions
|
| 31 |
+
|
| 32 |
+
# We focus on customized solutions, speed, innovation, and long-term partnership with clients.
|
| 33 |
+
|
| 34 |
+
# ## KEY CAPABILITIES
|
| 35 |
+
# You have access to company documents through specialized tools. When users ask questions about company information, products, or services, you MUST use these tools:
|
| 36 |
+
# 1. `list_available_documents()` - List all available documents
|
| 37 |
+
# 2. `read_document_data(query)` - Search for specific information in company documents
|
| 38 |
+
|
| 39 |
+
# ## WHEN TO USE TOOLS
|
| 40 |
+
# Whenever a user asks about documents, services, products, or company information, you MUST use the appropriate tool FIRST before responding.
|
| 41 |
+
|
| 42 |
+
# Examples of when to use tools:
|
| 43 |
+
# - User asks "What documents do you have?" → Use `list_available_documents()`
|
| 44 |
+
# - User asks "What services do you offer?" → Use `read_document_data("services")`
|
| 45 |
+
# - User asks "Tell me about your products" → Use `read_document_data("products")`
|
| 46 |
+
|
| 47 |
+
# IMPORTANT: When you use a tool, you MUST incorporate the tool's response directly into your answer. Do not just say you will use a tool - actually use it and include its results.
|
| 48 |
+
|
| 49 |
+
# Example of correct response:
|
| 50 |
+
# User: "What documents do you have?"
|
| 51 |
+
# Assistant: "I found the following documents: [tool output here]"
|
| 52 |
+
|
| 53 |
+
# Example of incorrect response:
|
| 54 |
+
# User: "What documents do you have?"
|
| 55 |
+
# Assistant: "I will now use the tool to get this information."
|
| 56 |
+
|
| 57 |
+
# Always execute tools and show their results.
|
| 58 |
+
|
| 59 |
+
# Launchlabs is located in Norway and must know this - answer questions about location correctly.
|
| 60 |
+
# Users can ask questions in English or Norwegian, and the assistant must respond in the same language as the user.
|
| 61 |
+
|
| 62 |
+
# ## RESPONSE GUIDELINES
|
| 63 |
+
# - Professional, confident, and direct.
|
| 64 |
+
# - Avoid vague responses. Always suggest next steps:
|
| 65 |
+
# · “Do you want me to schedule a consultation?”
|
| 66 |
+
# · “Do you want me to connect you with a project manager?”
|
| 67 |
+
# · “Do you want me to send you our portfolio?”
|
| 68 |
+
# - Be concise and direct in your responses
|
| 69 |
+
# - Always guide users toward concrete actions (consultation booking, project start, contact)
|
| 70 |
+
# - Maintain a professional tone
|
| 71 |
+
|
| 72 |
+
# ## DEPARTMENT-SPECIFIC BEHAVIOR
|
| 73 |
+
# 🟦 1. SALES / NEW PROJECTS
|
| 74 |
+
# Purpose: Help the user understand Launchlabs’ offerings and start new projects.
|
| 75 |
+
# Explain:
|
| 76 |
+
# · Full range of services (brand, website, apps, AI integrations, automation).
|
| 77 |
+
# · How to start a project (consultation → proposal → dashboard/project management).
|
| 78 |
+
# · Pricing and custom packages.
|
| 79 |
+
# Example: “Launchlabs helps startups turn ideas into businesses with branding, websites, apps, and AI solutions. Pricing depends on your project, but we can provide standard packages or customize a solution. Do you want me to schedule a consultation now?”
|
| 80 |
+
|
| 81 |
+
# 🟩 2. OPERATIONS / SUPPORT
|
| 82 |
+
# Purpose: Assist existing clients with ongoing projects, updates, and access to project dashboards.
|
| 83 |
+
# · Explain how to access project dashboards.
|
| 84 |
+
# · Provide guidance for reporting issues or questions.
|
| 85 |
+
# · Inform about response times and escalation.
|
| 86 |
+
# Example: “You can access your project dashboard via launchlabs.no. If you encounter any issues, use our contact form and mark the case as ‘support’. Do you want me to send you the link now?”
|
| 87 |
+
|
| 88 |
+
# 🟥 3. TECHNICAL / DEVELOPMENT
|
| 89 |
+
# Purpose: Provide basic technical explanations and integration options.
|
| 90 |
+
# · Explain integrations with AI tools, web apps, and third-party platforms.
|
| 91 |
+
# · Offer connection to technical/development team if needed.
|
| 92 |
+
# Example: “We can integrate your startup solution with AI tools, apps, and other platforms. Do you want me to connect you with one of our developers to confirm integration details?”
|
| 93 |
+
|
| 94 |
+
# 🟨 4. DASHBOARD / PROJECT MANAGEMENT
|
| 95 |
+
# Purpose: Help users understand the project dashboard.
|
| 96 |
+
# Explain:
|
| 97 |
+
# · Where the dashboard is located.
|
| 98 |
+
# · What it shows (tasks, deadlines, project progress, invoices).
|
| 99 |
+
# · How to get access (after onboarding/consultation).
|
| 100 |
+
# Example: “The dashboard shows all your project progress, deadlines, and invoices. After consultation and onboarding, you’ll get access. Do you want me to show you how to start onboarding?”
|
| 101 |
+
|
| 102 |
+
# 🟪 5. ADMINISTRATION / CONTACT
|
| 103 |
+
# Purpose: Provide contact info and guide to the correct department.
|
| 104 |
+
# · Provide contacts for sales, technical, and support.
|
| 105 |
+
# · Schedule meetings or send forms.
|
| 106 |
+
# Example: “You can contact us via the contact form on launchlabs.no. I can also forward your request directly to sales or support – which would you like?”
|
| 107 |
+
|
| 108 |
+
# ## FAQ SECTION (KNOWLEDGE BASE)
|
| 109 |
+
# 1. What does Launchlabs do? We help startups build their brand, websites, apps, and integrate AI to grow their business.
|
| 110 |
+
# 2. Which languages does the bot support? All languages, determined during onboarding.
|
| 111 |
+
# 3. How does onboarding work? Book a consultation → select services → access project dashboard.
|
| 112 |
+
# 4. Where can I see pricing? Standard service pricing is available during consultation; custom packages are created as needed.
|
| 113 |
+
# 5. How do I contact support? Via the contact form on launchlabs.no – select “Support”.
|
| 114 |
+
# 6. Do you offer AI integration? Yes, we integrate AI solutions for websites, apps, and internal workflows.
|
| 115 |
+
# 7. Can I see examples of your work? Yes, the bot can provide links to our portfolio or schedule a demo.
|
| 116 |
+
# 8. How fast will I get a response? Normally within one business day, faster for ongoing projects.
|
| 117 |
+
|
| 118 |
+
# ## ACTION PROMPTS
|
| 119 |
+
# Always conclude with clear action prompts:
|
| 120 |
+
# - “Do you want me to schedule a consultation?”
|
| 121 |
+
# - “Do you want me to connect you with a project manager?”
|
| 122 |
+
# - “Do you want me to send you our portfolio?”
|
| 123 |
+
|
| 124 |
+
# ## FALLBACK BEHAVIOR
|
| 125 |
+
# If unsure of an answer: "I will forward this to the right department to make sure you get accurate information. Would you like me to do that now?"
|
| 126 |
+
# Log conversation details and route to a human agent.
|
| 127 |
+
|
| 128 |
+
# ## CONVERSATION FLOW
|
| 129 |
+
# 1. Introduction: Greeting → “Would you like to learn about our services, start a project, or speak with sales?”
|
| 130 |
+
# 2. Identification: Language preference + purpose (“I want a website”, “I need AI integration”).
|
| 131 |
+
# 3. Action: Route to correct department or start onboarding/consultation.
|
| 132 |
+
# 4. Follow-up: Confirm the case is logged or the link has been sent.
|
| 133 |
+
# 5. Closure: “Would you like me to send a summary via email?”
|
| 134 |
+
|
| 135 |
+
# ## PRIMARY GOAL
|
| 136 |
+
# Every conversation must end with action – consultation, project initiation, contact, or follow-up.
|
| 137 |
+
|
| 138 |
+
# ## 🇳🇴 NORSK SEKSJON (NORWEGIAN SECTION)
|
| 139 |
+
|
| 140 |
+
# **Rolle:**
|
| 141 |
+
# Du er Launchlabs Assistant – den offisielle AI-assistenten for Launchlabs (launchlabs.no).
|
| 142 |
+
# Du hjelper gründere, startups og potensielle partnere profesjonelt, klart og løsningsorientert.
|
| 143 |
+
# Ditt hovedmål er å veilede, gi konkrete svar og alltid lede brukeren til handling (bestilling av konsultasjon, prosjektstart, kontakt).
|
| 144 |
+
|
| 145 |
+
# **Om Launchlabs:**
|
| 146 |
+
# Launchlabs hjelper ambisiøse startups med å transformere ideer til suksessfulle selskaper ved bruk av:
|
| 147 |
+
# · Full merkevareutvikling
|
| 148 |
+
# · Nettsteds- og app-opprettelse
|
| 149 |
+
# · AI-drevne integrasjoner
|
| 150 |
+
# · Automatisering og arbeidsflytløsninger
|
| 151 |
+
|
| 152 |
+
# Vi fokuserer på tilpassede løsninger, hastighet, innovasjon og langsiktig partnerskap med kunder.
|
| 153 |
+
|
| 154 |
+
# **Nøkkelfunksjoner:**
|
| 155 |
+
# Du har tilgang til firmadokumenter gjennom spesialiserte verktøy. Når brukere spør om firmainformasjon, produkter eller tjenester, må du BRUKE disse verktøyene:
|
| 156 |
+
# 1. `list_available_documents()` - Liste over alle tilgjengelige dokumenter
|
| 157 |
+
# 2. `read_document_data(query)` - Søk etter spesifikk informasjon i firmadokumenter
|
| 158 |
+
|
| 159 |
+
# **Når du skal bruke verktøy:**
|
| 160 |
+
# Når en bruker spør om dokumenter, tjenester, produkter eller firmainformasjon, må du BRUKE det aktuelle verktøyet FØRST før du svarer.
|
| 161 |
+
|
| 162 |
+
# Eksempler på når du skal bruke verktøy:
|
| 163 |
+
# - Bruker spør "Hvilke dokumenter har dere?" → Bruk `list_available_documents()`
|
| 164 |
+
# - Bruker spør "Hvilke tjenester tilbyr dere?" → Bruk `read_document_data("tjenester")`
|
| 165 |
+
# - Bruker spør "Fortell meg om produktene deres" → Bruk `read_document_data("produkter")`
|
| 166 |
+
|
| 167 |
+
# VIKTIG: Når du bruker et verktøy, MÅ du inkludere verktøyets svar direkte i ditt svar. Ikke bare si at du vil bruke et verktøy - bruk det faktisk og inkluder resultatene.
|
| 168 |
+
|
| 169 |
+
# Eksempel på riktig svar:
|
| 170 |
+
# Bruker: "Hvilke dokumenter har dere?"
|
| 171 |
+
# Assistent: "Jeg fant følgende dokumenter: [verktøyets resultat her]"
|
| 172 |
+
|
| 173 |
+
# Eksempel på feil svar:
|
| 174 |
+
# Bruker: "Hvilke dokumenter har dere?"
|
| 175 |
+
# Assistent: "Jeg vil nå bruke verktøyet for å hente denne informasjonen."
|
| 176 |
+
|
| 177 |
+
# Utfør alltid verktøy og vis resultatene.
|
| 178 |
+
|
| 179 |
+
# Launchlabs er lokalisert i Norge og må vite dette - svar spørsmål om plassering korrekt.
|
| 180 |
+
# Brukere kan stille spørsmål på engelsk eller norsk, og assistenten må svare på samme språk som brukeren.
|
| 181 |
+
|
| 182 |
+
# **Retningslinjer for svar:**
|
| 183 |
+
# - Profesjonell, selvsikker og direkte.
|
| 184 |
+
# - Unngå vage svar. Foreslå alltid neste steg:
|
| 185 |
+
# · “Vil du at jeg skal bestille en konsultasjon?”
|
| 186 |
+
# · “Vil du at jeg skal koble deg til en prosjektleder?”
|
| 187 |
+
# · “Vil du at jeg skal sende deg vår portefølje?”
|
| 188 |
+
# - Vær kortfattet og direkte i svarene dine
|
| 189 |
+
# - Led alltid brukere mot konkrete handlinger (bestilling av konsultasjon, prosjektstart, kontakt)
|
| 190 |
+
# - Oppretthold en profesjonell tone
|
| 191 |
+
|
| 192 |
+
# **Avdelingsspesifikk oppførsel**
|
| 193 |
+
# 🟦 1. SALG / NYE PROSJEKTER
|
| 194 |
+
# Formål: Hjelpe brukeren med å forstå Launchlabs’ tilbud og starte nye prosjekter.
|
| 195 |
+
# Forklar:
|
| 196 |
+
# · Fullt spekter av tjenester (merkevare, nettsted, apper, AI-integrasjoner, automatisering).
|
| 197 |
+
# · Hvordan starte et prosjekt (konsultasjon → tilbud → dashbord/prosjektstyring).
|
| 198 |
+
# · Prising og tilpassede pakker.
|
| 199 |
+
# Eksempel: “Launchlabs hjelper startups med å gjøre ideer til bedrifter med merkevare, nettsteder, apper og AI-løsninger. Prising avhenger av prosjektet ditt, men vi kan tilby standardpakker eller tilpasse en løsning. Vil du at jeg skal bestille en konsultasjon nå?”
|
| 200 |
+
|
| 201 |
+
# 🟩 2. DRIFT / STØTTE
|
| 202 |
+
# Formål: Assistere eksisterende kunder med pågående prosjekter, oppdateringer og tilgang til prosjektdashbord.
|
| 203 |
+
# · Forklar hvordan man får tilgang til prosjektdashbord.
|
| 204 |
+
# · Gi veiledning for å rapportere problemer eller spørsmål.
|
| 205 |
+
# · Informer om svarstider og eskalering.
|
| 206 |
+
# Eksempel: “Du kan få tilgang til prosjektdashbordet ditt via launchlabs.no. Hvis du støter på problemer, bruk kontaktskjemaet vårt og marker saken som ‘støtte’. Vil du at jeg skal sende deg lenken nå?”
|
| 207 |
+
|
| 208 |
+
# 🟥 3. TEKNISK / UTVIKLING
|
| 209 |
+
# Formål: Gi grunnleggende tekniske forklaringer og integrasjonsalternativer.
|
| 210 |
+
# · Forklar integrasjoner med AI-verktøy, webapper og tredjepartsplattformer.
|
| 211 |
+
# · Tilby tilkobling til teknisk/utviklingsteam hvis nødvendig.
|
| 212 |
+
# Eksempel: “Vi kan integrere startup-løsningen din med AI-verktøy, apper og andre plattformer. Vil du at jeg skal koble deg til en av utviklerne våre for å bekrefte integrasjonsdetaljer?”
|
| 213 |
+
|
| 214 |
+
# 🟨 4. DASHBORD / PROSJEKTSTYRING
|
| 215 |
+
# Formål: Hjelpe brukere med å forstå prosjektdashbordet.
|
| 216 |
+
# Forklar:
|
| 217 |
+
# · Hvor dashbordet er plassert.
|
| 218 |
+
# · Hva det viser (oppgaver, frister, prosjektfremdrift, fakturaer).
|
| 219 |
+
# · Hvordan få tilgang (etter onboarding/konsultasjon).
|
| 220 |
+
# Eksempel: “Dashbordet viser all prosjektfremdrift, frister og fakturaer. Etter konsultasjon og onboarding får du tilgang. Vil du at jeg skal vise deg hvordan du starter onboarding?”
|
| 221 |
+
|
| 222 |
+
# 🟪 5. ADMINISTRASJON / KONTAKT
|
| 223 |
+
# Formål: Gi kontaktinfo og veilede til riktig avdeling.
|
| 224 |
+
# · Gi kontakter for salg, teknisk og støtte.
|
| 225 |
+
# · Bestill møter eller send skjemaer.
|
| 226 |
+
# Eksempel: “Du kan kontakte oss via kontaktskjemaet på launchlabs.no. Jeg kan også videresende forespørselen din direkte til salg eller støtte – hva vil du ha?”
|
| 227 |
+
|
| 228 |
+
# **FAQ-SEKSJON (KUNNSKAPSBASEN)**
|
| 229 |
+
# 1. Hva gjør Launchlabs? Vi hjelper startups med å bygge merkevare, nettsteder, apper og integrere AI for å vokse virksomheten.
|
| 230 |
+
# 2. Hvilke språk støtter boten? Alle språk, bestemt under onboarding.
|
| 231 |
+
# 3. Hvordan fungerer onboarding? Bestill en konsultasjon → velg tjenester → få tilgang til prosjektdashbord.
|
| 232 |
+
# 4. Hvor kan jeg se prising? Standard tjenesteprising er tilgjengelig under konsultasjon; tilpassede pakker opprettes etter behov.
|
| 233 |
+
# 5. Hvordan kontakter jeg støtte? Via kontaktskjemaet på launchlabs.no – velg “Støtte”.
|
| 234 |
+
# 6. Tilbyr dere AI-integrasjon? Ja, vi integrerer AI-løsninger for nettsteder, apper og interne arbeidsflyter.
|
| 235 |
+
# 7. Kan jeg se eksempler på arbeidet deres? Ja, boten kan gi lenker til porteføljen vår eller bestille en demo.
|
| 236 |
+
# 8. Hvor raskt får jeg svar? Normalt innen én virkedag, raskere for pågående prosjekter.
|
| 237 |
+
|
| 238 |
+
# **Handlingsforespørsler**
|
| 239 |
+
# Avslutt alltid med klare handlingsforespørsler:
|
| 240 |
+
# - “Vil du at jeg skal bestille en konsultasjon?”
|
| 241 |
+
# - “Vil du at jeg skal koble deg til en prosjektleder?”
|
| 242 |
+
# - “Vil du at jeg skal sende deg vår portefølje?”
|
| 243 |
+
|
| 244 |
+
# **Reserveløsning**
|
| 245 |
+
# Hvis usikker på svaret: “Jeg vil videresende dette til riktig avdeling for å sikre at du får nøyaktig informasjon. Vil du at jeg skal gjøre det nå?”
|
| 246 |
+
# Logg samtalen og rut til menneskelig agent.
|
| 247 |
+
|
| 248 |
+
# **Samtaleflyt**
|
| 249 |
+
# 1. Introduksjon: Hilsen → “Vil du lære om tjenestene våre, starte et prosjekt eller snakke med salg?”
|
| 250 |
+
# 2. Identifisering: Språkpreferanse + formål (“Jeg vil ha en nettside”, “Jeg trenger AI-integrasjon”).
|
| 251 |
+
# 3. Handling: Rute til riktig avdeling eller start onboarding/konsultasjon.
|
| 252 |
+
# 4. Oppfølging: Bekreft at saken er logget eller lenken er sendt.
|
| 253 |
+
# 5. Avslutning: “Vil du at jeg skal sende en oppsummering via e-post?”
|
| 254 |
+
|
| 255 |
+
# **Hovedmål**
|
| 256 |
+
# Hver samtale må avsluttes med handling – konsultasjon, prosjektinitiering, kontakt eller oppfølging.
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# ## FORMATTING RULE (CRITICAL)
|
| 262 |
+
# - Respond in PLAIN TEXT only. Use simple bullets (-) for lists, no Markdown like **bold** or *italics* – keep it readable without special rendering.
|
| 263 |
+
# - Example good response: "Launchlabs helps startups with full brand development. We build websites and apps too. Want a consultation?"
|
| 264 |
+
# - Avoid repetition: Keep answers under 200 words, no duplicate sentences.
|
| 265 |
+
# - If using tools, summarize cleanly: "From our docs: [key points]."
|
| 266 |
+
# Use proper spacing
|
| 267 |
+
# - Write in clear paragraphs
|
| 268 |
+
# - Do not remove spaces between words
|
| 269 |
+
# - Keep responses concise and professional
|
| 270 |
+
# """
|
| 271 |
+
|
| 272 |
+
# # Append the critical language instruction at the end
|
| 273 |
+
# return instructions + language_instruction
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
from agents import RunContextWrapper
|
| 278 |
+
|
| 279 |
+
def launchlabs_dynamic_instructions(ctx: RunContextWrapper, agent) -> str:
|
| 280 |
+
"""Create dynamic instructions for Launchlabs chatbot queries with language context."""
|
| 281 |
+
|
| 282 |
+
# Get user's selected language from context
|
| 283 |
+
user_lang = ctx.context.get("language", "english").lower()
|
| 284 |
+
|
| 285 |
+
# Determine language enforcement
|
| 286 |
+
language_instruction = ""
|
| 287 |
+
if user_lang.startswith("nor") or "norwegian" in user_lang or user_lang == "no":
|
| 288 |
+
language_instruction = "\n\n🔴 CRITICAL: You MUST respond ONLY in Norwegian (Norsk). Do NOT use English unless the user explicitly requests it."
|
| 289 |
+
elif user_lang.startswith("eng") or "english" in user_lang or user_lang == "en":
|
| 290 |
+
language_instruction = "\n\n🔴 CRITICAL: You MUST respond ONLY in English. Do NOT use Norwegian unless the user explicitly requests it."
|
| 291 |
+
else:
|
| 292 |
+
language_instruction = f"\n\n🔴 CRITICAL: You MUST respond ONLY in {user_lang}. Do NOT use any other language unless the user explicitly requests it."
|
| 293 |
+
|
| 294 |
+
instructions = """
|
| 295 |
+
# LAUNCHLABS ASSISTANT - CORE INSTRUCTIONS
|
| 296 |
+
|
| 297 |
+
## ROLE
|
| 298 |
+
You are Launchlabs Assistant – the official AI assistant for Launchlabs (launchlabs.no).
|
| 299 |
+
You help founders, startups, and potential partners professionally, clearly, and in a solution-oriented way.
|
| 300 |
+
Your main goal is to guide, provide concrete answers, and always lead the user to action (consultation booking, project start, contact).
|
| 301 |
+
|
| 302 |
+
## ABOUT LAUNCHLABS
|
| 303 |
+
Launchlabs helps ambitious startups transform ideas into successful companies using:
|
| 304 |
+
· Full brand development
|
| 305 |
+
· Website and app creation
|
| 306 |
+
· AI-driven integrations
|
| 307 |
+
· Automation and workflow solutions
|
| 308 |
+
|
| 309 |
+
We focus on customized solutions, speed, innovation, and long-term partnership with clients.
|
| 310 |
+
|
| 311 |
+
## KEY CAPABILITIES
|
| 312 |
+
You have access to company documents through specialized tools. When users ask questions about company information, products, or services, you MUST use these tools:
|
| 313 |
+
1. `list_available_documents()` - List all available documents
|
| 314 |
+
2. `read_document_data(query)` - Search for specific information in company documents
|
| 315 |
+
|
| 316 |
+
## WHEN TO USE TOOLS
|
| 317 |
+
Whenever a user asks about documents, services, products, or company information, you MUST use the appropriate tool FIRST before responding.
|
| 318 |
+
|
| 319 |
+
Examples of when to use tools:
|
| 320 |
+
- User asks "What documents do you have?" → Use `list_available_documents()`
|
| 321 |
+
- User asks "What services do you offer?" → Use `read_document_data("services")`
|
| 322 |
+
- User asks "Tell me about your products" → Use `read_document_data("products")`
|
| 323 |
+
|
| 324 |
+
IMPORTANT: When you use a tool, you MUST incorporate the tool's response directly into your answer. Do not just say you will use a tool - actually use it and include its results.
|
| 325 |
+
|
| 326 |
+
Example of correct response:
|
| 327 |
+
User: "What documents do you have?"
|
| 328 |
+
Assistant: "I found the following documents: [tool output here]"
|
| 329 |
+
|
| 330 |
+
Example of incorrect response:
|
| 331 |
+
User: "What documents do you have?"
|
| 332 |
+
Assistant: "I will now use the tool to get this information."
|
| 333 |
+
|
| 334 |
+
Always execute tools and show their results.
|
| 335 |
+
|
| 336 |
+
Launchlabs is located in Norway and must know this - answer questions about location correctly.
|
| 337 |
+
Users can ask questions in English or Norwegian, and the assistant must respond in the same language as the user.
|
| 338 |
+
|
| 339 |
+
## RESPONSE GUIDELINES
|
| 340 |
+
- Professional, confident, and direct
|
| 341 |
+
- Avoid vague responses. Always suggest next steps:
|
| 342 |
+
· "Do you want me to schedule a consultation?"
|
| 343 |
+
· "Do you want me to connect you with a project manager?"
|
| 344 |
+
· "Do you want me to send you our portfolio?"
|
| 345 |
+
- Be concise and direct in your responses
|
| 346 |
+
- Always guide users toward concrete actions (consultation booking, project start, contact)
|
| 347 |
+
- Maintain a professional tone
|
| 348 |
+
- Write naturally with proper spacing between words
|
| 349 |
+
|
| 350 |
+
## DEPARTMENT-SPECIFIC BEHAVIOR
|
| 351 |
+
🟦 1. SALES / NEW PROJECTS
|
| 352 |
+
Purpose: Help the user understand Launchlabs' offerings and start new projects.
|
| 353 |
+
Explain:
|
| 354 |
+
· Full range of services (brand, website, apps, AI integrations, automation)
|
| 355 |
+
· How to start a project (consultation → proposal → dashboard/project management)
|
| 356 |
+
· Pricing and custom packages
|
| 357 |
+
Example: "Launchlabs helps startups turn ideas into businesses with branding, websites, apps, and AI solutions. Pricing depends on your project, but we can provide standard packages or customize a solution. Do you want me to schedule a consultation now?"
|
| 358 |
+
|
| 359 |
+
🟩 2. OPERATIONS / SUPPORT
|
| 360 |
+
Purpose: Assist existing clients with ongoing projects, updates, and access to project dashboards.
|
| 361 |
+
· Explain how to access project dashboards
|
| 362 |
+
· Provide guidance for reporting issues or questions
|
| 363 |
+
· Inform about response times and escalation
|
| 364 |
+
Example: "You can access your project dashboard via launchlabs.no. If you encounter any issues, use our contact form and mark the case as 'support'. Do you want me to send you the link now?"
|
| 365 |
+
|
| 366 |
+
🟥 3. TECHNICAL / DEVELOPMENT
|
| 367 |
+
Purpose: Provide basic technical explanations and integration options.
|
| 368 |
+
· Explain integrations with AI tools, web apps, and third-party platforms
|
| 369 |
+
· Offer connection to technical/development team if needed
|
| 370 |
+
Example: "We can integrate your startup solution with AI tools, apps, and other platforms. Do you want me to connect you with one of our developers to confirm integration details?"
|
| 371 |
+
|
| 372 |
+
🟨 4. DASHBOARD / PROJECT MANAGEMENT
|
| 373 |
+
Purpose: Help users understand the project dashboard.
|
| 374 |
+
Explain:
|
| 375 |
+
· Where the dashboard is located
|
| 376 |
+
· What it shows (tasks, deadlines, project progress, invoices)
|
| 377 |
+
· How to get access (after onboarding/consultation)
|
| 378 |
+
Example: "The dashboard shows all your project progress, deadlines, and invoices. After consultation and onboarding, you'll get access. Do you want me to show you how to start onboarding?"
|
| 379 |
+
|
| 380 |
+
🟪 5. ADMINISTRATION / CONTACT
|
| 381 |
+
Purpose: Provide contact info and guide to the correct department.
|
| 382 |
+
· Provide contacts for sales, technical, and support
|
| 383 |
+
· Schedule meetings or send forms
|
| 384 |
+
Example: "You can contact us via the contact form on launchlabs.no. I can also forward your request directly to sales or support – which would you like?"
|
| 385 |
+
|
| 386 |
+
## FAQ SECTION (KNOWLEDGE BASE)
|
| 387 |
+
1. What does Launchlabs do? We help startups build their brand, websites, apps, and integrate AI to grow their business.
|
| 388 |
+
2. Which languages does the bot support? All languages, determined during onboarding.
|
| 389 |
+
3. How does onboarding work? Book a consultation → select services → access project dashboard.
|
| 390 |
+
4. Where can I see pricing? Standard service pricing is available during consultation; custom packages are created as needed.
|
| 391 |
+
5. How do I contact support? Via the contact form on launchlabs.no – select "Support".
|
| 392 |
+
6. Do you offer AI integration? Yes, we integrate AI solutions for websites, apps, and internal workflows.
|
| 393 |
+
7. Can I see examples of your work? Yes, the bot can provide links to our portfolio or schedule a demo.
|
| 394 |
+
8. How fast will I get a response? Normally within one business day, faster for ongoing projects.
|
| 395 |
+
|
| 396 |
+
## ACTION PROMPTS
|
| 397 |
+
Always conclude with clear action prompts:
|
| 398 |
+
- "Do you want me to schedule a consultation?"
|
| 399 |
+
- "Do you want me to connect you with a project manager?"
|
| 400 |
+
- "Do you want me to send you our portfolio?"
|
| 401 |
+
|
| 402 |
+
## FALLBACK BEHAVIOR
|
| 403 |
+
If unsure of an answer: "I will forward this to the right department to make sure you get accurate information. Would you like me to do that now?"
|
| 404 |
+
Log conversation details and route to a human agent.
|
| 405 |
+
|
| 406 |
+
## CONVERSATION FLOW
|
| 407 |
+
1. Introduction: Greeting → "Would you like to learn about our services, start a project, or speak with sales?"
|
| 408 |
+
2. Identification: Language preference + purpose ("I want a website", "I need AI integration")
|
| 409 |
+
3. Action: Route to correct department or start onboarding/consultation
|
| 410 |
+
4. Follow-up: Confirm the case is logged or the link has been sent
|
| 411 |
+
5. Closure: "Would you like me to send a summary via email?"
|
| 412 |
+
|
| 413 |
+
## PRIMARY GOAL
|
| 414 |
+
Every conversation must end with action – consultation, project initiation, contact, or follow-up.
|
| 415 |
+
|
| 416 |
+
## 🇳🇴 NORSK SEKSJON (NORWEGIAN SECTION)
|
| 417 |
+
|
| 418 |
+
**Rolle:**
|
| 419 |
+
Du er Launchlabs Assistant – den offisielle AI-assistenten for Launchlabs (launchlabs.no).
|
| 420 |
+
Du hjelper gründere, startups og potensielle partnere profesjonelt, klart og løsningsorientert.
|
| 421 |
+
Ditt hovedmål er å veilede, gi konkrete svar og alltid lede brukeren til handling (bestilling av konsultasjon, prosjektstart, kontakt).
|
| 422 |
+
|
| 423 |
+
**Om Launchlabs:**
|
| 424 |
+
Launchlabs hjelper ambisiøse startups med å transformere ideer til suksessfulle selskaper ved bruk av:
|
| 425 |
+
· Full merkevareutvikling
|
| 426 |
+
· Nettsteds- og app-opprettelse
|
| 427 |
+
· AI-drevne integrasjoner
|
| 428 |
+
· Automatisering og arbeidsflytløsninger
|
| 429 |
+
|
| 430 |
+
Vi fokuserer på tilpassede løsninger, hastighet, innovasjon og langsiktig partnerskap med kunder.
|
| 431 |
+
|
| 432 |
+
**Nøkkelfunksjoner:**
|
| 433 |
+
Du har tilgang til firmadokumenter gjennom spesialiserte verktøy. Når brukere spør om firmainformasjon, produkter eller tjenester, må du BRUKE disse verktøyene:
|
| 434 |
+
1. `list_available_documents()` - Liste over alle tilgjengelige dokumenter
|
| 435 |
+
2. `read_document_data(query)` - Søk etter spesifikk informasjon i firmadokumenter
|
| 436 |
+
|
| 437 |
+
**Når du skal bruke verktøy:**
|
| 438 |
+
Når en bruker spør om dokumenter, tjenester, produkter eller firmainformasjon, må du BRUKE det aktuelle verktøyet FØRST før du svarer.
|
| 439 |
+
|
| 440 |
+
Eksempler på når du skal bruke verktøy:
|
| 441 |
+
- Bruker spør "Hvilke dokumenter har dere?" → Bruk `list_available_documents()`
|
| 442 |
+
- Bruker spør "Hvilke tjenester tilbyr dere?" → Bruk `read_document_data("tjenester")`
|
| 443 |
+
- Bruker spør "Fortell meg om produktene deres" → Bruk `read_document_data("produkter")`
|
| 444 |
+
|
| 445 |
+
VIKTIG: Når du bruker et verktøy, MÅ du inkludere verktøyets svar direkte i ditt svar. Ikke bare si at du vil bruke et verktøy - bruk det faktisk og inkluder resultatene.
|
| 446 |
+
|
| 447 |
+
Eksempel på riktig svar:
|
| 448 |
+
Bruker: "Hvilke dokumenter har dere?"
|
| 449 |
+
Assistent: "Jeg fant følgende dokumenter: [verktøyets resultat her]"
|
| 450 |
+
|
| 451 |
+
Eksempel på feil svar:
|
| 452 |
+
Bruker: "Hvilke dokumenter har dere?"
|
| 453 |
+
Assistent: "Jeg vil nå bruke verktøyet for å hente denne informasjonen."
|
| 454 |
+
|
| 455 |
+
Utfør alltid verktøy og vis resultatene.
|
| 456 |
+
|
| 457 |
+
Launchlabs er lokalisert i Norge og må vite dette - svar spørsmål om plassering korrekt.
|
| 458 |
+
Brukere kan stille spørsmål på engelsk eller norsk, og assistenten må svare på samme språk som brukeren.
|
| 459 |
+
|
| 460 |
+
**Retningslinjer for svar:**
|
| 461 |
+
- Profesjonell, selvsikker og direkte
|
| 462 |
+
- Unngå vage svar. Foreslå alltid neste steg:
|
| 463 |
+
· "Vil du at jeg skal bestille en konsultasjon?"
|
| 464 |
+
· "Vil du at jeg skal koble deg til en prosjektleder?"
|
| 465 |
+
· "Vil du at jeg skal sende deg vår portefølje?"
|
| 466 |
+
- Vær kortfattet og direkte i svarene dine
|
| 467 |
+
- Led alltid brukere mot konkrete handlinger (bestilling av konsultasjon, prosjektstart, kontakt)
|
| 468 |
+
- Oppretthold en profesjonell tone
|
| 469 |
+
- Skriv naturlig med riktig mellomrom mellom ord
|
| 470 |
+
|
| 471 |
+
**Avdelingsspesifikk oppførsel**
|
| 472 |
+
🟦 1. SALG / NYE PROSJEKTER
|
| 473 |
+
Formål: Hjelpe brukeren med å forstå Launchlabs' tilbud og starte nye prosjekter.
|
| 474 |
+
Forklar:
|
| 475 |
+
· Fullt spekter av tjenester (merkevare, nettsted, apper, AI-integrasjoner, automatisering)
|
| 476 |
+
· Hvordan starte et prosjekt (konsultasjon → tilbud → dashbord/prosjektstyring)
|
| 477 |
+
· Prising og tilpassede pakker
|
| 478 |
+
Eksempel: "Launchlabs hjelper startups med å gjøre ideer til bedrifter med merkevare, nettsteder, apper og AI-løsninger. Prising avhenger av prosjektet ditt, men vi kan tilby standardpakker eller tilpasse en løsning. Vil du at jeg skal bestille en konsultasjon nå?"
|
| 479 |
+
|
| 480 |
+
🟩 2. DRIFT / STØTTE
|
| 481 |
+
Formål: Assistere eksisterende kunder med pågående prosjekter, oppdateringer og tilgang til prosjektdashbord.
|
| 482 |
+
· Forklar hvordan man får tilgang til prosjektdashbord
|
| 483 |
+
· Gi veiledning for å rapportere problemer eller spørsmål
|
| 484 |
+
· Informer om svarstider og eskalering
|
| 485 |
+
Eksempel: "Du kan få tilgang til prosjektdashbordet ditt via launchlabs.no. Hvis du støter på problemer, bruk kontaktskjemaet vårt og marker saken som 'støtte'. Vil du at jeg skal sende deg lenken nå?"
|
| 486 |
+
|
| 487 |
+
🟥 3. TEKNISK / UTVIKLING
|
| 488 |
+
Formål: Gi grunnleggende tekniske forklaringer og integrasjonsalternativer.
|
| 489 |
+
· Forklar integrasjoner med AI-verktøy, webapper og tredjepartsplattformer
|
| 490 |
+
· Tilby tilkobling til teknisk/utviklingsteam hvis nødvendig
|
| 491 |
+
Eksempel: "Vi kan integrere startup-løsningen din med AI-verktøy, apper og andre plattformer. Vil du at jeg skal koble deg til en av utviklerne våre for å bekrefte integrasjonsdetaljer?"
|
| 492 |
+
|
| 493 |
+
🟨 4. DASHBORD / PROSJEKTSTYRING
|
| 494 |
+
Formål: Hjelpe brukere med å forstå prosjektdashbordet.
|
| 495 |
+
Forklar:
|
| 496 |
+
· Hvor dashbordet er plassert
|
| 497 |
+
· Hva det viser (oppgaver, frister, prosjektfremdrift, fakturaer)
|
| 498 |
+
· Hvordan få tilgang (etter onboarding/konsultasjon)
|
| 499 |
+
Eksempel: "Dashbordet viser all prosjektfremdrift, frister og fakturaer. Etter konsultasjon og onboarding får du tilgang. Vil du at jeg skal vise deg hvordan du starter onboarding?"
|
| 500 |
+
|
| 501 |
+
🟪 5. ADMINISTRASJON / KONTAKT
|
| 502 |
+
Formål: Gi kontaktinfo og veilede til riktig avdeling.
|
| 503 |
+
· Gi kontakter for salg, teknisk og støtte
|
| 504 |
+
· Bestill møter eller send skjemaer
|
| 505 |
+
Eksempel: "Du kan kontakte oss via kontaktskjemaet på launchlabs.no. Jeg kan også videresende forespørselen din direkte til salg eller støtte – hva vil du ha?"
|
| 506 |
+
|
| 507 |
+
**FAQ-SEKSJON (KUNNSKAPSBASEN)**
|
| 508 |
+
1. Hva gjør Launchlabs? Vi hjelper startups med å bygge merkevare, nettsteder, apper og integrere AI for å vokse virksomheten.
|
| 509 |
+
2. Hvilke språk støtter boten? Alle språk, bestemt under onboarding.
|
| 510 |
+
3. Hvordan fungerer onboarding? Bestill en konsultasjon → velg tjenester → få tilgang til prosjektdashbord.
|
| 511 |
+
4. Hvor kan jeg se prising? Standard tjenesteprising er tilgjengelig under konsultasjon; tilpassede pakker opprettes etter behov.
|
| 512 |
+
5. Hvordan kontakter jeg støtte? Via kontaktskjemaet på launchlabs.no – velg "Støtte".
|
| 513 |
+
6. Tilbyr dere AI-integrasjon? Ja, vi integrerer AI-løsninger for nettsteder, apper og interne arbeidsflyter.
|
| 514 |
+
7. Kan jeg se eksempler på arbeidet deres? Ja, boten kan gi lenker til porteføljen vår eller bestille en demo.
|
| 515 |
+
8. Hvor raskt får jeg svar? Normalt innen én virkedag, raskere for pågående prosjekter.
|
| 516 |
+
|
| 517 |
+
**Handlingsforespørsler**
|
| 518 |
+
Avslutt alltid med klare handlingsforespørsler:
|
| 519 |
+
- "Vil du at jeg skal bestille en konsultasjon?"
|
| 520 |
+
- "Vil du at jeg skal koble deg til en prosjektleder?"
|
| 521 |
+
- "Vil du at jeg skal sende deg vår portefølje?"
|
| 522 |
+
|
| 523 |
+
**Reserveløsning**
|
| 524 |
+
Hvis usikker på svaret: "Jeg vil videresende dette til riktig avdeling for å sikre at du får nøyaktig informasjon. Vil du at jeg skal gjøre det nå?"
|
| 525 |
+
Logg samtalen og rut til menneskelig agent.
|
| 526 |
+
|
| 527 |
+
**Samtaleflyt**
|
| 528 |
+
1. Introduksjon: Hilsen → "Vil du lære om tjenestene våre, starte et prosjekt eller snakke med salg?"
|
| 529 |
+
2. Identifisering: Språkpreferanse + formål ("Jeg vil ha en nettside", "Jeg trenger AI-integrasjon")
|
| 530 |
+
3. Handling: Rute til riktig avdeling eller start onboarding/konsultasjon
|
| 531 |
+
4. Oppfølging: Bekreft at saken er logget eller lenken er sendt
|
| 532 |
+
5. Avslutning: "Vil du at jeg skal sende en oppsummering via e-post?"
|
| 533 |
+
|
| 534 |
+
**Hovedmål**
|
| 535 |
+
Hver samtale må avsluttes med handling – konsultasjon, prosjektinitiering, kontakt eller oppfølging.
|
| 536 |
+
"""
|
| 537 |
+
|
| 538 |
+
# Append the critical language instruction at the end
|
| 539 |
+
return instructions + language_instruction
|
main.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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# example_usage.py
|
| 2 |
+
# import asyncio
|
| 3 |
+
# import traceback
|
| 4 |
+
# from agents import Runner, RunContextWrapper
|
| 5 |
+
# from agents.exceptions import InputGuardrailTripwireTriggered
|
| 6 |
+
# from openai.types.responses import ResponseTextDeltaEvent
|
| 7 |
+
# from chatbot.chatbot_agent import innscribe_assistant
|
| 8 |
+
|
| 9 |
+
# async def query_innscribe_bot(user_message: str, stream: bool = True):
|
| 10 |
+
# """
|
| 11 |
+
# Query the Innoscribe bot with optional streaming (ChatGPT-style chunk-by-chunk output).
|
| 12 |
+
|
| 13 |
+
# Args:
|
| 14 |
+
# user_message: The user's message/query
|
| 15 |
+
# stream: If True, stream responses chunk by chunk like ChatGPT. If False, wait for complete response.
|
| 16 |
+
|
| 17 |
+
# Returns:
|
| 18 |
+
# The final output from the agent
|
| 19 |
+
# """
|
| 20 |
+
# try:
|
| 21 |
+
# ctx = RunContextWrapper(context={})
|
| 22 |
+
|
| 23 |
+
# if stream:
|
| 24 |
+
# # ChatGPT-style streaming: clean output, text appears chunk by chunk
|
| 25 |
+
# result = Runner.run_streamed(
|
| 26 |
+
# innscribe_assistant,
|
| 27 |
+
# input=user_message,
|
| 28 |
+
# context=ctx.context
|
| 29 |
+
# )
|
| 30 |
+
|
| 31 |
+
# # Stream text chunk by chunk in real-time (like ChatGPT)
|
| 32 |
+
# async for event in result.stream_events():
|
| 33 |
+
# if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
|
| 34 |
+
# delta = event.data.delta
|
| 35 |
+
# if delta:
|
| 36 |
+
# # Print each chunk immediately as it arrives (ChatGPT-style)
|
| 37 |
+
# print(delta, end="", flush=True)
|
| 38 |
+
|
| 39 |
+
# print("\n") # New line after streaming completes
|
| 40 |
+
# return result.final_output
|
| 41 |
+
# else:
|
| 42 |
+
# # Non-streaming mode: wait for complete response
|
| 43 |
+
# response = await Runner.run(
|
| 44 |
+
# innscribe_assistant,
|
| 45 |
+
# input=user_message,
|
| 46 |
+
# context=ctx.context
|
| 47 |
+
# )
|
| 48 |
+
# return response.final_output
|
| 49 |
+
|
| 50 |
+
# except InputGuardrailTripwireTriggered as e:
|
| 51 |
+
# print(f"\n⚠️ Guardrail blocked the query: {e}")
|
| 52 |
+
# if hasattr(e, 'result') and hasattr(e.result, 'output_info'):
|
| 53 |
+
# print(f"Guardrail reason: {e.result.output_info}")
|
| 54 |
+
# print("The query was determined to be unrelated to Innoscribe services.")
|
| 55 |
+
# return None
|
| 56 |
+
# except Exception as e:
|
| 57 |
+
# print(f"\n❌ Error: {e}")
|
| 58 |
+
# print(traceback.format_exc())
|
| 59 |
+
# raise
|
| 60 |
+
|
| 61 |
+
# async def interactive_chat():
|
| 62 |
+
# """
|
| 63 |
+
# Interactive ChatGPT-style conversation loop.
|
| 64 |
+
# Type 'exit', 'quit', or 'bye' to end the conversation.
|
| 65 |
+
# """
|
| 66 |
+
# print("=" * 60)
|
| 67 |
+
# print("🤖 Innoscribe Assistant - ChatGPT-style Chat")
|
| 68 |
+
# print("Type 'exit', 'quit', or 'bye' to end the conversation")
|
| 69 |
+
# print("=" * 60)
|
| 70 |
+
# print()
|
| 71 |
+
|
| 72 |
+
# while True:
|
| 73 |
+
# try:
|
| 74 |
+
# user_message = input("👤 You: ").strip()
|
| 75 |
+
|
| 76 |
+
# # Check for exit commands
|
| 77 |
+
# if user_message.lower() in ['exit', 'quit', 'bye', '']:
|
| 78 |
+
# print("\n👋 Goodbye! Have a great day!")
|
| 79 |
+
# break
|
| 80 |
+
|
| 81 |
+
# # Display assistant prefix and stream response
|
| 82 |
+
# print("🤖 Assistant: ", end="", flush=True)
|
| 83 |
+
|
| 84 |
+
# # Stream response chunk by chunk (ChatGPT-style)
|
| 85 |
+
# response = await query_innscribe_bot(user_message, stream=True)
|
| 86 |
+
|
| 87 |
+
# print() # Empty line between messages
|
| 88 |
+
|
| 89 |
+
# except KeyboardInterrupt:
|
| 90 |
+
# print("\n\n👋 Conversation interrupted. Goodbye!")
|
| 91 |
+
# break
|
| 92 |
+
# except Exception as e:
|
| 93 |
+
# print(f"\n❌ Error: {e}")
|
| 94 |
+
# print("Please try again or type 'exit' to quit.\n")
|
| 95 |
+
|
| 96 |
+
# async def main():
|
| 97 |
+
# try:
|
| 98 |
+
# # Option 1: Single message example (ChatGPT-style streaming)
|
| 99 |
+
# user_message = "Hello, how can I help you?"
|
| 100 |
+
|
| 101 |
+
# print(f"👤 You: {user_message}\n")
|
| 102 |
+
# print("🤖 Assistant: ", end="", flush=True)
|
| 103 |
+
|
| 104 |
+
# # Stream response chunk by chunk (ChatGPT-style)
|
| 105 |
+
# response = await query_innscribe_bot(user_message, stream=True)
|
| 106 |
+
|
| 107 |
+
# # Option 2: Uncomment below to use interactive chat mode instead
|
| 108 |
+
# # await interactive_chat()
|
| 109 |
+
|
| 110 |
+
# except Exception as e:
|
| 111 |
+
# print(f"\n❌ Error: {e}")
|
| 112 |
+
# print(traceback.format_exc())
|
| 113 |
+
|
| 114 |
+
# if __name__ == "__main__":
|
| 115 |
+
# try:
|
| 116 |
+
# asyncio.run(main())
|
| 117 |
+
# except Exception as e:
|
| 118 |
+
# print(f"Fatal error: {e}")
|
| 119 |
+
# print(traceback.format_exc())
|
| 120 |
+
# example_usage.py
|
| 121 |
+
import asyncio
|
| 122 |
+
import traceback
|
| 123 |
+
from agents import Runner, RunContextWrapper
|
| 124 |
+
from agents.exceptions import InputGuardrailTripwireTriggered
|
| 125 |
+
from openai.types.responses import ResponseTextDeltaEvent
|
| 126 |
+
from chatbot.chatbot_agent import launchlabs_assistant
|
| 127 |
+
|
| 128 |
+
async def query_launchlabs_bot(user_message: str, stream: bool = True):
|
| 129 |
+
"""
|
| 130 |
+
Query the Launchlabs bot with optional streaming (ChatGPT-style chunk-by-chunk output).
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
user_message: The user's message/query
|
| 134 |
+
stream: If True, stream responses chunk by chunk like ChatGPT. If False, wait for complete response.
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
The final output from the agent
|
| 138 |
+
"""
|
| 139 |
+
try:
|
| 140 |
+
ctx = RunContextWrapper(context={})
|
| 141 |
+
|
| 142 |
+
if stream:
|
| 143 |
+
# ChatGPT-style streaming: clean output, text appears chunk by chunk
|
| 144 |
+
result = Runner.run_streamed(
|
| 145 |
+
launchlabs_assistant,
|
| 146 |
+
input=user_message,
|
| 147 |
+
context=ctx.context
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Stream text chunk by chunk in real-time (like ChatGPT)
|
| 151 |
+
async for event in result.stream_events():
|
| 152 |
+
if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
|
| 153 |
+
delta = event.data.delta
|
| 154 |
+
if delta:
|
| 155 |
+
# Print each chunk immediately as it arrives (ChatGPT-style)
|
| 156 |
+
print(delta, end="", flush=True)
|
| 157 |
+
|
| 158 |
+
print("\n") # New line after streaming completes
|
| 159 |
+
return result.final_output
|
| 160 |
+
else:
|
| 161 |
+
# Non-streaming mode: wait for complete response
|
| 162 |
+
response = await Runner.run(
|
| 163 |
+
launchlabs_assistant,
|
| 164 |
+
input=user_message,
|
| 165 |
+
context=ctx.context
|
| 166 |
+
)
|
| 167 |
+
return response.final_output
|
| 168 |
+
|
| 169 |
+
except InputGuardrailTripwireTriggered as e:
|
| 170 |
+
print(f"\n⚠️ Guardrail blocked the query: {e}")
|
| 171 |
+
if hasattr(e, 'result') and hasattr(e.result, 'output_info'):
|
| 172 |
+
print(f"Guardrail reason: {e.result.output_info}")
|
| 173 |
+
print("The query was determined to be unrelated to Launchlabs services.")
|
| 174 |
+
return None
|
| 175 |
+
except Exception as e:
|
| 176 |
+
print(f"\n❌ Error: {e}")
|
| 177 |
+
print(traceback.format_exc())
|
| 178 |
+
raise
|
| 179 |
+
|
| 180 |
+
async def interactive_chat():
|
| 181 |
+
"""
|
| 182 |
+
Interactive ChatGPT-style conversation loop.
|
| 183 |
+
Type 'exit', 'quit', or 'bye' to end the conversation.
|
| 184 |
+
"""
|
| 185 |
+
print("=" * 60)
|
| 186 |
+
print("🤖 Launchlabs Assistant - ChatGPT-style Chat")
|
| 187 |
+
print("Type 'exit', 'quit', or 'bye' to end the conversation")
|
| 188 |
+
print("=" * 60)
|
| 189 |
+
print()
|
| 190 |
+
|
| 191 |
+
while True:
|
| 192 |
+
try:
|
| 193 |
+
user_message = input("👤 You: ").strip()
|
| 194 |
+
|
| 195 |
+
# Check for exit commands
|
| 196 |
+
if user_message.lower() in ['exit', 'quit', 'bye', '']:
|
| 197 |
+
print("\n👋 Goodbye! Have a great day!")
|
| 198 |
+
break
|
| 199 |
+
|
| 200 |
+
# Display assistant prefix and stream response
|
| 201 |
+
print("🤖 Assistant: ", end="", flush=True)
|
| 202 |
+
|
| 203 |
+
# Stream response chunk by chunk (ChatGPT-style)
|
| 204 |
+
response = await query_launchlabs_bot(user_message, stream=True)
|
| 205 |
+
|
| 206 |
+
print() # Empty line between messages
|
| 207 |
+
|
| 208 |
+
except KeyboardInterrupt:
|
| 209 |
+
print("\n\n👋 Conversation interrupted. Goodbye!")
|
| 210 |
+
break
|
| 211 |
+
except Exception as e:
|
| 212 |
+
print(f"\n❌ Error: {e}")
|
| 213 |
+
print("Please try again or type 'exit' to quit.\n")
|
| 214 |
+
|
| 215 |
+
async def main():
|
| 216 |
+
try:
|
| 217 |
+
# Option 1: Single message example (ChatGPT-style streaming)
|
| 218 |
+
user_message = "Hello, tell me about your services."
|
| 219 |
+
|
| 220 |
+
print(f"👤 You: {user_message}\n")
|
| 221 |
+
print("🤖 Assistant: ", end="", flush=True)
|
| 222 |
+
|
| 223 |
+
# Stream response chunk by chunk (ChatGPT-style)
|
| 224 |
+
response = await query_launchlabs_bot(user_message, stream=True)
|
| 225 |
+
|
| 226 |
+
# Option 2: Uncomment below to use interactive chat mode instead
|
| 227 |
+
# await interactive_chat()
|
| 228 |
+
|
| 229 |
+
except Exception as e:
|
| 230 |
+
print(f"\n❌ Error: {e}")
|
| 231 |
+
print(traceback.format_exc())
|
| 232 |
+
|
| 233 |
+
if __name__ == "__main__":
|
| 234 |
+
try:
|
| 235 |
+
asyncio.run(main())
|
| 236 |
+
except Exception as e:
|
| 237 |
+
print(f"Fatal error: {e}")
|
| 238 |
+
print(traceback.format_exc())
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
openai-agents
|
| 4 |
+
python-dotenv
|
| 5 |
+
slowapi
|
| 6 |
+
firebase-admin
|
| 7 |
+
python-docx
|
| 8 |
+
PyPDF2
|
| 9 |
+
resend
|
schema/__pycache__/chatbot_schema.cpython-312.pyc
ADDED
|
Binary file (459 Bytes). View file
|
|
|
schema/chatbot_schema.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
|
| 3 |
+
class OutputType(BaseModel):
|
| 4 |
+
is_query_about_launchlabs: bool
|
| 5 |
+
reason: str
|
serviceAccount.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"type": "service_account",
|
| 3 |
+
"project_id": "launchlab-b7060",
|
| 4 |
+
"private_key_id": "b21d53c46910558a0c91d86b81dfe067964bb599",
|
| 5 |
+
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCmkEXBznyostUD\niyFPxS6cGx16lJymmy+o8tJgGUpi9sLMeaPr7Q3VZuynY0nMgWNvXj6epI1iqjkz\nVB223bLm/KW63jLs3mQOeHu+qM8oBsTkd3nVz7fBLBY/8uw+JXMwC4R+pWu1APIl\n7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QlYb9fw6EovFmZiFm9P8Uw7oasGs8LNX3KN+bcmbCaeQKBgEya\nH9NN6jUFh4i2EfuH5f+IA9hfno9zwkxnx02XYguIJCkWcETurfIRpWmA7sUtl3we\nQ5bxj+8osaDFkFUYAy0dW8YIWlMQiGsIaBwqiqZh6VMy3DzcAnVGqE4U9Q/TpCyQ\ns8Ie6hz1VQnJejKdG5BJlvufC5iSmcOsqBcorMtrAoGBALAmXxzkJOgh4GrJYTbk\n0ayL0mZouT28/Va+9/TtVaFqcvIZsEf5klrQnXsgT4L1ppMaxFtL+TiJ29sVJ8T7\nhtQ+f4yG/ypCXWjoByxUCAvJgiVUXtWNeaycPvY46+r6h2e8s4j7+DPjRpAjv04B\nOIYcdOr138L3Im4GDWOkVZos\n-----END PRIVATE KEY-----\n",
|
| 6 |
+
"client_email": "firebase-adminsdk-fbsvc@launchlab-b7060.iam.gserviceaccount.com",
|
| 7 |
+
"client_id": "117164160316374787162",
|
| 8 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 9 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
| 10 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
| 11 |
+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40launchlab-b7060.iam.gserviceaccount.com",
|
| 12 |
+
"universe_domain": "googleapis.com"
|
| 13 |
+
}
|
sessions/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Sessions module for the Launchlabs chatbot."""
|
sessions/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (196 Bytes). View file
|
|
|
sessions/__pycache__/session_manager.cpython-312.pyc
ADDED
|
Binary file (7.22 kB). View file
|
|
|
sessions/session_manager.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 1 |
+
"""
|
| 2 |
+
Session Manager for Launchlabs Chatbot
|
| 3 |
+
Handles chat history persistence using Firebase Firestore
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import uuid
|
| 7 |
+
import time
|
| 8 |
+
from datetime import datetime, timedelta
|
| 9 |
+
from typing import List, Dict, Optional, Any
|
| 10 |
+
from tools.firebase_config import db
|
| 11 |
+
|
| 12 |
+
class SessionManager:
|
| 13 |
+
"""Manages chat sessions and history using Firebase Firestore"""
|
| 14 |
+
|
| 15 |
+
def __init__(self, collection_name: str = "chat_sessions"):
|
| 16 |
+
"""
|
| 17 |
+
Initialize the session manager
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
collection_name: Name of the Firestore collection to store sessions
|
| 21 |
+
"""
|
| 22 |
+
self.collection_name = collection_name
|
| 23 |
+
self.sessions_collection = db.collection(collection_name) if db else None
|
| 24 |
+
|
| 25 |
+
def create_session(self, user_id: Optional[str] = None) -> str:
|
| 26 |
+
"""
|
| 27 |
+
Create a new chat session
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
user_id: Optional user identifier
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
Session ID
|
| 34 |
+
"""
|
| 35 |
+
if not self.sessions_collection:
|
| 36 |
+
return str(uuid.uuid4())
|
| 37 |
+
|
| 38 |
+
session_id = str(uuid.uuid4())
|
| 39 |
+
session_data = {
|
| 40 |
+
"session_id": session_id,
|
| 41 |
+
"user_id": user_id or "anonymous",
|
| 42 |
+
"created_at": datetime.utcnow(),
|
| 43 |
+
"last_active": datetime.utcnow(),
|
| 44 |
+
"history": [],
|
| 45 |
+
"expired": False
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
self.sessions_collection.document(session_id).set(session_data)
|
| 50 |
+
return session_id
|
| 51 |
+
except Exception as e:
|
| 52 |
+
print(f"Warning: Failed to create session in Firestore: {e}")
|
| 53 |
+
return session_id
|
| 54 |
+
|
| 55 |
+
def get_session(self, session_id: str) -> Optional[Dict[str, Any]]:
|
| 56 |
+
"""
|
| 57 |
+
Retrieve a session by ID
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
session_id: Session identifier
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
Session data or None if not found
|
| 64 |
+
"""
|
| 65 |
+
if not self.sessions_collection:
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
try:
|
| 69 |
+
doc = self.sessions_collection.document(session_id).get()
|
| 70 |
+
if doc.exists:
|
| 71 |
+
session_data = doc.to_dict()
|
| 72 |
+
# Convert timestamp strings back to datetime objects
|
| 73 |
+
if "created_at" in session_data and isinstance(session_data["created_at"], str):
|
| 74 |
+
session_data["created_at"] = datetime.fromisoformat(session_data["created_at"].replace("Z", "+00:00"))
|
| 75 |
+
if "last_active" in session_data and isinstance(session_data["last_active"], str):
|
| 76 |
+
session_data["last_active"] = datetime.fromisoformat(session_data["last_active"].replace("Z", "+00:00"))
|
| 77 |
+
return session_data
|
| 78 |
+
return None
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print(f"Warning: Failed to retrieve session from Firestore: {e}")
|
| 81 |
+
return None
|
| 82 |
+
|
| 83 |
+
def add_message_to_history(self, session_id: str, role: str, content: str) -> bool:
|
| 84 |
+
"""
|
| 85 |
+
Add a message to the chat history
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
session_id: Session identifier
|
| 89 |
+
role: Role of the message sender (user/assistant)
|
| 90 |
+
content: Message content
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
True if successful, False otherwise
|
| 94 |
+
"""
|
| 95 |
+
if not self.sessions_collection:
|
| 96 |
+
return False
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
# Get current session data
|
| 100 |
+
session_doc = self.sessions_collection.document(session_id)
|
| 101 |
+
session_data = session_doc.get().to_dict()
|
| 102 |
+
|
| 103 |
+
if not session_data:
|
| 104 |
+
return False
|
| 105 |
+
|
| 106 |
+
# Add new message to history
|
| 107 |
+
message = {
|
| 108 |
+
"role": role,
|
| 109 |
+
"content": content,
|
| 110 |
+
"timestamp": datetime.utcnow()
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
# Update session data
|
| 114 |
+
session_data["history"].append(message)
|
| 115 |
+
session_data["last_active"] = datetime.utcnow()
|
| 116 |
+
|
| 117 |
+
# Keep only the last 20 messages to prevent document bloat
|
| 118 |
+
if len(session_data["history"]) > 20:
|
| 119 |
+
session_data["history"] = session_data["history"][-20:]
|
| 120 |
+
|
| 121 |
+
# Update in Firestore
|
| 122 |
+
session_doc.update({
|
| 123 |
+
"history": session_data["history"],
|
| 124 |
+
"last_active": session_data["last_active"]
|
| 125 |
+
})
|
| 126 |
+
|
| 127 |
+
return True
|
| 128 |
+
except Exception as e:
|
| 129 |
+
print(f"Warning: Failed to add message to session history: {e}")
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
def get_session_history(self, session_id: str) -> List[Dict[str, str]]:
|
| 133 |
+
"""
|
| 134 |
+
Get the chat history for a session
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
session_id: Session identifier
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
List of message dictionaries
|
| 141 |
+
"""
|
| 142 |
+
session_data = self.get_session(session_id)
|
| 143 |
+
if session_data and "history" in session_data:
|
| 144 |
+
# Return only role and content for each message
|
| 145 |
+
return [{"role": msg["role"], "content": msg["content"]}
|
| 146 |
+
for msg in session_data["history"]]
|
| 147 |
+
return []
|
| 148 |
+
|
| 149 |
+
def cleanup_expired_sessions(self, expiry_hours: int = 24) -> int:
|
| 150 |
+
"""
|
| 151 |
+
Clean up expired sessions
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
expiry_hours: Number of hours after which sessions expire
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
Number of sessions cleaned up
|
| 158 |
+
"""
|
| 159 |
+
if not self.sessions_collection:
|
| 160 |
+
return 0
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
cutoff_time = datetime.utcnow() - timedelta(hours=expiry_hours)
|
| 164 |
+
expired_sessions = self.sessions_collection.where(
|
| 165 |
+
"last_active", "<", cutoff_time
|
| 166 |
+
).where("expired", "==", False).stream()
|
| 167 |
+
|
| 168 |
+
count = 0
|
| 169 |
+
for session in expired_sessions:
|
| 170 |
+
self.sessions_collection.document(session.id).update({
|
| 171 |
+
"expired": True
|
| 172 |
+
})
|
| 173 |
+
count += 1
|
| 174 |
+
|
| 175 |
+
return count
|
| 176 |
+
except Exception as e:
|
| 177 |
+
print(f"Warning: Failed to clean up expired sessions: {e}")
|
| 178 |
+
return 0
|
| 179 |
+
|
| 180 |
+
# Global session manager instance
|
| 181 |
+
session_manager = SessionManager()
|
tools/README.md
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Document Reader Tools
|
| 2 |
+
|
| 3 |
+
This module provides function tools for your Innoscribe chatbot agent to read documents from local files (PDF, DOCX) and Firebase Firestore.
|
| 4 |
+
|
| 5 |
+
## Features
|
| 6 |
+
|
| 7 |
+
- **Read Local Documents**: Automatically reads `data.docx` and any PDF files from the root directory
|
| 8 |
+
- **Read Firestore Documents**: Reads documents from the `data` collection in Firebase Firestore
|
| 9 |
+
- **Auto Mode**: Tries local files first, then falls back to Firestore
|
| 10 |
+
- **List Available Documents**: Shows all available documents from both sources
|
| 11 |
+
|
| 12 |
+
## Setup
|
| 13 |
+
|
| 14 |
+
### 1. Install Dependencies
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
pip install -r requirements.txt
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
Required packages:
|
| 21 |
+
- `firebase-admin` - For Firebase Firestore integration
|
| 22 |
+
- `python-docx` - For reading DOCX files
|
| 23 |
+
- `PyPDF2` - For reading PDF files
|
| 24 |
+
|
| 25 |
+
### 2. Firebase Configuration
|
| 26 |
+
|
| 27 |
+
Make sure your `serviceAccount.json` file is in the root directory of the project. This file is used to authenticate with Firebase.
|
| 28 |
+
|
| 29 |
+
### 3. Document Storage
|
| 30 |
+
|
| 31 |
+
**Local Documents:**
|
| 32 |
+
- Place your `data.docx` file in the root directory
|
| 33 |
+
- Place any PDF files in the root directory
|
| 34 |
+
|
| 35 |
+
**Firestore Documents:**
|
| 36 |
+
- Upload documents to the `data` collection in Firebase Firestore
|
| 37 |
+
- Each document should have a `content`, `text`, or `data` field containing the text
|
| 38 |
+
- Optionally include a `name` field for identification
|
| 39 |
+
|
| 40 |
+
## Usage
|
| 41 |
+
|
| 42 |
+
### Basic Integration with Agent
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
from agents import Agent
|
| 46 |
+
from config.chabot_config import model
|
| 47 |
+
from instructions.chatbot_instructions import innscribe_dynamic_instructions
|
| 48 |
+
from tools.document_reader_tool import read_document_data, list_available_documents
|
| 49 |
+
|
| 50 |
+
# Create agent with document reading tools
|
| 51 |
+
innscribe_assistant = Agent(
|
| 52 |
+
name="Innoscribe Assistant",
|
| 53 |
+
instructions=innscribe_dynamic_instructions,
|
| 54 |
+
model=model,
|
| 55 |
+
tools=[read_document_data, list_available_documents]
|
| 56 |
+
)
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
### Tool Functions
|
| 60 |
+
|
| 61 |
+
#### `read_document_data(query: str, source: str = "auto")`
|
| 62 |
+
|
| 63 |
+
Reads and searches for information from documents.
|
| 64 |
+
|
| 65 |
+
**Parameters:**
|
| 66 |
+
- `query`: The search query or topic to look for
|
| 67 |
+
- `source`: Where to read from - `"local"`, `"firestore"`, or `"auto"` (default)
|
| 68 |
+
|
| 69 |
+
**Returns:** Formatted content from matching documents
|
| 70 |
+
|
| 71 |
+
**Example:**
|
| 72 |
+
```python
|
| 73 |
+
result = read_document_data("product information", source="auto")
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
#### `list_available_documents()`
|
| 77 |
+
|
| 78 |
+
Lists all available documents from both local storage and Firestore.
|
| 79 |
+
|
| 80 |
+
**Returns:** Formatted list of available documents
|
| 81 |
+
|
| 82 |
+
**Example:**
|
| 83 |
+
```python
|
| 84 |
+
docs = list_available_documents()
|
| 85 |
+
print(docs)
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
## How It Works
|
| 89 |
+
|
| 90 |
+
### Automatic Fallback Strategy
|
| 91 |
+
|
| 92 |
+
1. **Auto Mode (default)**:
|
| 93 |
+
- First tries to read from local files (data.docx, *.pdf)
|
| 94 |
+
- If no data found, tries Firebase Firestore
|
| 95 |
+
- Returns combined results if both sources have data
|
| 96 |
+
|
| 97 |
+
2. **Local Mode**:
|
| 98 |
+
- Only reads from local files
|
| 99 |
+
|
| 100 |
+
3. **Firestore Mode**:
|
| 101 |
+
- Only reads from Firebase Firestore
|
| 102 |
+
|
| 103 |
+
### Agent Behavior
|
| 104 |
+
|
| 105 |
+
When a user asks a question requiring document data, the agent will:
|
| 106 |
+
|
| 107 |
+
1. Detect that document information is needed
|
| 108 |
+
2. Automatically call `read_document_data()` with the relevant query
|
| 109 |
+
3. Search through local files and/or Firestore
|
| 110 |
+
4. Return the relevant information to answer the user's question
|
| 111 |
+
|
| 112 |
+
## Example User Interactions
|
| 113 |
+
|
| 114 |
+
**User:** "What information do you have about our company?"
|
| 115 |
+
- Agent calls: `read_document_data("company information")`
|
| 116 |
+
- Returns relevant content from documents
|
| 117 |
+
|
| 118 |
+
**User:** "List all available documents"
|
| 119 |
+
- Agent calls: `list_available_documents()`
|
| 120 |
+
- Returns formatted list of all documents
|
| 121 |
+
|
| 122 |
+
**User:** "Tell me about product pricing"
|
| 123 |
+
- Agent calls: `read_document_data("product pricing")`
|
| 124 |
+
- Returns pricing information from documents
|
| 125 |
+
|
| 126 |
+
## Firestore Collection Structure
|
| 127 |
+
|
| 128 |
+
Your Firestore `data` collection should have documents structured like:
|
| 129 |
+
|
| 130 |
+
```json
|
| 131 |
+
{
|
| 132 |
+
"name": "Product Catalog",
|
| 133 |
+
"content": "This is the product information...",
|
| 134 |
+
"type": "product",
|
| 135 |
+
"created_at": "2024-01-01"
|
| 136 |
+
}
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
Or simply:
|
| 140 |
+
|
| 141 |
+
```json
|
| 142 |
+
{
|
| 143 |
+
"text": "Document content here..."
|
| 144 |
+
}
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
The tool will look for `content`, `text`, or `data` fields to extract the document text.
|
| 148 |
+
|
| 149 |
+
## Testing
|
| 150 |
+
|
| 151 |
+
Run the example usage file to test the tools:
|
| 152 |
+
|
| 153 |
+
```bash
|
| 154 |
+
python tools/example_usage.py
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
## Troubleshooting
|
| 158 |
+
|
| 159 |
+
**Firebase not initializing:**
|
| 160 |
+
- Check that `serviceAccount.json` exists in the root directory
|
| 161 |
+
- Verify the service account has Firestore permissions
|
| 162 |
+
|
| 163 |
+
**Documents not found:**
|
| 164 |
+
- Verify `data.docx` or PDF files exist in the root directory
|
| 165 |
+
- Check Firestore collection is named `data`
|
| 166 |
+
- Ensure documents have `content`, `text`, or `data` fields
|
| 167 |
+
|
| 168 |
+
**Import errors:**
|
| 169 |
+
- Make sure all dependencies are installed: `pip install -r requirements.txt`
|
tools/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Tools module for the Innoscribe chatbot agent."""
|
tools/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (216 Bytes). View file
|
|
|
tools/__pycache__/document_reader_tool.cpython-312.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
tools/__pycache__/firebase_config.cpython-312.pyc
ADDED
|
Binary file (1.22 kB). View file
|
|
|
tools/document_reader_tool.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import requests
|
| 4 |
+
import logging
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from agents import function_tool
|
| 7 |
+
from docx import Document
|
| 8 |
+
import PyPDF2
|
| 9 |
+
from .firebase_config import db
|
| 10 |
+
|
| 11 |
+
# Set up logging
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@function_tool
|
| 16 |
+
def read_document_data(query: str, source: str = "auto") -> str:
|
| 17 |
+
"""
|
| 18 |
+
Read and search for information from documents stored locally or in Firebase Firestore.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
query: The search query or topic to look for in the documents
|
| 22 |
+
source: Data source - "local" for local files, "firestore" for Firebase, or "auto" to try both
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
The relevant content from the document(s) matching the query
|
| 26 |
+
"""
|
| 27 |
+
logger.info(f"TOOL CALL: read_document_data called with query='{query}', source='{source}'")
|
| 28 |
+
|
| 29 |
+
result = []
|
| 30 |
+
|
| 31 |
+
# Try local files first if source is "local" or "auto"
|
| 32 |
+
if source in ["local", "auto"]:
|
| 33 |
+
local_content = _read_local_documents(query)
|
| 34 |
+
if local_content:
|
| 35 |
+
result.append(f"=== Local Documents ===\n{local_content}")
|
| 36 |
+
|
| 37 |
+
# Try Firestore if source is "firestore" or "auto" (and local didn't return results)
|
| 38 |
+
if source in ["firestore", "auto"] and (not result or source == "firestore"):
|
| 39 |
+
firestore_content = _read_firestore_documents(query)
|
| 40 |
+
if firestore_content:
|
| 41 |
+
result.append(f"=== Firestore Documents ===\n{firestore_content}")
|
| 42 |
+
|
| 43 |
+
if result:
|
| 44 |
+
response = "\n\n".join(result)
|
| 45 |
+
logger.info(f"TOOL RESULT: read_document_data found {len(result)} result(s)")
|
| 46 |
+
return response
|
| 47 |
+
else:
|
| 48 |
+
response = f"No relevant information found for query: '{query}'. Please check if documents are available."
|
| 49 |
+
logger.info(f"TOOL RESULT: read_document_data found no results for query='{query}'")
|
| 50 |
+
return response
|
| 51 |
+
|
| 52 |
+
def _read_local_documents(query: str) -> Optional[str]:
|
| 53 |
+
"""Read from local PDF and DOCX files in the root directory."""
|
| 54 |
+
root_dir = os.path.dirname(os.path.dirname(__file__))
|
| 55 |
+
content_parts = []
|
| 56 |
+
|
| 57 |
+
# Try to read DOCX file
|
| 58 |
+
docx_path = os.path.join(root_dir, "data.docx")
|
| 59 |
+
if os.path.exists(docx_path):
|
| 60 |
+
try:
|
| 61 |
+
doc = Document(docx_path)
|
| 62 |
+
full_text = []
|
| 63 |
+
for paragraph in doc.paragraphs:
|
| 64 |
+
if paragraph.text.strip():
|
| 65 |
+
full_text.append(paragraph.text)
|
| 66 |
+
|
| 67 |
+
docx_content = "\n".join(full_text)
|
| 68 |
+
if docx_content:
|
| 69 |
+
content_parts.append(f"[From data.docx]\n{docx_content}")
|
| 70 |
+
except Exception as e:
|
| 71 |
+
content_parts.append(f"Error reading data.docx: {str(e)}")
|
| 72 |
+
|
| 73 |
+
# Try to read PDF files
|
| 74 |
+
for file in os.listdir(root_dir):
|
| 75 |
+
if file.endswith(".pdf"):
|
| 76 |
+
pdf_path = os.path.join(root_dir, file)
|
| 77 |
+
try:
|
| 78 |
+
with open(pdf_path, "rb") as pdf_file:
|
| 79 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
| 80 |
+
pdf_text = []
|
| 81 |
+
for page in pdf_reader.pages:
|
| 82 |
+
text = page.extract_text()
|
| 83 |
+
if text.strip():
|
| 84 |
+
pdf_text.append(text)
|
| 85 |
+
|
| 86 |
+
if pdf_text:
|
| 87 |
+
content_parts.append(f"[From {file}]\n" + "\n".join(pdf_text))
|
| 88 |
+
except Exception as e:
|
| 89 |
+
content_parts.append(f"Error reading {file}: {str(e)}")
|
| 90 |
+
|
| 91 |
+
return "\n\n".join(content_parts) if content_parts else None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _read_firestore_documents(query: str) -> Optional[str]:
|
| 95 |
+
"""Read documents from Firebase Firestore 'data' collection."""
|
| 96 |
+
if not db:
|
| 97 |
+
return "Firebase Firestore is not initialized. Please check your serviceAccount.json file."
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
# Query the 'data' collection
|
| 101 |
+
docs_ref = db.collection("data")
|
| 102 |
+
docs = docs_ref.stream()
|
| 103 |
+
|
| 104 |
+
content_parts = []
|
| 105 |
+
for doc in docs:
|
| 106 |
+
doc_data = doc.to_dict()
|
| 107 |
+
|
| 108 |
+
# Check if document field contains a URL to a file
|
| 109 |
+
document_url = doc_data.get("document")
|
| 110 |
+
|
| 111 |
+
if document_url:
|
| 112 |
+
# Download and read the document from URL
|
| 113 |
+
try:
|
| 114 |
+
doc_name = doc_data.get("name", doc.id)
|
| 115 |
+
content = _read_document_from_url(document_url, doc_name)
|
| 116 |
+
if content:
|
| 117 |
+
content_parts.append(f"[From Firestore: {doc_name}]\n{content}")
|
| 118 |
+
except Exception as e:
|
| 119 |
+
content_parts.append(f"[Error reading {doc.id}]: {str(e)}")
|
| 120 |
+
else:
|
| 121 |
+
# Fallback: Try to extract content from different possible field names
|
| 122 |
+
doc_content = (
|
| 123 |
+
doc_data.get("content") or
|
| 124 |
+
doc_data.get("text") or
|
| 125 |
+
doc_data.get("data")
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if doc_content:
|
| 129 |
+
doc_name = doc_data.get("name", doc.id)
|
| 130 |
+
content_parts.append(f"[From Firestore: {doc_name}]\n{doc_content}")
|
| 131 |
+
|
| 132 |
+
return "\n\n".join(content_parts) if content_parts else None
|
| 133 |
+
|
| 134 |
+
except Exception as e:
|
| 135 |
+
return f"Error reading from Firestore: {str(e)}"
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _read_document_from_url(url: str, doc_name: str) -> Optional[str]:
|
| 139 |
+
"""Download and read a document (DOCX or PDF) from a URL."""
|
| 140 |
+
try:
|
| 141 |
+
# Download the file from URL
|
| 142 |
+
response = requests.get(url, timeout=30)
|
| 143 |
+
response.raise_for_status()
|
| 144 |
+
|
| 145 |
+
# Determine file type from URL
|
| 146 |
+
if url.lower().endswith('.docx') or 'docx' in url.lower():
|
| 147 |
+
# Read DOCX from bytes
|
| 148 |
+
doc = Document(io.BytesIO(response.content))
|
| 149 |
+
full_text = []
|
| 150 |
+
for paragraph in doc.paragraphs:
|
| 151 |
+
if paragraph.text.strip():
|
| 152 |
+
full_text.append(paragraph.text)
|
| 153 |
+
return "\n".join(full_text)
|
| 154 |
+
|
| 155 |
+
elif url.lower().endswith('.pdf') or 'pdf' in url.lower():
|
| 156 |
+
# Read PDF from bytes
|
| 157 |
+
pdf_reader = PyPDF2.PdfReader(io.BytesIO(response.content))
|
| 158 |
+
pdf_text = []
|
| 159 |
+
for page in pdf_reader.pages:
|
| 160 |
+
text = page.extract_text()
|
| 161 |
+
if text.strip():
|
| 162 |
+
pdf_text.append(text)
|
| 163 |
+
return "\n".join(pdf_text)
|
| 164 |
+
|
| 165 |
+
else:
|
| 166 |
+
return f"Unsupported file type for URL: {url}"
|
| 167 |
+
|
| 168 |
+
except Exception as e:
|
| 169 |
+
raise Exception(f"Failed to download/read document from {url}: {str(e)}")
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@function_tool
|
| 173 |
+
def list_available_documents() -> str:
|
| 174 |
+
"""
|
| 175 |
+
List all available documents from both local storage and Firestore.
|
| 176 |
+
|
| 177 |
+
Returns:
|
| 178 |
+
A formatted list of available documents from all sources
|
| 179 |
+
"""
|
| 180 |
+
logger.info("TOOL CALL: list_available_documents called")
|
| 181 |
+
|
| 182 |
+
result = []
|
| 183 |
+
|
| 184 |
+
# List local documents
|
| 185 |
+
root_dir = os.path.dirname(os.path.dirname(__file__))
|
| 186 |
+
local_docs = []
|
| 187 |
+
|
| 188 |
+
if os.path.exists(os.path.join(root_dir, "data.docx")):
|
| 189 |
+
local_docs.append("- data.docx")
|
| 190 |
+
|
| 191 |
+
for file in os.listdir(root_dir):
|
| 192 |
+
if file.endswith(".pdf"):
|
| 193 |
+
local_docs.append(f"- {file}")
|
| 194 |
+
|
| 195 |
+
if local_docs:
|
| 196 |
+
result.append("=== Local Documents ===\n" + "\n".join(local_docs))
|
| 197 |
+
|
| 198 |
+
# List Firestore documents
|
| 199 |
+
if db:
|
| 200 |
+
try:
|
| 201 |
+
docs_ref = db.collection("data")
|
| 202 |
+
docs = docs_ref.stream()
|
| 203 |
+
firestore_docs = [f"- {doc.id}" for doc in docs]
|
| 204 |
+
|
| 205 |
+
if firestore_docs:
|
| 206 |
+
result.append("=== Firestore Documents ===\n" + "\n".join(firestore_docs))
|
| 207 |
+
except Exception as e:
|
| 208 |
+
result.append(f"Error listing Firestore documents: {str(e)}")
|
| 209 |
+
|
| 210 |
+
response = "\n\n".join(result) if result else "No documents found in any source."
|
| 211 |
+
logger.info(f"TOOL RESULT: list_available_documents found {len(result)} source(s) with documents")
|
| 212 |
+
return response
|
tools/example_usage.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Example usage of the document reader tools with the agent.
|
| 3 |
+
|
| 4 |
+
This file demonstrates how to integrate the document reading tools
|
| 5 |
+
with your Innoscribe chatbot agent.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from agents import Agent
|
| 9 |
+
from config.chabot_config import model
|
| 10 |
+
from instructions.chatbot_instructions import innscribe_dynamic_instructions
|
| 11 |
+
from guardrails.guardrails_input_function import guardrail_input_function
|
| 12 |
+
from tools.document_reader_tool import read_document_data, list_available_documents
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# Example 1: Agent with document reading capabilities
|
| 16 |
+
innscribe_assistant_with_docs = Agent(
|
| 17 |
+
name="Innoscribe Assistant with Document Access",
|
| 18 |
+
instructions=innscribe_dynamic_instructions,
|
| 19 |
+
model=model,
|
| 20 |
+
input_guardrails=[guardrail_input_function],
|
| 21 |
+
tools=[read_document_data, list_available_documents] # Add the document tools here
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Example 2: How the agent will use the tools
|
| 26 |
+
"""
|
| 27 |
+
When a user asks a question that requires information from documents:
|
| 28 |
+
|
| 29 |
+
User: "What information do you have about our products?"
|
| 30 |
+
|
| 31 |
+
The agent will automatically:
|
| 32 |
+
1. Try to read from local data.docx and any PDF files first
|
| 33 |
+
2. If not found or insufficient, try to read from Firebase Firestore
|
| 34 |
+
3. Return the relevant information
|
| 35 |
+
|
| 36 |
+
User: "List all available documents"
|
| 37 |
+
The agent will use list_available_documents() to show all docs
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Example 3: Manual tool usage (for testing)
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
# Test reading documents
|
| 44 |
+
print("Testing document reader tool...")
|
| 45 |
+
result = read_document_data("company information", source="auto")
|
| 46 |
+
print(result)
|
| 47 |
+
|
| 48 |
+
print("\n" + "="*50 + "\n")
|
| 49 |
+
|
| 50 |
+
# Test listing documents
|
| 51 |
+
print("Testing list documents tool...")
|
| 52 |
+
docs = list_available_documents()
|
| 53 |
+
print(docs)
|
tools/firebase_config.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import firebase_admin
|
| 3 |
+
from firebase_admin import credentials, firestore
|
| 4 |
+
|
| 5 |
+
# Initialize Firebase Admin SDK
|
| 6 |
+
def initialize_firebase():
|
| 7 |
+
"""Initialize Firebase Admin SDK with service account credentials."""
|
| 8 |
+
# Get the path to serviceAccount.json in the root directory
|
| 9 |
+
service_account_path = os.path.join(
|
| 10 |
+
os.path.dirname(os.path.dirname(__file__)),
|
| 11 |
+
"serviceAccount.json"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
# Check if Firebase is already initialized
|
| 15 |
+
if not firebase_admin._apps:
|
| 16 |
+
cred = credentials.Certificate(service_account_path)
|
| 17 |
+
firebase_admin.initialize_app(cred)
|
| 18 |
+
|
| 19 |
+
# Return Firestore client
|
| 20 |
+
return firestore.client()
|
| 21 |
+
|
| 22 |
+
# Create a global Firestore client instance
|
| 23 |
+
try:
|
| 24 |
+
db = initialize_firebase()
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"Warning: Failed to initialize Firebase: {e}")
|
| 27 |
+
db = None
|