How to use Semantic Kernel with Microsoft Graph
Quick answer
Use
semantic_kernel to build AI-powered workflows that call Microsoft Graph by implementing custom connectors or skills that authenticate via OAuth and invoke Graph REST APIs. Combine semantic_kernel with Microsoft Graph SDK or direct HTTP calls to access Microsoft 365 data and automate tasks.PREREQUISITES
Python 3.8+Microsoft Azure AD app registration with Microsoft Graph API permissionsMicrosoft Authentication Library (MSAL) for Pythonpip install semantic-kernel msal requests
Setup
Install the required Python packages and configure Azure AD app registration to obtain client ID, tenant ID, and client secret for Microsoft Graph API authentication.
- Install Semantic Kernel and MSAL:
pip install semantic-kernel msal requests - Register an app in Azure portal with Microsoft Graph API permissions (e.g., User.Read, Mail.Read)
- Note your
client_id,tenant_id, andclient_secret
pip install semantic-kernel msal requests Step by step
This example shows how to authenticate with Microsoft Graph using MSAL, then create a Semantic Kernel skill that calls Graph API to fetch the signed-in user's profile.
import os
import requests
from msal import ConfidentialClientApplication
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
# Load environment variables
CLIENT_ID = os.environ['AZURE_CLIENT_ID']
TENANT_ID = os.environ['AZURE_TENANT_ID']
CLIENT_SECRET = os.environ['AZURE_CLIENT_SECRET']
# Acquire token for Microsoft Graph
authority = f'https://login.microsoftonline.com/{TENANT_ID}'
scopes = ['https://graph.microsoft.com/.default']
app = ConfidentialClientApplication(CLIENT_ID, authority=authority, client_credential=CLIENT_SECRET)
result = app.acquire_token_for_client(scopes=scopes)
if 'access_token' not in result:
raise Exception(f"Failed to acquire token: {result.get('error_description')}")
access_token = result['access_token']
# Define a Semantic Kernel skill to call Microsoft Graph
class MicrosoftGraphSkill:
def __init__(self, token):
self.token = token
def get_user_profile(self):
headers = {'Authorization': f'Bearer {self.token}'}
response = requests.get('https://graph.microsoft.com/v1.0/me', headers=headers)
response.raise_for_status()
return response.json()
# Initialize Semantic Kernel
kernel = sk.Kernel()
kernel.add_service(OpenAIChatCompletion(
service_id="chat",
api_key=os.environ["OPENAI_API_KEY"],
ai_model_id="gpt-4o-mini"
))
# Register Microsoft Graph skill
ms_graph_skill = MicrosoftGraphSkill(access_token)
kernel.register_semantic_skill(ms_graph_skill, "msgraph")
# Use the skill
profile = kernel.skills.msgraph.get_user_profile()
print("User display name:", profile.get('displayName'))
print("User email:", profile.get('mail') or profile.get('userPrincipalName')) output
User display name: Jane Doe User email: jane.doe@example.com
Common variations
You can extend this integration by:
- Using async HTTP clients like
httpxfor asynchronous calls - Implementing additional Microsoft Graph API endpoints as Semantic Kernel skills
- Using different AI models by changing
ai_model_idinOpenAIChatCompletion - Adding caching or token refresh logic for long-running applications
import httpx
class AsyncMicrosoftGraphSkill:
def __init__(self, token):
self.token = token
async def get_user_profile(self):
headers = {'Authorization': f'Bearer {self.token}'}
async with httpx.AsyncClient() as client:
response = await client.get('https://graph.microsoft.com/v1.0/me', headers=headers)
response.raise_for_status()
return response.json() Troubleshooting
- If you get authentication errors, verify your Azure AD app permissions and client credentials.
- Ensure the Microsoft Graph API permissions are granted admin consent.
- Check network connectivity and that the token is included correctly in the
Authorizationheader. - Use
response.raise_for_status()to catch HTTP errors and inspect the response content for details.
Key Takeaways
- Use MSAL to authenticate and acquire Microsoft Graph access tokens securely.
- Create Semantic Kernel skills that wrap Microsoft Graph API calls for seamless AI integration.
- Extend skills to cover various Microsoft 365 data and automate workflows with AI.
- Handle token expiration and errors gracefully for robust applications.