From de0e2f27fde2fd51641c0ca5f196374237addfdd Mon Sep 17 00:00:00 2001 From: Scarlet Moore Date: Fri, 9 Jan 2026 14:11:17 +0000 Subject: [PATCH] feat: enhance Azure OpenAI support in configuration and agent classes --- .env.example | 2 +- src/agents/co_writer/narrator_agent.py | 3 +- src/agents/question/agents/base_agent.py | 6 +- .../question/tools/question_extractor.py | 2 +- src/agents/question/validation_workflow.py | 6 +- src/api/routers/solve.py | 280 +++++++++--------- src/services/embedding/provider_config.py | 4 +- src/services/llm/provider.py | 4 +- 8 files changed, 152 insertions(+), 155 deletions(-) diff --git a/.env.example b/.env.example index aa80a9dd0..53dc7acfb 100644 --- a/.env.example +++ b/.env.example @@ -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= diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.py index 0b9589f29..240ac8de6 100644 --- a/src/agents/co_writer/narrator_agent.py +++ b/src/agents/co_writer/narrator_agent.py @@ -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( diff --git a/src/agents/question/agents/base_agent.py b/src/agents/question/agents/base_agent.py index 6b5af25e2..f189b037b 100644 --- a/src/agents/question/agents/base_agent.py +++ b/src/agents/question/agents/base_agent.py @@ -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 diff --git a/src/agents/question/tools/question_extractor.py b/src/agents/question/tools/question_extractor.py index fdd124969..808bdc34c 100644 --- a/src/agents/question/tools/question_extractor.py +++ b/src/agents/question/tools/question_extractor.py @@ -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 diff --git a/src/agents/question/validation_workflow.py b/src/agents/question/validation_workflow.py index 8d1e2fe49..bd1dfc0a6 100644 --- a/src/agents/question/validation_workflow.py +++ b/src/agents/question/validation_workflow.py @@ -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 diff --git a/src/api/routers/solve.py b/src/api/routers/solve.py index e86be940a..4a7c216d0 100644 --- a/src/api/routers/solve.py +++ b/src/api/routers/solve.py @@ -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}") diff --git a/src/services/embedding/provider_config.py b/src/services/embedding/provider_config.py index bc4b1d62e..12e46fbcc 100644 --- a/src/services/embedding/provider_config.py +++ b/src/services/embedding/provider_config.py @@ -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") diff --git a/src/services/llm/provider.py b/src/services/llm/provider.py index 8fb5d986d..90c8b1698 100644 --- a/src/services/llm/provider.py +++ b/src/services/llm/provider.py @@ -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(