Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,45 +42,51 @@ def get_dimensions():
return res


def get_project_endpoint():
def get_project_endpoint(logger=None):
project_endpoint = os.environ.get(Constants.AZURE_AI_PROJECT_ENDPOINT)
if project_endpoint:
if logger:
logger.info(f"Using project endpoint from {Constants.AZURE_AI_PROJECT_ENDPOINT}: {project_endpoint}")
return project_endpoint
project_resource_id = os.environ.get(Constants.AGENT_PROJECT_RESOURCE_ID)
if project_resource_id:
last_part = project_resource_id.split("/")[-1]

parts = last_part.split("@")
if len(parts) < 2:
print(f"invalid project resource id: {project_resource_id}")
if logger:
logger.warning(f"Invalid project resource id format: {project_resource_id}")
return None
account = parts[0]
project = parts[1]
return f"https://{account}.services.ai.azure.com/api/projects/{project}"
print("environment variable AGENT_PROJECT_RESOURCE_ID not set.")
endpoint = f"https://{account}.services.ai.azure.com/api/projects/{project}"
if logger:
logger.info(f"Using project endpoint derived from {Constants.AGENT_PROJECT_RESOURCE_ID}: {endpoint}")
return endpoint
return None


def get_application_insights_connstr():
def get_application_insights_connstr(logger=None):
try:
conn_str = os.environ.get(APPINSIGHT_CONNSTR_ENV_NAME)
if not conn_str:
print(f"environment variable {APPINSIGHT_CONNSTR_ENV_NAME} not set.")
project_endpoint = get_project_endpoint()
project_endpoint = get_project_endpoint(logger=logger)
if project_endpoint:
# try to get the project connected application insights
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential

project_client = AIProjectClient(credential=DefaultAzureCredential(), endpoint=project_endpoint)
conn_str = project_client.telemetry.get_application_insights_connection_string()
if not conn_str:
print(f"no connected application insights found for project:{project_endpoint}")
else:
if not conn_str and logger:
logger.info(f"No Application Insights connection found for project: {project_endpoint}")
elif conn_str:
os.environ[APPINSIGHT_CONNSTR_ENV_NAME] = conn_str
elif logger:
logger.info("Application Insights not configured, telemetry export disabled.")
return conn_str
except Exception as e:
print(f"failed to get application insights with error: {e}")
if logger:
logger.warning(f"Failed to get Application Insights connection string, telemetry export disabled: {e}")
return None


Expand All @@ -107,8 +113,9 @@ def configure(log_config: dict = default_log_config):
"""
try:
config.dictConfig(log_config)
app_logger = logging.getLogger("azure.ai.agentserver")

application_insights_connection_string = get_application_insights_connstr()
application_insights_connection_string = get_application_insights_connstr(logger=app_logger)
enable_application_insights_logger = (
os.environ.get(Constants.ENABLE_APPLICATION_INSIGHTS_LOGGER, "true").lower() == "true"
)
Expand Down Expand Up @@ -137,7 +144,6 @@ def configure(log_config: dict = default_log_config):
handler.addFilter(custom_filter)

# Only add to azure.ai.agentserver namespace to avoid infrastructure logs
app_logger = logging.getLogger("azure.ai.agentserver")
app_logger.setLevel(get_log_level())
app_logger.addHandler(handler)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def __init__(self,
credentials: Optional[Union[AsyncTokenCredential, TokenCredential]] = None,
project_endpoint: Optional[str] = None) -> None:
self.credentials = AsyncTokenCredentialAdapter(credentials) if credentials else AsyncDefaultTokenCredential()
project_endpoint = get_project_endpoint() or project_endpoint
project_endpoint = get_project_endpoint(logger=logger) or project_endpoint
AgentServerContext(create_tool_runtime(project_endpoint, self.credentials))

async def runs_endpoint(request):
Expand Down Expand Up @@ -198,9 +198,14 @@ async def readiness_endpoint(request):
self.app.add_middleware(AgentRunContextMiddleware, agent=self)

@self.app.on_event("startup")
async def attach_appinsights_logger():
async def on_startup():
import logging

# Log server started successfully
port = getattr(self, '_port', 'unknown')
logger.info(f"FoundryCBAgent server started successfully on port {port}")

# Attach App Insights handler to uvicorn loggers
for handler in logger.handlers:
if handler.name == "appinsights_handler":
for logger_name in ["uvicorn", "uvicorn.error", "uvicorn.access"]:
Expand Down Expand Up @@ -348,6 +353,7 @@ async def run_async(
self.init_tracing()
config = uvicorn.Config(self.app, host="0.0.0.0", port=port, loop="asyncio")
server = uvicorn.Server(config)
self._port = port
logger.info(f"Starting FoundryCBAgent server async on port {port}")
await server.serve()

Expand All @@ -363,6 +369,7 @@ def run(self, port: int = int(os.environ.get("DEFAULT_AD_PORT", 8088))) -> None:
:type port: int
"""
self.init_tracing()
self._port = port
logger.info(f"Starting FoundryCBAgent server on port {port}")
uvicorn.run(self.app, host="0.0.0.0", port=port)

Expand Down