feat: enhance Azure OpenAI support in configuration and agent classes

This commit is contained in:
Scarlet Moore
2026-01-09 14:11:17 +00:00
parent 4d8f6bcd9b
commit de0e2f27fd
8 changed files with 152 additions and 155 deletions

View File

@@ -132,7 +132,7 @@ TTS_MODEL=
# TTS API endpoint URL
# - OpenAI: https://api.openai.com/v1
# - Azure OpenAI: https://{your-resource}.openai.azure.com/
# - Azure OpenAI: https://{your-resource}.openai.azure.com/
# (Note: For TTS on Azure, use the base resource URL)
TTS_URL=

View File

@@ -353,12 +353,13 @@ class NarratorAgent:
try:
# Check for Azure OpenAI TTS
import os
from openai import AsyncAzureOpenAI
binding = os.getenv("TTS_BINDING", "openai")
api_version = self.tts_config.get("api_version")
# Only use Azure client if binding is explicitly Azure,
# Only use Azure client if binding is explicitly Azure,
# OR if binding is generic 'openai' but an Azure-specific api_version is present.
if binding == "azure_openai" or (binding == "openai" and api_version):
client = AsyncAzureOpenAI(

View File

@@ -13,7 +13,7 @@ import sys
from typing import Any
from dotenv import load_dotenv
from openai import AsyncOpenAI, AsyncAzureOpenAI
from openai import AsyncAzureOpenAI, AsyncOpenAI
# Load environment variables
load_dotenv(override=False)
@@ -110,7 +110,7 @@ class BaseAgent(ABC):
# For local LLM servers, use placeholder key if none provided
client_api_key = api_key or "sk-no-key-required"
binding = os.getenv("LLM_BINDING", "openai")
if binding == "azure_openai" or api_version:
self.client = AsyncAzureOpenAI(
@@ -120,7 +120,7 @@ class BaseAgent(ABC):
)
else:
self.client = AsyncOpenAI(api_key=client_api_key, base_url=base_url)
self.api_key = api_key
self.base_url = base_url
self.api_version = api_version

View File

@@ -17,7 +17,7 @@ from typing import Any
project_root = Path(__file__).parent.parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from openai import OpenAI, AzureOpenAI
from openai import AzureOpenAI, OpenAI
from src.services.config import get_agent_params
from src.services.llm import get_llm_config

View File

@@ -12,7 +12,7 @@ from pathlib import Path
import sys
from typing import Any
from openai import AsyncOpenAI, AsyncAzureOpenAI
from openai import AsyncAzureOpenAI, AsyncOpenAI
# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
@@ -64,7 +64,7 @@ class QuestionValidationWorkflow:
# For local LLM servers, use placeholder key if none provided
client_api_key = api_key or "sk-no-key-required"
binding = os.getenv("LLM_BINDING", "openai")
if binding == "azure_openai" or api_version:
self.client = AsyncAzureOpenAI(
@@ -74,7 +74,7 @@ class QuestionValidationWorkflow:
)
else:
self.client = AsyncOpenAI(api_key=client_api_key, base_url=base_url)
self.api_key = api_key
self.base_url = base_url
self.api_version = api_version

View File

@@ -21,7 +21,7 @@ from src.api.utils.task_id_manager import TaskIDManager
_project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(_project_root))
from src.logging import get_logger
from src.services.config import load_config_with_main
from src.services.config import get_llm_config, load_config_with_main
# Initialize logger with config
project_root = Path(__file__).parent.parent.parent.parent
@@ -37,6 +37,47 @@ async def websocket_solve(websocket: WebSocket):
await websocket.accept()
task_manager = TaskIDManager.get_instance()
connection_closed = asyncio.Event()
log_queue = asyncio.Queue()
pusher_task = None
async def safe_send_json(data: dict[str, Any]):
"""Safely send JSON to WebSocket, checking if connection is closed"""
if connection_closed.is_set():
return False
try:
await websocket.send_json(data)
return True
except (WebSocketDisconnect, RuntimeError, ConnectionError) as e:
logger.debug(f"WebSocket connection closed: {e}")
connection_closed.set()
return False
except Exception as e:
logger.debug(f"Error sending WebSocket message: {e}")
return False
async def log_pusher():
while not connection_closed.is_set():
try:
# Use timeout to periodically check if connection is closed
entry = await asyncio.wait_for(log_queue.get(), timeout=0.5)
try:
await websocket.send_json(entry)
except (WebSocketDisconnect, RuntimeError, ConnectionError) as e:
# Connection closed, stop pushing
logger.debug(f"WebSocket connection closed in log_pusher: {e}")
connection_closed.set()
break
except Exception as e:
logger.debug(f"Error sending log entry: {e}")
# Continue to next entry
log_queue.task_done()
except asyncio.TimeoutError:
# Timeout, check if connection is still open
continue
except Exception as e:
logger.debug(f"Error in log_pusher: {e}")
break
try:
# 1. Wait for the initial message with the question and config
@@ -83,7 +124,7 @@ async def websocket_solve(websocket: WebSocket):
# The main logger already writes to data/user/logs/ai_tutor_YYYYMMDD.log
# 3. Setup Log Queue
log_queue = asyncio.Queue()
# log_queue already initialized
# 4. Setup status update mechanism
display_manager = None
@@ -138,146 +179,102 @@ async def websocket_solve(websocket: WebSocket):
solver._send_progress_update = send_progress_update
# 5. Background task to push logs to WebSocket
connection_closed = asyncio.Event()
async def log_pusher():
while not connection_closed.is_set():
try:
# Use timeout to periodically check if connection is closed
entry = await asyncio.wait_for(log_queue.get(), timeout=0.5)
try:
await websocket.send_json(entry)
except (WebSocketDisconnect, RuntimeError, ConnectionError) as e:
# Connection closed, stop pushing
logger.debug(f"WebSocket connection closed in log_pusher: {e}")
connection_closed.set()
break
except Exception as e:
logger.debug(f"Error sending log entry: {e}")
# Continue to next entry
log_queue.task_done()
except asyncio.TimeoutError:
# Timeout, check if connection is still open
continue
except Exception as e:
logger.debug(f"Error in log_pusher: {e}")
break
pusher_task = asyncio.create_task(log_pusher())
# Helper function to safely send WebSocket messages
async def safe_send_json(data: dict[str, Any]):
"""Safely send JSON to WebSocket, checking if connection is closed"""
if connection_closed.is_set():
return False
try:
await websocket.send_json(data)
return True
except (WebSocketDisconnect, RuntimeError, ConnectionError) as e:
logger.debug(f"WebSocket connection closed: {e}")
connection_closed.set()
return False
except Exception as e:
logger.debug(f"Error sending WebSocket message: {e}")
return False
# 6. Run Solver within the LogInterceptor context
try:
interceptor = LogInterceptor(target_logger, log_queue)
with interceptor:
await safe_send_json({"type": "status", "content": "started"})
interceptor = LogInterceptor(target_logger, log_queue)
with interceptor:
await safe_send_json({"type": "status", "content": "started"})
if display_manager:
await safe_send_json(
{
"type": "agent_status",
"agent": "all",
"status": "initial",
"all_agents": display_manager.agents_status.copy(),
}
)
await safe_send_json(
{"type": "token_stats", "stats": display_manager.stats.copy()}
)
if display_manager:
await safe_send_json(
{
"type": "agent_status",
"agent": "all",
"status": "initial",
"all_agents": display_manager.agents_status.copy(),
}
)
await safe_send_json({"type": "token_stats", "stats": display_manager.stats.copy()})
logger.progress(f"[{task_id}] Solving started")
logger.progress(f"[{task_id}] Solving started")
result = await solver.solve(question, verbose=True)
result = await solver.solve(question, verbose=True)
logger.success(f"[{task_id}] Solving completed")
task_manager.update_task_status(task_id, "completed")
logger.success(f"[{task_id}] Solving completed")
task_manager.update_task_status(task_id, "completed")
# Process Markdown content to fix image paths
final_answer = result.get("final_answer", "")
output_dir_str = result.get("output_dir", "")
# Process Markdown content to fix image paths
final_answer = result.get("final_answer", "")
output_dir_str = result.get("output_dir", "")
if output_dir_str and final_answer:
try:
output_dir = Path(output_dir_str)
if output_dir_str and final_answer:
try:
output_dir = Path(output_dir_str)
if not output_dir.is_absolute():
output_dir = output_dir.resolve()
if not output_dir.is_absolute():
output_dir = output_dir.resolve()
path_str = str(output_dir).replace("\\", "/")
parts = path_str.split("/")
path_str = str(output_dir).replace("\\", "/")
parts = path_str.split("/")
if "user" in parts:
idx = parts.index("user")
rel_path = "/".join(parts[idx + 1 :])
base_url = f"/api/outputs/{rel_path}"
if "user" in parts:
idx = parts.index("user")
rel_path = "/".join(parts[idx + 1 :])
base_url = f"/api/outputs/{rel_path}"
pattern = r"\]\(artifacts/([^)]+)\)"
replacement = rf"]({base_url}/artifacts/\1)"
final_answer = re.sub(pattern, replacement, final_answer)
except Exception as e:
logger.debug(f"Error processing image paths: {e}")
pattern = r"\]\(artifacts/([^)]+)\)"
replacement = rf"]({base_url}/artifacts/\1)"
final_answer = re.sub(pattern, replacement, final_answer)
except Exception as e:
logger.debug(f"Error processing image paths: {e}")
# Send final agent status update
if display_manager:
final_agent_status = dict.fromkeys(display_manager.agents_status.keys(), "done")
await safe_send_json(
{
"type": "agent_status",
"agent": "all",
"status": "complete",
"all_agents": final_agent_status,
}
)
# Send final result
final_res = {
"type": "result",
"final_answer": final_answer,
"output_dir": output_dir_str,
"metadata": result.get("metadata"),
}
await safe_send_json(final_res)
# Save to history
history_manager.add_entry(
activity_type=ActivityType.SOLVE,
title=question[:50] + "..." if len(question) > 50 else question,
content={
"question": question,
"answer": result.get("final_answer"),
"kb_name": kb_name,
},
summary=(
result.get("final_answer")[:100] + "..."
if result.get("final_answer")
else ""
),
# Send final agent status update
if display_manager:
final_agent_status = dict.fromkeys(display_manager.agents_status.keys(), "done")
await safe_send_json(
{
"type": "agent_status",
"agent": "all",
"status": "complete",
"all_agents": final_agent_status,
}
)
except Exception as e:
# Mark connection as closed before sending error (to prevent log_pusher from interfering)
connection_closed.set()
await safe_send_json({"type": "error", "content": str(e)})
logger.error(f"[{task_id}] Solving failed: {e}")
# Send final result
final_res = {
"type": "result",
"final_answer": final_answer,
"output_dir": output_dir_str,
"metadata": result.get("metadata"),
}
await safe_send_json(final_res)
# Save to history
history_manager.add_entry(
activity_type=ActivityType.SOLVE,
title=question[:50] + "..." if len(question) > 50 else question,
content={
"question": question,
"answer": result.get("final_answer"),
"kb_name": kb_name,
},
summary=(
result.get("final_answer")[:100] + "..." if result.get("final_answer") else ""
),
)
except Exception as e:
# Mark connection as closed before sending error (to prevent log_pusher from interfering)
connection_closed.set()
await safe_send_json({"type": "error", "content": str(e)})
logger.error(f"[{task_id if 'task_id' in locals() else 'unknown'}] Solving failed: {e}")
if "task_id" in locals():
task_manager.update_task_status(task_id, "error", error=str(e))
finally:
# Stop log pusher first
connection_closed.set()
finally:
# Stop log pusher first
connection_closed.set()
if pusher_task:
pusher_task.cancel()
try:
await pusher_task
@@ -286,23 +283,18 @@ async def websocket_solve(websocket: WebSocket):
except Exception as e:
logger.debug(f"Error waiting for pusher task: {e}")
# Close WebSocket connection
try:
# Check if connection is still open before closing
if hasattr(websocket, "client_state"):
state = websocket.client_state
if hasattr(state, "name") and state.name != "DISCONNECTED":
await websocket.close()
else:
# Fallback: try to close anyway
# Close WebSocket connection
try:
# Check if connection is still open before closing
if hasattr(websocket, "client_state"):
state = websocket.client_state
if hasattr(state, "name") and state.name != "DISCONNECTED":
await websocket.close()
except (WebSocketDisconnect, RuntimeError, ConnectionError):
# Connection already closed, ignore
pass
except Exception as e:
logger.debug(f"Error closing WebSocket: {e}")
except WebSocketDisconnect:
logger.debug("Client disconnected")
except Exception as e:
logger.error(f"WebSocket error: {e}")
else:
# Fallback: try to close anyway
await websocket.close()
except (WebSocketDisconnect, RuntimeError, ConnectionError):
# Connection already closed, ignore
pass
except Exception as e:
logger.debug(f"Error closing WebSocket: {e}")

View File

@@ -25,7 +25,9 @@ class EmbeddingProvider(BaseModel):
binding: str = Field(..., description="Provider type (openai, jina, cohere, ollama, etc.)")
base_url: str = Field(..., description="API endpoint URL")
api_key: str = Field(default="", description="API Key (optional for local providers)")
api_version: Optional[str] = Field(default=None, description="API Version (required for Azure OpenAI)")
api_version: Optional[str] = Field(
default=None, description="API Version (required for Azure OpenAI)"
)
model: str = Field(..., description="Model name to use")
dimensions: int = Field(..., description="Embedding vector dimensions")
is_active: bool = Field(default=False, description="Whether this provider is currently active")

View File

@@ -36,7 +36,9 @@ class LLMProvider(BaseModel):
binding: str = Field(..., description="Provider type (e.g., openai, azure_openai, ollama)")
base_url: str = Field(..., description="API endpoint URL")
api_key: str = Field(default="", description="API Key (optional for local providers)")
api_version: Optional[str] = Field(default=None, description="API Version (required for Azure OpenAI)")
api_version: Optional[str] = Field(
default=None, description="API Version (required for Azure OpenAI)"
)
model: str = Field(..., description="Model name to use")
is_active: bool = Field(default=False, description="Whether this provider is currently active")
provider_type: Literal["api", "local"] = Field(