Skip to main content

Microsoft 365 Copilot APIs V1 Python Client Library

Integrate the Microsoft 365 Copilot APIs into your Python application!

Installation

To install the client libraries via PyPi:

pip install microsoft-agents-m365copilot

Create a Copilot APIs client and make an API call

The following code example shows how to create an instance of a Microsoft 365 Copilot APIs client with an authentication provider in the supported languages. The authentication provider handles acquiring access tokens for the application. Many different authentication providers are available for each language and platform. The different authentication providers support different client scenarios. For details about which provider and options are appropriate for your scenario, see Choose an Authentication Provider.

The example also shows how to make a call to the Microsoft 365 Copilot Retrieval API. To call this API, you first need to create a request object and then run the POST method on the request.

The client ID is the app registration ID that is generated when you register your app in the Azure portal.

  1. 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.

  2. Create a main.py file with the following snippet:

    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 import AgentsM365CopilotServiceClient
    from microsoft_agents_m365copilot.generated.copilot.retrieval.retrieval_post_request_body import (
        RetrievalPostRequestBody,
    )
    from microsoft_agents_m365copilot.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 V1 endpoint explicitly
    scopes = ['https://graph.microsoft.com/.default']
    client = AgentsM365CopilotBetaServiceClient(credentials=credentials, scopes=scopes)
    
    # Make sure the base URL is set to V1
    client.request_adapter.base_url = "https://graph.microsoft.com/v1.0"
    
    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())
    
  3. If successful, you should get a list of retrievalHits collection.

Issues

To view or log issues, see issues.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

Metadata

Release files for microsoft-agents-m365copilot 1.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for microsoft-agents-m365copilot 1.10.0
File Size Uploaded
microsoft_agents_m365copilot-1.10.0.tar.gz 49.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for microsoft-agents-m365copilot 1.10.0
File Interpreter ABI Platform
microsoft_agents_m365copilot-1.10.0-py3-none-any.whl Python 3 none any Details

Total release size: 216.5 kB

Release files / microsoft_agents_m365copilot-1.10.0.tar.gz

Download URL microsoft_agents_m365copilot-1.10.0.tar.gz
Size 49.4 kB
Tags Source
SHA-256 checksum
How to use checksums
20e55bdc3e8fc8bc1bd1b558ec0da50e8e414e6dab469462fea76fea46412e0c
BLAKE2b-256 checksum
How to use checksums
269801a8c34c4568ecdb146c3afce1bf2d32c1f93894b7a1e6d0aeb89956454e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via RestSharp/106.13.0.0

Release files / microsoft_agents_m365copilot-1.10.0-py3-none-any.whl

Download URL microsoft_agents_m365copilot-1.10.0-py3-none-any.whl
Size 167.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2304e7a7d9d0b662577dd3b97ba772c365ae11f09ba4d0daeea0f3bac09654e9
BLAKE2b-256 checksum
How to use checksums
7ac219acea72509e1a0e9b5f826aebed105fadeb48856e879e389acf2599813a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via RestSharp/106.13.0.0

Release history Release notifications | RSS feed

This release

1.10.0 This release

2 release files

1.9.0

2 release files

1.8.0

2 release files

1.7.0

2 release files

1.6.0

2 release files

1.5.0

2 release files

1.4.0

2 release files

1.3.0

2 release files

1.2.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page