Skip to content

Commit f8ced61

Browse files
committed
add python foundry agent integration tutorial
1 parent 58f4ee1 commit f8ced61

4 files changed

Lines changed: 191 additions & 2 deletions

File tree

215 KB
Loading

articles/app-service/tutorial-ai-integrate-azure-ai-agent-node.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ ms.author: cephalin
66
ms.date: 07/21/2025
77
ms.topic: tutorial
88
ms.custom:
9-
- devx-track-dotnet
9+
- devx-track-javascript
1010
ms.collection: ce-skilling-ai-copilot
1111
ms.service: azure-app-service
1212
---
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
---
2+
title: Integrate web app with OpenAPI in Azure AI Foundry Agent Service (Python)
3+
description: Empower your existing Python web apps by integrating their capabilities into Azure AI Foundry Agent Service with OpenAPI, enabling AI agents to perform real-world tasks.
4+
author: cephalin
5+
ms.author: cephalin
6+
ms.date: 08/21/2025
7+
ms.topic: tutorial
8+
ms.custom:
9+
- devx-track-python
10+
ms.collection: ce-skilling-ai-copilot
11+
ms.service: azure-app-service
12+
---
13+
14+
# Add an App Service app as a tool in Azure AI Foundry Agent Service (Python)
15+
16+
In this tutorial, you'll learn how to expose an FastAPI app's functionality through OpenAPI, add it as a tool to Azure AI Foundry Agent Service, and interact with your app using natural language in the agents playground.
17+
18+
If your web application already has useful features, like shopping, hotel booking, or data management, it's easy to make those capabilities available to an AI agent in Azure AI Foundry Agent Service. By simply adding an OpenAPI schema to your app, you enable the agent to understand and use your app's capabilities when it responds to users' prompts. This means anything your app can do, your AI agent can do too, with minimal effort beyond creating an OpenAPI endpoint for your app. In this tutorial, you start with a simple to-do list app. By the end, you'll be able to create, update, and manage tasks with an agent through conversational AI.
19+
20+
:::image type="content" source="media/tutorial-ai-integrate-azure-ai-agent-dotnet/agents-playground.png" alt-text="Screenshot showing the agents playground in the middle of a conversation that takes actions by using the OpenAPI tool.":::
21+
22+
> [!div class="checklist"]
23+
> * Add OpenAPI functionality to your web app.
24+
> * Make sure OpenAPI schema compatible with Azure AI Foundry Agent Service.
25+
> * Register your app as an OpenAPI tool in Azure AI Foundry Agent Service.
26+
> * Test your agent in the the agents playground.
27+
28+
## Prerequisites
29+
30+
This tutorial assumes you're working with the sample used in [Deploy a Python FastAPI web app with PostgreSQL in Azure](tutorial-python-postgresql-app-fastapi.md).
31+
32+
At a minimum, open the [sample application](https://github.com/Azure-Samples/msdocs-fastapi-postgresql-sample-app) in GitHub Codespaces and deploy the app by running `azd up`.
33+
34+
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://github.com/Azure-Samples/msdocs-fastapi-postgresql-sample-app?quickstart=1)
35+
36+
## Add OpenAPI functionality to your web app
37+
38+
FasAPI already contains OpenAPI functionality at the default path `/openapi.json`. You just need to make a few changes to existing code to make it callable remotely by an agent.
39+
40+
1. Open *src/fastapi_app/app.py* and find line 24, where the FastAPI app is declared. Replace `app = FastAPI()` with the following code:
41+
42+
```python
43+
if os.getenv("WEBSITE_HOSTNAME"):
44+
server_url = f"https://{os.getenv('WEBSITE_HOSTNAME')}"
45+
else:
46+
server_url = "http://localhost:8000"
47+
app = FastAPI(
48+
title="Restaurant Review API",
49+
version="1.0.0",
50+
description="Can show restaurant ratings HTML and add new restaurants and reviews.",
51+
servers=[{"url": server_url}],
52+
)
53+
```
54+
55+
This code adds metadata to the OpenAPI schema, such as `title` and `description`. Most importantly, it adds the server URL of the API endpoint.
56+
57+
1. Open *src/fastapi_app/app.py*, add `operation_id` to the `/` and `/details/{id}` GET APIs. These two APIs return HTML documents that an AI agent can parse. For all other APIs, add the `include_in_schema=False` parameter.
58+
59+
```python
60+
@app.get("/", response_class=HTMLResponse, operation_id="getRestaurantsWithRatingsHtml")
61+
...
62+
63+
@app.get("/create", response_class=HTMLResponse, include_in_schema=False)
64+
...
65+
66+
@app.post("/add", response_class=RedirectResponse, include_in_schema=False)
67+
...
68+
69+
@app.get("/details/{id}", response_class=HTMLResponse, operation_id="getRestaurantDetails")
70+
...
71+
72+
@app.post("/review/{id}", response_class=RedirectResponse, include_in_schema=False)
73+
...
74+
```
75+
76+
You use `include_in_schema=False` to exclude `GET /create`, `POST /add`, and `POST /review/{id}` because they're part of the form-based functionality, whereas the AI agent needs to submit JSON data.
77+
78+
1. To add the add restaurant and add review functionality using JSON, add the following code:
79+
80+
```python
81+
from typing import Optional
82+
from fastapi import Body, HTTPException
83+
84+
@app.post("/api/restaurants", response_model=Restaurant, status_code=status.HTTP_201_CREATED, operation_id="createRestaurant")
85+
async def create_restaurant_json(
86+
name: str = Body(...),
87+
street_address: str = Body(...),
88+
description: str = Body(...),
89+
session: Session = Depends(get_db_session),
90+
):
91+
restaurant = Restaurant(name=name, street_address=street_address, description=description)
92+
session.add(restaurant)
93+
session.commit()
94+
session.refresh(restaurant)
95+
return restaurant
96+
97+
98+
@app.post("/api/restaurants/{id}/reviews", response_model=Review, status_code=status.HTTP_201_CREATED,operation_id="createReview")
99+
async def create_review_for_restaurant_json(
100+
id: int,
101+
user_name: str = Body(...),
102+
rating: Optional[int] = Body(None),
103+
review_text: str = Body(...),
104+
session: Session = Depends(get_db_session),
105+
):
106+
if not session.get(Restaurant, id):
107+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Restaurant not found")
108+
109+
review = Review(
110+
restaurant=id, user_name=user_name, rating=rating, review_text=review_text, review_date=datetime.now()
111+
)
112+
session.add(review)
113+
session.commit()
114+
session.refresh(review)
115+
return review
116+
```
117+
118+
1. Start the development server for the sample app with the following commands:
119+
120+
```bash
121+
python3 -m venv .venv
122+
source .venv/bin/activate
123+
pip install -r src/requirements.txt
124+
pip install -e src
125+
python3 src/fastapi_app/seed_data.py
126+
python3 -m uvicorn fastapi_app:app --reload --port=8000
127+
```
128+
129+
130+
1. Select **Open in Browser**.
131+
132+
1. View the OpenAPI schema by adding `/openapi.json` to the URL, which is the default path used by FastAPI to serve the schema.
133+
134+
1. Back in the codespace terminal, deploy your changes by committing your changes (GitHub Actions method) or run `azd up` (Azure Developer CLI method).
135+
136+
1. Once your changes are deployed, navigate to `https://<your-app's-url>/openapi.json` and copy the schema for later.
137+
138+
## Create an agent in Azure AI Foundry
139+
140+
1. Create an agent in the Azure AI Foundry portal by following the steps at: [Quickstart: Create a new agent](/azure/ai-services/agents/quickstart?pivots=ai-foundry-portal).
141+
142+
Note the [models you can use and the available regions](/azure/ai-services/agents/concepts/model-region-support#azure-openai-models).
143+
144+
1. Select the new agent and add an action with the OpenAPI 3.0 specified tool by following the steps at [How to use the OpenAPI spec tool](/azure/ai-services/agents/how-to/tools/openapi-spec-samples?pivots=portal).
145+
146+
1. In the **Define schema** page, paste the schema that you copied earlier. Review and save the action.
147+
148+
## Test the agent
149+
150+
1. If the agents playground isn't already opened in the foundry portal, select the agent and select **Try in playground**.
151+
152+
1. Chat with the agent with the following prompt suggestions:
153+
154+
- "Show me the list of restaurant reviews."
155+
- "Create a restaurant. Use your imagination for the details."
156+
- "I didn't like the food at this restaurant. Please create a 2 star review."
157+
158+
:::image type="content" source="media/tutorial-ai-integrate-azure-ai-agent-python/agents-playground.png" alt-text="Screenshot showing the agents playground in the middle of a conversation that takes actions by using the OpenAPI tool.":::
159+
160+
## Security best practices
161+
162+
When exposing APIs via OpenAPI in Azure App Service, follow these security best practices:
163+
164+
- **Authentication and Authorization**: Protect your OpenAPI endpoints in App Service behind [Azure API Management with Microsoft Entra ID](/azure/api-management/api-management-howto-protect-backend-with-aad) and ensure only authorized users or agents can access the tools.
165+
- **Validate input data:** Always validate incoming data to prevent invalid or malicious input. For Python apps, use libraries such as [Pydantic](https://pypi.org/project/pydantic/) to enforce data validation rules with dedicated request schema models (such as RestaurantCreate and ReviewCreate). Refer to their documentation for best practices and implementation details.
166+
- **Use HTTPS:** The sample relies on Azure App Service, which enforces HTTPS by default and provides free TLS/SSL certificates to encrypt data in transit.
167+
- **Limit CORS:** Restrict Cross-Origin Resource Sharing (CORS) to trusted domains only. For more information, see [Enable CORS](app-service-web-tutorial-rest-api.md#enable-cors).
168+
- **Apply rate limiting:** Use [API Management](/azure/api-management/api-management-sample-flexible-throttling) or custom middleware to prevent abuse and denial-of-service attacks.
169+
- **Hide sensitive endpoints:** Avoid exposing internal or admin APIs in your OpenAPI schema.
170+
- **Review OpenAPI schema:** Ensure your OpenAPI schema doesn't leak sensitive information (such as internal URLs, secrets, or implementation details).
171+
- **Keep dependencies updated:** Regularly update NuGet packages and monitor for security advisories.
172+
- **Monitor and log activity:** Enable logging and monitor access to detect suspicious activity.
173+
- **Use managed identities:** When calling other Azure services, use managed identities instead of hardcoded credentials.
174+
175+
For more information, see [Secure your App Service app](overview-security.md) and [Best practices for REST API security](/azure/architecture/best-practices/api-design#security).
176+
177+
## Next step
178+
179+
You've now enabled your App Service app to be used as a tool by Azure AI Foundry Agent Service and interact with your app's APIs through natural language in the agents playground. From here, you can continue add features to your agent in the Foundry portal, integrate it into your own applications using the Azure AI Foundry SDK or REST API, or deploy it as part of a larger solution. Agents created in Azure AI Foundry can be run in the cloud, integrated into chatbots, or embedded in web and mobile apps.
180+
181+
To take the next step and learn how to run your agent directly within Azure App Service, see the following tutorial:
182+
183+
> [!div class="nextstepaction"]
184+
> [Tutorial: Build an agentic web app in Azure App Service with LangGraph or Azure AI Foundry Agent Service (Python)](tutorial-ai-agent-web-app-langgraph-foundry-python.md)
185+
186+
## More resources
187+
188+
- [Integrate AI into your Azure App Service applications](overview-ai-integration.md)
189+
- [What is Azure AI Foundry Agent Service?](/azure/ai-services/agents/overview)

articles/app-service/tutorial-ai-model-context-protocol-server-node.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ ms.author: cephalin
66
ms.date: 07/22/2025
77
ms.topic: tutorial
88
ms.custom:
9-
- devx-track-dotnet
9+
- devx-track-javascript
1010
ms.collection: ce-skilling-ai-copilot
1111
ms.service: azure-app-service
1212
---

0 commit comments

Comments
 (0)