File size: 16,336 Bytes
9178353 846f4fb 9178353 f73a254 4aab314 846f4fb 9178353 846f4fb 9178353 4aab314 5cb21e4 a79844e 4e5987e 4aab314 9178353 0990d2f 9178353 0990d2f 9178353 fdb085f 9ca0227 8b847a6 846f4fb 4aab314 846f4fb fdb085f 846f4fb a8fd0a9 fdb085f 846f4fb 4aab314 fdb085f 9178353 fdb085f 4aab314 846f4fb fdb085f 4aab314 9178353 846f4fb fdb085f 846f4fb 0990d2f fdb085f 4aab314 fdb085f 4aab314 846f4fb fdb085f 846f4fb fdb085f 9178353 4aab314 fdb085f 0990d2f 9178353 fdb085f 13046df fdb085f 13046df fdb085f 13046df 9178353 fdb085f 4aab314 9178353 a79844e 846f4fb a79844e 9178353 a79844e 9178353 4aab314 846f4fb fdb085f 9178353 fdb085f 4aab314 846f4fb fdb085f 846f4fb fdb085f 846f4fb fdb085f 846f4fb fdb085f d805a2c fdb085f db547a3 fdb085f 846f4fb fdb085f db547a3 fdb085f d805a2c fdb085f b5dd409 fdb085f 846f4fb fdb085f db547a3 846f4fb fdb085f 846f4fb 4aab314 846f4fb c92f85e 9178353 4aab314 a79844e 9178353 4aab314 13046df fdb085f 846f4fb 9ca0227 a79844e 846f4fb 9ca0227 846f4fb a79844e 8b847a6 a79844e 846f4fb fdb085f 846f4fb fdb085f 846f4fb fdb085f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
import os
import json
import asyncio
import requests
from datetime import datetime
from typing import List, Dict, Optional
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from openai import OpenAI
import logging
# --- Security Helper Functions ---
def verify_origin(request: Request):
"""Verify that the request comes from an allowed origin for /chat endpoint"""
origin = request.headers.get("origin")
referer = request.headers.get("referer")
allowed_origins = [
"https://chrunos.com",
"https://www.chrunos.com"
]
# Allow localhost for development (you can remove this in production)
if origin and any(origin.startswith(local) for local in ["http://localhost:", "http://127.0.0.1:"]):
return True
# Check origin header
if origin in allowed_origins:
return True
# Check referer header as fallback
if referer and any(referer.startswith(allowed) for allowed in allowed_origins):
return True
raise HTTPException(
status_code=403,
detail="Access denied: This endpoint is only accessible from chrunos.com"
)
# --- Configure Logging ---
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --- Load API Keys from Environment Variables ---
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
GOOGLE_CX = os.getenv("GOOGLE_CX")
LLM_API_KEY = os.getenv("LLM_API_KEY")
LLM_BASE_URL = os.getenv("LLM_BASE_URL", "https://api-15i2e8ze256bvfn6.aistudio-app.com/v1")
# --- Improved System Prompts ---
SYSTEM_PROMPT_WITH_SEARCH = """You are an intelligent AI assistant with access to real-time web search capabilities.
When you need current information, recent events, specific facts, or when the user's question would benefit from up-to-date information, use the google_search function.
**Use search for:**
- Recent news or events
- Current statistics or data
- Specific factual information you're unsure about
- Questions about things that may have changed recently
- When the user explicitly asks for current/recent information
**Response Guidelines:**
1. Always use the search tool when it would provide more accurate or current information
2. Synthesize information from multiple sources when available
3. Clearly indicate when information comes from search results
4. Provide comprehensive, well-structured answers
5. Cite sources appropriately with links.
6. If search results conflict with my knowledge, prioritize the search results.
Current date: {current_date}"""
SYSTEM_PROMPT_NO_SEARCH = """You are an intelligent AI assistant. Provide helpful, accurate, and comprehensive responses based on your training data.
Current date: {current_date}"""
# --- Optimized Web Search Tool ---
async def google_search_tool_async(query: str, num_results: int = 3) -> List[Dict]:
"""
Async Google Custom Search - reduced results for faster response
"""
if not GOOGLE_API_KEY or not GOOGLE_CX or not query.strip():
return []
logger.info(f"Executing search for: '{query}'")
search_url = "https://www.googleapis.com/customsearch/v1"
params = {
"key": GOOGLE_API_KEY,
"cx": GOOGLE_CX,
"q": query.strip(),
"num": min(num_results, 5),
"dateRestrict": "m3"
}
try:
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
None,
lambda: requests.get(search_url, params=params, timeout=10)
)
response.raise_for_status()
search_results = response.json()
if "items" not in search_results:
return []
parsed_results = []
for item in search_results.get("items", [])[:num_results]:
title = item.get("title", "").strip()
url = item.get("link", "").strip()
snippet = item.get("snippet", "").strip()
if title and url and snippet:
parsed_results.append({
"source_title": title,
"url": url,
"snippet": snippet,
"domain": url.split('/')[2] if '/' in url else url
})
logger.info(f"Retrieved {len(parsed_results)} search results")
return parsed_results
except Exception as e:
logger.error(f"Search error: {e}")
return []
def format_search_results_compact(search_results: List[Dict]) -> str:
"""Compact formatting for faster processing"""
if not search_results:
return "No search results found."
formatted = ["Search Results:"]
for i, result in enumerate(search_results, 1):
formatted.append(f"\n{i}. {result['source_title']}")
formatted.append(f" Source: {result['domain']}")
formatted.append(f" Content: {result['snippet']}")
return "\n".join(formatted)
# --- FastAPI Application Setup ---
app = FastAPI(title="Streaming AI Chatbot", version="2.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=[
"https://chrunos.com",
"https://www.chrunos.com",
"http://localhost:3000",
"http://localhost:8000",
],
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)
# --- OpenAI Client Initialization ---
if not LLM_API_KEY or not LLM_BASE_URL:
logger.error("LLM_API_KEY or LLM_BASE_URL not configured")
client = None
else:
client = OpenAI(api_key=LLM_API_KEY, base_url=LLM_BASE_URL)
logger.info("OpenAI client initialized successfully")
# --- Tool Definition ---
available_tools = [
{
"type": "function",
"function": {
"name": "google_search",
"description": "Search Google for current information, recent events, or specific facts. Use this when you need up-to-date information or when the user's question would benefit from current data.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query with relevant keywords"
}
},
"required": ["query"]
}
}
}
]
# --- Fixed Streaming Response Generator ---
async def generate_streaming_response(messages: List[Dict], use_search: bool, temperature: float):
"""Generate streaming response with optional search"""
try:
# Initial LLM call with streaming
llm_kwargs = {
"model": "unsloth/Qwen3-30B-A3B-GGUF",
"temperature": temperature,
"messages": messages,
"max_tokens": 2000,
"stream": True
}
if use_search:
llm_kwargs["tools"] = available_tools
llm_kwargs["tool_choice"] = "auto"
source_links = []
response_content = ""
tool_calls_data = []
current_tool_call = None
# First streaming call
stream = client.chat.completions.create(**llm_kwargs)
# Track if we're in the middle of collecting a tool call
collecting_tool_call = False
for chunk in stream:
delta = chunk.choices[0].delta
finish_reason = chunk.choices[0].finish_reason
# Handle content streaming
if delta.content:
content_chunk = delta.content
response_content += content_chunk
yield f"data: {json.dumps({'type': 'content', 'data': content_chunk})}\n\n"
# Handle tool calls - FIXED LOGIC
if delta.tool_calls:
collecting_tool_call = True
for tool_call in delta.tool_calls:
# Ensure we have enough slots in tool_calls_data
while len(tool_calls_data) <= tool_call.index:
tool_calls_data.append({
"id": None,
"function": {"name": None, "arguments": ""}
})
# Update the tool call data
if tool_call.id:
tool_calls_data[tool_call.index]["id"] = tool_call.id
if tool_call.function and tool_call.function.name:
tool_calls_data[tool_call.index]["function"]["name"] = tool_call.function.name
if tool_call.function and tool_call.function.arguments:
tool_calls_data[tool_call.index]["function"]["arguments"] += tool_call.function.arguments
# Check if we've finished collecting tool calls
if finish_reason in ["tool_calls", "stop"] and collecting_tool_call:
break
# Process tool calls if any were collected
processed_any_tools = False
if tool_calls_data and any(tc.get("id") and tc.get("function", {}).get("name") for tc in tool_calls_data):
yield f"data: {json.dumps({'type': 'status', 'data': 'Searching...'})}\n\n"
tool_responses = []
# Process each tool call
for tool_call in tool_calls_data:
if not tool_call.get("id") or not tool_call.get("function", {}).get("name"):
continue
function_name = tool_call["function"]["name"]
if function_name == "google_search":
try:
args = json.loads(tool_call["function"]["arguments"])
query = args.get("query", "").strip()
if query:
logger.info(f"Executing search with query: {query}")
search_results = await google_search_tool_async(query)
if search_results:
processed_any_tools = True
# Collect source links
for result in search_results:
source_links.append({
"title": result["source_title"],
"url": result["url"],
"domain": result["domain"]
})
# Format results for the model
search_context = format_search_results_compact(search_results)
tool_responses.append({
"tool_call_id": tool_call["id"],
"role": "tool",
"content": search_context
})
else:
tool_responses.append({
"tool_call_id": tool_call["id"],
"role": "tool",
"content": "No search results found."
})
except json.JSONDecodeError as e:
logger.error(f"Failed to parse tool arguments: {e}")
tool_responses.append({
"tool_call_id": tool_call["id"],
"role": "tool",
"content": "Error: Invalid search query format."
})
except Exception as e:
logger.error(f"Search tool error: {e}")
tool_responses.append({
"tool_call_id": tool_call["id"],
"role": "tool",
"content": f"Search error: {str(e)}"
})
# If we have tool responses, make a second call to get the final response
if tool_responses:
yield f"data: {json.dumps({'type': 'status', 'data': 'Generating response...'})}\n\n"
# Add tool call and tool response messages
final_messages = messages.copy()
# Add the assistant's tool call message
assistant_message = {
"role": "assistant",
"content": response_content if response_content else None,
"tool_calls": [
{
"id": tc["id"],
"type": "function",
"function": {
"name": tc["function"]["name"],
"arguments": tc["function"]["arguments"]
}
}
for tc in tool_calls_data if tc.get("id") and tc.get("function", {}).get("name")
]
}
final_messages.append(assistant_message)
# Add tool response messages
final_messages.extend(tool_responses)
# Generate final response
final_stream = client.chat.completions.create(
model="unsloth/Qwen3-30B-A3B-GGUF",
temperature=temperature,
messages=final_messages,
max_tokens=2000,
stream=True
)
for chunk in final_stream:
if chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
yield f"data: {json.dumps({'type': 'content', 'data': content})}\n\n"
# Send sources and completion
if source_links:
yield f"data: {json.dumps({'type': 'sources', 'data': source_links})}\n\n"
yield f"data: {json.dumps({'type': 'done', 'data': {'search_used': processed_any_tools}})}\n\n"
except Exception as e:
logger.error(f"Streaming error: {e}")
yield f"data: {json.dumps({'type': 'error', 'data': str(e)})}\n\n"
# --- Streaming Chat Endpoint ---
@app.post("/chat/stream")
async def chat_stream_endpoint(request: Request, _: None = Depends(verify_origin)):
if not client:
raise HTTPException(status_code=500, detail="LLM client not configured")
try:
data = await request.json()
user_message = data.get("message", "").strip()
use_search = data.get("use_search", False)
temperature = max(0, min(2, data.get("temperature", 0.7)))
conversation_history = data.get("history", [])
user_prompt = data.get("system_prompt")
if not user_message:
raise HTTPException(status_code=400, detail="No message provided")
# Prepare messages
current_date = datetime.now().strftime("%Y-%m-%d")
system_content = (SYSTEM_PROMPT_WITH_SEARCH if use_search else user_prompt#SYSTEM_PROMPT_NO_SEARCH
).format(current_date=current_date)
messages = [{"role": "system", "content": system_content}] + conversation_history + [{"role": "user", "content": user_message}]
logger.info(f"Stream request - search: {use_search}, temp: {temperature}, message: {user_message[:100]}...")
return StreamingResponse(
generate_streaming_response(messages, use_search, temperature),
media_type="text/plain",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no"
}
)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
except Exception as e:
logger.error(f"Stream endpoint error: {e}")
raise HTTPException(status_code=500, detail=str(e)) |