GitHub Copilot SDK for Python

0.2.2 · active · verified Tue Apr 14

The GitHub Copilot SDK for Python provides programmatic access to GitHub Copilot's agentic engine via JSON-RPC, allowing developers to embed AI capabilities directly into their applications and workflows. It manages the connection to the Copilot CLI, handles session context, tool invocation, and streaming events. The SDK is currently in public preview, requires Python 3.11+, and is actively developed with frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `CopilotClient`, create a session, send a message, and receive a response. It utilizes Python's `asyncio` for asynchronous operations and `async with` for proper resource management. The `on_permission_request` handler is essential for tool execution within a session. Replace 'gpt-4o' with an appropriate model.

import asyncio
import os
from copilot import CopilotClient, SubprocessConfig
from copilot.session import PermissionHandler

async def main():
    # Ensure COPILOT_CLI_PATH or 'copilot' in PATH for the CLI to be found
    # The CLI is often bundled, but its presence is crucial.
    
    # For programmatic authentication with BYOK, you might set API keys
    # os.environ['OPENAI_API_KEY'] = os.environ.get('OPENAI_API_KEY', '')

    try:
        # Using async with for automatic client lifecycle management
        # Use SubprocessConfig for default behavior (SDK managing CLI process)
        # Or ExternalServerConfig if connecting to an already running CLI server
        async with CopilotClient(SubprocessConfig()) as client:
            print("Copilot client started.")

            # Create a session. on_permission_request is required.
            # 'model' is required when using a custom provider.
            async with await client.create_session(
                model="gpt-4o", # Example model, check available models with client.list_models()
                on_permission_request=PermissionHandler.approve_all,
            ) as session:
                print(f"Session created: {session.session_id}")

                print("Sending message...")
                # send_and_wait now takes a plain string prompt (v0.2.x+)
                response = await session.send_and_wait("What is 2+2?")

                if response and response.data and response.data.content:
                    print(f"Response: {response.data.content}")
                else:
                    print("No content in response.")

            print("Session disconnected.")

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →