Skip to content

Commit 8486b50

Browse files
author
Shreyas-Microsoft
committed
add liifespan of an agent
1 parent 2a9c143 commit 8486b50

2 files changed

Lines changed: 101 additions & 34 deletions

File tree

src/backend/app.py

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
11
"""Create and configure the FastAPI application."""
2+
from contextlib import asynccontextmanager
3+
24
from api.api_routes import router as backend_router
35

6+
from azure.identity.aio import DefaultAzureCredential
7+
8+
from common.config.config import app_config
49
from common.logger.app_logger import AppLogger
510

611
from dotenv import load_dotenv
712

813
from fastapi import FastAPI
914
from fastapi.middleware.cors import CORSMiddleware
1015

16+
from semantic_kernel.agents.azure_ai.azure_ai_agent import AzureAIAgent # pylint: disable=E0611
17+
18+
from sql_agents.agents.agent_config import AgentBaseConfig
19+
from sql_agents.helpers.agents_manager import SqlAgents
20+
1121
import uvicorn
1222
# from agent_services.agents_routes import router as agents_router
1323

@@ -17,10 +27,77 @@
1727
# Configure logging
1828
logger = AppLogger("app")
1929

30+
# Global variables for agents
31+
sql_agents: SqlAgents = None
32+
azure_client = None
33+
34+
35+
def get_sql_agents() -> SqlAgents:
36+
"""Get the global SQL agents instance."""
37+
return sql_agents
38+
39+
40+
async def update_agent_config(convert_from: str, convert_to: str):
41+
"""Update the global agent configuration for different SQL conversion types."""
42+
global sql_agents
43+
if sql_agents and sql_agents.agent_config:
44+
sql_agents.agent_config.sql_from = convert_from
45+
sql_agents.agent_config.sql_to = convert_to
46+
logger.logger.info(f"Updated agent configuration: {convert_from} -> {convert_to}")
47+
else:
48+
logger.logger.warning("SQL agents not initialized, cannot update configuration")
49+
50+
51+
@asynccontextmanager
52+
async def lifespan(app: FastAPI):
53+
"""Manage application lifespan - startup and shutdown."""
54+
global sql_agents, azure_client
55+
56+
# Startup
57+
try:
58+
logger.logger.info("Initializing SQL agents...")
59+
60+
# Create Azure credentials and client
61+
creds = DefaultAzureCredential()
62+
azure_client = AzureAIAgent.create_client(
63+
credential=creds,
64+
endpoint=app_config.ai_project_endpoint
65+
)
66+
67+
# Setup agent configuration with default conversion settings
68+
agent_config = AgentBaseConfig(
69+
project_client=azure_client,
70+
sql_from="informix", # Default source dialect
71+
sql_to="tsql" # Default target dialect
72+
)
73+
74+
# Create SQL agents
75+
sql_agents = await SqlAgents.create(agent_config)
76+
logger.logger.info("SQL agents initialized successfully.")
77+
78+
except Exception as exc:
79+
logger.logger.error("Failed to initialize SQL agents: %s", exc)
80+
# Don't raise the exception to allow the app to start even if agents fail
81+
82+
yield # Application runs here
83+
84+
# Shutdown
85+
try:
86+
if sql_agents:
87+
logger.logger.info("Cleaning up SQL agents...")
88+
await sql_agents.delete_agents()
89+
logger.logger.info("SQL agents cleaned up successfully.")
90+
91+
if azure_client:
92+
await azure_client.close()
93+
94+
except Exception as exc:
95+
logger.logger.error("Error during agent cleanup: %s", exc)
96+
2097

2198
def create_app() -> FastAPI:
2299
"""Create and return the FastAPI application instance."""
23-
app = FastAPI(title="Code Gen Accelerator", version="1.0.0")
100+
app = FastAPI(title="Code Gen Accelerator", version="1.0.0", lifespan=lifespan)
24101

25102
# Configure CORS
26103
app.add_middleware(

src/backend/sql_agents/process_batch.py

Lines changed: 23 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,8 @@
77
import logging
88

99
from api.status_updates import send_status_update
10+
from app import get_sql_agents, update_agent_config
1011

11-
from azure.identity.aio import DefaultAzureCredential
12-
13-
from common.config.config import app_config
1412
from common.models.api import (
1513
FileProcessUpdate,
1614
FileRecord,
@@ -23,14 +21,10 @@
2321

2422
from fastapi import HTTPException
2523

26-
27-
from semantic_kernel.agents.azure_ai.azure_ai_agent import AzureAIAgent # pylint: disable=E0611
2824
from semantic_kernel.contents import AuthorRole
2925
from semantic_kernel.exceptions.service_exceptions import ServiceResponseException
3026

31-
from sql_agents.agents.agent_config import AgentBaseConfig
3227
from sql_agents.convert_script import convert_script
33-
from sql_agents.helpers.agents_manager import SqlAgents
3428
from sql_agents.helpers.models import AgentType
3529
from sql_agents.helpers.utils import is_text
3630

@@ -57,22 +51,20 @@ async def process_batch_async(
5751
except Exception as exc:
5852
logger.error("Error updating batch status. %s", exc)
5953

60-
# Add client and auto cleanup
61-
async with (
62-
DefaultAzureCredential() as creds,
63-
AzureAIAgent.create_client(credential=creds, endpoint=app_config.ai_project_endpoint) as client,
64-
):
65-
66-
# setup all agent settings and agents per batch
67-
agent_config = AgentBaseConfig(
68-
project_client=client, sql_from=convert_from, sql_to=convert_to
69-
)
70-
sql_agents = await SqlAgents.create(agent_config)
71-
72-
# Walk through each file name and retrieve it from blob storage
73-
# Send file to the agents for processing
74-
# Send status update to the client of type in progress, completed, or failed
75-
for file in batch_files:
54+
# Get the global SQL agents instance
55+
sql_agents = get_sql_agents()
56+
if not sql_agents:
57+
logger.error("SQL agents not initialized. Application may not have started properly.")
58+
await batch_service.update_batch(batch_id, ProcessStatus.FAILED)
59+
return
60+
61+
# Update agent configuration for this batch's conversion requirements
62+
await update_agent_config(convert_from, convert_to)
63+
64+
# Walk through each file name and retrieve it from blob storage
65+
# Send file to the agents for processing
66+
# Send status update to the client of type in progress, completed, or failed
67+
for file in batch_files:
7668
# Get the file from blob storage
7769
try:
7870
file_record = FileRecord.fromdb(file)
@@ -145,16 +137,14 @@ async def process_batch_async(
145137
# insert data base write to file record stating invalid file
146138
await process_error(exc, file_record, batch_service)
147139

148-
# Cleanup the agents
149-
await sql_agents.delete_agents()
150-
151-
try:
152-
await batch_service.batch_files_final_update(batch_id)
153-
await batch_service.update_batch(batch_id, ProcessStatus.COMPLETED)
154-
except Exception as exc:
155-
await batch_service.update_batch(batch_id, ProcessStatus.FAILED)
156-
logger.error("Error updating batch status. %s", exc)
157-
logger.info("Batch processing complete.")
140+
# Update batch status to completed or failed
141+
try:
142+
await batch_service.batch_files_final_update(batch_id)
143+
await batch_service.update_batch(batch_id, ProcessStatus.COMPLETED)
144+
except Exception as exc:
145+
await batch_service.update_batch(batch_id, ProcessStatus.FAILED)
146+
logger.error("Error updating batch status. %s", exc)
147+
logger.info("Batch processing complete.")
158148

159149

160150
async def process_error(

0 commit comments

Comments
 (0)