# Microsoft 365 Copilot APIs Python Core Client Library
The Microsoft 365 Copilot APIs Python Core Client Library contains core classes used by the [Microsoft 365 Copilot APIs Library](https://github.com/microsoft/Agents-M365Copilot/tree/main/python) to send native HTTP requests to the [Microsoft 365 Copilot APIs](https://aka.ms/M365CopilotAPIs).
> **Note:**
>
> Because the Microsoft 365 Copilot APIs in the beta endpoint are subject to breaking changes, don't use a preview release of the client libraries in production apps.
## Prerequisites
- Python 3.9+
This library doesn't support [older](https://devguide.python.org/versions/) versions of Python.
## Getting started
### 1. Register your application
To call the Copilot endpoints, your app must acquire an access token from the Microsoft identity platform. Learn more about this:
- [Authentication and authorization basics for Microsoft](https://docs.microsoft.com/en-us/graph/auth/auth-concepts)
- [Register your app with the Microsoft identity platform](https://docs.microsoft.com/en-us/graph/auth-register-app-v2)
### 2. Install the required packages
```cmd
pip install azure-identity
pip install python-dotenv
```
The `python-dotenv` is a utility library to load environment variables. Ensure you **DO NOT** commit the file holding your secrets.
You have to build `microsoft-agents-m365copilot-core` locally. To build it, run the following command from the root of the `python` folder:
```cmd
pip install -r requirements-dev.txt
```
This will install the core library with the latest version attached to it in the environment.
Alternatively, you can switch to the root of the core library and run:
```cmd
pip install -e .
```
This will install the core library and it's dependencies to the environment.
### 3. Create a `.env` file with the following values:
```
TENANT_ID = "YOUR_TENANT_ID"
CLIENT_ID = "YOUR_CLIENT_ID"
```
> **Note:**
>
> Your tenant must have a Microsoft 365 Copilot license.
### 4. Create a `main.py` file with the following snippet:
> **Note:**
>
> This example shows how to make a call to the Microsoft 365 Copilot Retrieval API. To call this API, you need to install the [Microsoft 365 Copilot APIs Python Beta Client Library](https://github.com/microsoft/Agents-M365Copilot/tree/main/python/packages/microsoft_agents_m365copilot_beta), create a request object and then run the POST method on the request.
```python
import asyncio
import os
from datetime import datetime
from azure.identity import DeviceCodeCredential
from dotenv import load_dotenv
from kiota_abstractions.api_error import APIError
from microsoft_agents_m365copilot_beta import AgentsM365CopilotBetaServiceClient
from microsoft_agents_m365copilot_beta.generated.copilot.retrieval.retrieval_post_request_body import (
RetrievalPostRequestBody,
)
from microsoft_agents_m365copilot_beta.generated.models.retrieval_data_source import RetrievalDataSource
load_dotenv()
TENANT_ID = os.getenv("TENANT_ID")
CLIENT_ID = os.getenv("CLIENT_ID")
# Define a proper callback function that accepts all three parameters
def auth_callback(verification_uri: str, user_code: str, expires_on: datetime):
print(f"\nTo sign in, use a web browser to open the page {verification_uri}")
print(f"Enter the code {user_code} to authenticate.")
print(f"The code will expire at {expires_on}")
# Create device code credential with correct callback
credentials = DeviceCodeCredential(
client_id=CLIENT_ID,
tenant_id=TENANT_ID,
prompt_callback=auth_callback
)
# Use the Graph API beta endpoint explicitly
scopes = ['https://graph.microsoft.com/.default']
client = AgentsM365CopilotBetaServiceClient(credentials=credentials, scopes=scopes)
# Make sure the base URL is set to beta
client.request_adapter.base_url = "https://graph.microsoft.com/beta"
async def retrieve():
try:
# Print the URL being used
print(f"Using API base URL: {client.request_adapter.base_url}\n")
# Create the retrieval request body
retrieval_body = RetrievalPostRequestBody()
retrieval_body.data_source = RetrievalDataSource.SharePoint
retrieval_body.query_string = "What is the latest in my organization?"
# Try more parameters that might be required
# retrieval_body.maximum_number_of_results = 10
# Make the API call
print("Making retrieval API request...")
retrieval = await client.copilot.retrieval.post(retrieval_body)
# Process the results
if retrieval and hasattr(retrieval, "retrieval_hits"):
print(f"Received {len(retrieval.retrieval_hits)} hits")
for r in retrieval.retrieval_hits:
print(f"Web URL: {r.web_url}\n")
for extract in r.extracts:
print(f"Text:\n{extract.text}\n")
else:
print(f"Retrieval response structure: {dir(retrieval)}")
except APIError as e:
print(f"Error: {e.error.code}: {e.error.message}")
if hasattr(e, 'error') and hasattr(e.error, 'inner_error'):
print(f"Inner error details: {e.error.inner_error}")
raise e
# Run the async function
asyncio.run(retrieve())
```
### 5. If successful, you should get a list of `retrievalHits` collection.
> **Note**:
> This client library offers an asynchronous API by default. Async is a concurrency model that is far more efficient than multi-threading, and can provide significant performance benefits and enable the use of long-lived network connections such as WebSockets. We support popular python async environments such as `asyncio`, `anyio` or `trio`. For authentication you need to use one of the async credential classes from `azure.identity`.
## Telemetry Metadata
This library captures metadata by default that provides insights into its usage and helps to improve the developer experience. This metadata includes the `SdkVersion`, `RuntimeEnvironment` and `HostOs` on which the client is running.
## Issues
View or log issues on the [Issues](https://github.com/microsoft/Agents-M365Copilot/issues) tab in the repo and tag them as `python` or `python-core`.
## Copyright and license
Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT [license](https://github.com/microsoft/Agents-M365Copilot/tree/main/python/LICENSE).
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
Raw data
{
"_id": null,
"home_page": null,
"name": "microsoft-agents-m365copilot-core",
"maintainer": "Microsoft",
"docs_url": null,
"requires_python": "<4.0,>=3.9",
"maintainer_email": "graphtooling+ccspython@microsoft.com",
"keywords": "Copilot, Microsoft, OpenAPI, SDK, M365",
"author": "Microsoft",
"author_email": "graphtooling+ccspython@microsoft.com",
"download_url": "https://files.pythonhosted.org/packages/ab/88/735cd80c051d22fe376473da11c8737981995d9fe8e80bd2a0b8468411dd/microsoft_agents_m365copilot_core-1.0.0rc1.tar.gz",
"platform": null,
"description": "# Microsoft 365 Copilot APIs Python Core Client Library\n\nThe Microsoft 365 Copilot APIs Python Core Client Library contains core classes used by the [Microsoft 365 Copilot APIs Library](https://github.com/microsoft/Agents-M365Copilot/tree/main/python) to send native HTTP requests to the [Microsoft 365 Copilot APIs](https://aka.ms/M365CopilotAPIs).\n\n> **Note:**\n>\n> Because the Microsoft 365 Copilot APIs in the beta endpoint are subject to breaking changes, don't use a preview release of the client libraries in production apps.\n\n## Prerequisites\n\n- Python 3.9+\n\nThis library doesn't support [older](https://devguide.python.org/versions/) versions of Python.\n\n## Getting started\n\n### 1. Register your application\n\nTo call the Copilot endpoints, your app must acquire an access token from the Microsoft identity platform. Learn more about this:\n\n- [Authentication and authorization basics for Microsoft](https://docs.microsoft.com/en-us/graph/auth/auth-concepts)\n- [Register your app with the Microsoft identity platform](https://docs.microsoft.com/en-us/graph/auth-register-app-v2)\n\n### 2. Install the required packages\n\n```cmd\npip install azure-identity\npip install python-dotenv\n```\n\nThe `python-dotenv` is a utility library to load environment variables. Ensure you **DO NOT** commit the file holding your secrets.\n\nYou have to build `microsoft-agents-m365copilot-core` locally. To build it, run the following command from the root of the `python` folder:\n\n```cmd\npip install -r requirements-dev.txt\n```\n\nThis will install the core library with the latest version attached to it in the environment.\n\nAlternatively, you can switch to the root of the core library and run:\n\n```cmd\npip install -e .\n```\n\nThis will install the core library and it's dependencies to the environment.\n\n### 3. Create a `.env` file with the following values:\n\n```\nTENANT_ID = \"YOUR_TENANT_ID\"\nCLIENT_ID = \"YOUR_CLIENT_ID\"\n```\n\n> **Note:**\n>\n> Your tenant must have a Microsoft 365 Copilot license.\n\n### 4. Create a `main.py` file with the following snippet:\n\n> **Note:**\n>\n> This example shows how to make a call to the Microsoft 365 Copilot Retrieval API. To call this API, you need to install the [Microsoft 365 Copilot APIs Python Beta Client Library](https://github.com/microsoft/Agents-M365Copilot/tree/main/python/packages/microsoft_agents_m365copilot_beta), create a request object and then run the POST method on the request.\n\n```python\nimport asyncio\nimport os\nfrom datetime import datetime\n\nfrom azure.identity import DeviceCodeCredential\nfrom dotenv import load_dotenv\nfrom kiota_abstractions.api_error import APIError\n\nfrom microsoft_agents_m365copilot_beta import AgentsM365CopilotBetaServiceClient\nfrom microsoft_agents_m365copilot_beta.generated.copilot.retrieval.retrieval_post_request_body import (\n RetrievalPostRequestBody,\n)\nfrom microsoft_agents_m365copilot_beta.generated.models.retrieval_data_source import RetrievalDataSource\n\nload_dotenv()\n\nTENANT_ID = os.getenv(\"TENANT_ID\")\nCLIENT_ID = os.getenv(\"CLIENT_ID\")\n\n# Define a proper callback function that accepts all three parameters\ndef auth_callback(verification_uri: str, user_code: str, expires_on: datetime):\n print(f\"\\nTo sign in, use a web browser to open the page {verification_uri}\")\n print(f\"Enter the code {user_code} to authenticate.\")\n print(f\"The code will expire at {expires_on}\")\n\n# Create device code credential with correct callback\ncredentials = DeviceCodeCredential(\n client_id=CLIENT_ID,\n tenant_id=TENANT_ID,\n prompt_callback=auth_callback\n)\n\n# Use the Graph API beta endpoint explicitly\nscopes = ['https://graph.microsoft.com/.default']\nclient = AgentsM365CopilotBetaServiceClient(credentials=credentials, scopes=scopes)\n\n# Make sure the base URL is set to beta\nclient.request_adapter.base_url = \"https://graph.microsoft.com/beta\"\n\nasync def retrieve():\n try:\n # Print the URL being used\n print(f\"Using API base URL: {client.request_adapter.base_url}\\n\")\n \n # Create the retrieval request body\n retrieval_body = RetrievalPostRequestBody()\n retrieval_body.data_source = RetrievalDataSource.SharePoint\n retrieval_body.query_string = \"What is the latest in my organization?\"\n \n # Try more parameters that might be required\n # retrieval_body.maximum_number_of_results = 10\n \n # Make the API call\n print(\"Making retrieval API request...\")\n retrieval = await client.copilot.retrieval.post(retrieval_body)\n \n # Process the results\n if retrieval and hasattr(retrieval, \"retrieval_hits\"):\n print(f\"Received {len(retrieval.retrieval_hits)} hits\")\n for r in retrieval.retrieval_hits:\n print(f\"Web URL: {r.web_url}\\n\")\n for extract in r.extracts:\n print(f\"Text:\\n{extract.text}\\n\")\n else:\n print(f\"Retrieval response structure: {dir(retrieval)}\")\n except APIError as e:\n print(f\"Error: {e.error.code}: {e.error.message}\")\n if hasattr(e, 'error') and hasattr(e.error, 'inner_error'):\n print(f\"Inner error details: {e.error.inner_error}\")\n raise e\n\n# Run the async function\nasyncio.run(retrieve())\n```\n\n### 5. If successful, you should get a list of `retrievalHits` collection.\n\n> **Note**:\n> This client library offers an asynchronous API by default. Async is a concurrency model that is far more efficient than multi-threading, and can provide significant performance benefits and enable the use of long-lived network connections such as WebSockets. We support popular python async environments such as `asyncio`, `anyio` or `trio`. For authentication you need to use one of the async credential classes from `azure.identity`.\n\n## Telemetry Metadata\n\nThis library captures metadata by default that provides insights into its usage and helps to improve the developer experience. This metadata includes the `SdkVersion`, `RuntimeEnvironment` and `HostOs` on which the client is running.\n\n## Issues\n\nView or log issues on the [Issues](https://github.com/microsoft/Agents-M365Copilot/issues) tab in the repo and tag them as `python` or `python-core`.\n\n## Copyright and license\n\nCopyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT [license](https://github.com/microsoft/Agents-M365Copilot/tree/main/python/LICENSE).\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Core component of the Microsoft Agents M365 Copilot Core Python SDK",
"version": "1.0.0rc1",
"project_urls": {
"Documentation": "https://github.com/microsoft/Agents-M365Copilot/tree/main/python/packages/microsoft_agents_m365copilot_core#readme",
"Homepage": "https://github.com/microsoft/Agents-M365Copilot/tree/main/python",
"Repository": "https://github.com/microsoft/Agents-M365Copilot"
},
"split_keywords": [
"copilot",
" microsoft",
" openapi",
" sdk",
" m365"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "c1915db0770e76dfbf6ada8fcb5d9607dec277a5de176f1fad6a971640fc37e5",
"md5": "07579c5146acc99781b8344d92be6eeb",
"sha256": "c3dfcb4ca108bd882fa6df53a899bdccdc52c9975e3c62c261361b059fe81fb6"
},
"downloads": -1,
"filename": "microsoft_agents_m365copilot_core-1.0.0rc1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "07579c5146acc99781b8344d92be6eeb",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.9",
"size": 14658,
"upload_time": "2025-07-16T03:52:06",
"upload_time_iso_8601": "2025-07-16T03:52:06.996937Z",
"url": "https://files.pythonhosted.org/packages/c1/91/5db0770e76dfbf6ada8fcb5d9607dec277a5de176f1fad6a971640fc37e5/microsoft_agents_m365copilot_core-1.0.0rc1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "ab88735cd80c051d22fe376473da11c8737981995d9fe8e80bd2a0b8468411dd",
"md5": "81822e7feb3edbc2c4f863dcd9e256d3",
"sha256": "babaf496d84ad013b2617d2230e52f064dba06031ab5d8b7c2f55961fa9c841b"
},
"downloads": -1,
"filename": "microsoft_agents_m365copilot_core-1.0.0rc1.tar.gz",
"has_sig": false,
"md5_digest": "81822e7feb3edbc2c4f863dcd9e256d3",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.9",
"size": 12385,
"upload_time": "2025-07-16T03:52:05",
"upload_time_iso_8601": "2025-07-16T03:52:05.996829Z",
"url": "https://files.pythonhosted.org/packages/ab/88/735cd80c051d22fe376473da11c8737981995d9fe8e80bd2a0b8468411dd/microsoft_agents_m365copilot_core-1.0.0rc1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-16 03:52:05",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "microsoft",
"github_project": "Agents-M365Copilot",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "microsoft-agents-m365copilot-core"
}