Agentify Your App with GitHub Copilot’s Agentic Coding SDK


import asyncio

import sys

from copilot import CopilotClient

from copilot.tools import define_tool

from copilot.generated.session_events import SessionEventType

from pydantic import BaseModel, Field

 

# Step 1: Define custom tools using the @define_tool decorator.

class GetDataVisualizationParams(BaseModel):

    library_name: str = Field(description=“The name of the Python library to get info about”)

 

 

@define_tool(description=“Get information about a Python data visualization library”)

async def get_library_info(params: GetDataVisualizationParams) -> dict:

    “”“Custom tool that provides information about data visualization libraries.”“”

    libraries = {

        “matplotlib”: {

            “name”: “Matplotlib”,

            “use_case”: “Foundational plotting library for static, animated, and interactive visualizations”,

            “install”: “pip install matplotlib”,

            “popularity”: “Most widely used, basis for many other libraries”,

        },

        “seaborn”: {

            “name”: “Seaborn”,

            “use_case”: “Statistical data visualization with attractive default styles”,

            “install”: “pip install seaborn”,

            “popularity”: “Great for exploratory data analysis”,

        },

        “plotly”: {

            “name”: “Plotly”,

            “use_case”: “Interactive, publication-quality graphs for dashboards”,

            “install”: “pip install plotly”,

            “popularity”: “Best for web-based interactive visualizations”,

        },

    }

 

    library = params.library_name.lower()

    if library in libraries:

        return libraries[library]

    return {“error”: f“Library ‘{library}’ not found. Try: matplotlib, seaborn, or plotly”}

 

 

async def main():

    # Step 2: Create and start the Copilot client with an explicit CLI path.

    # The SDK needs to find the Copilot CLI, so specify the path explicitly.

    client = CopilotClient({

        “cli_path”: “C:\\nvm4w\\nodejs\\copilot.cmd”,  # Path to Copilot CLI

        “log_level”: “debug”,  # Enable debug logging for troubleshooting

    })

 

    print(” GitHub Copilot SDK Demo – Agentic Coding in Action”)

    print(” Starting Copilot client (this may take a moment)…\n”)

 

    await client.start()

 

    print(“=” * 60)

 

    # Step 3: Create a session with custom configuration.

    session = await client.create_session({

        “model”: “gpt-4.1”,            # Choose a model

        “streaming”: True,             # Enable streaming responses

        “tools”: [get_library_info],   # Register custom tools

        “system_message”: (

            “You are a helpful technical assistant for data scientists. “

            “When asked about visualization libraries, use the get_library_info tool “

            “to provide accurate information.”

        ),

    })

 

    print(f“Session created: {session.session_id}\n”)

 

    # Step 4: Set up event handlers for streaming.

    def handle_event(event):

        if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:

            # Stream the response as it arrives.

            sys.stdout.write(event.data.delta_content)

            sys.stdout.flush()

        elif event.type == SessionEventType.TOOL_EXECUTION_START:

            print(f“\n Tool called: {event.data.tool_name}”)

 

    session.on(handle_event)

 

    # Step 5: Send a prompt and let the agent work.

    print(” User: List three common Python libraries for data visualization and their main use case.\n”)

    print(” Assistant: “, end=“”)

 

    await session.send_and_wait({

        “prompt”: (

            “List three common Python libraries for data visualization and their main use case. “

            “Use the get_library_info tool to get accurate information about each one.”

        )

    })

 

    print(“\n\n” + “=” * 60)

 

    # Step 6: Clean up.

    await session.destroy()

    await client.stop()

 

    print(” Session ended successfully!”)

 

 

if __name__ == “__main__”:

    asyncio.run(main())



Source link