2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GitHub Copilot SDKで何ができる?

2
Posted at

概要

先日、GitHub Copilot SDKというものがプレビュー版で公開されました。

これで、自作したコードの中でCopilotの応答結果などを利用できます。実際に使ってみながら、どんな風に使い道がありそうか試してみましょう!

GitHub Copilot SDKとは

簡単に言うと、言語のライブラリとしてCopilotを呼び出せる機能です。Node.js/TypeScript, Python, Go, .NETで利用可能です。

仕組みとしては、Copilot CLIのサーバモード概要
先日、GitHub Copilot SDKというものがプレビュー版で公開されました。

これで、自作したコードの中でCopilotの応答結果などを利用できます。実際に使ってみながら、どんな風に使い道がありそうか試してみましょう!

GitHub Copilot SDKとは

簡単に言うと、言語のライブラリとしてCopilotを呼び出せる機能です。Node.js/TypeScript, Python, Go, .NETで利用可能です。

仕組みとしては、自作のアプリケーションからSDKを使い、JSON-PRC経由でCopilot CLIに命令を渡すそうです。

Your Application
       ↓
  SDK Client
       ↓ JSON-RPC
  Copilot CLI (server mode)

導入 ~ 簡単なアプリ作成まで

今回はpythonで進めていきます。導入から簡単な対話アプリケーションの作成まで。Pythonのバージョンは3.8以上が必要です。

こちらを参考にしています。

導入

インストールは以下コマンドだけで完結します。

pip install github-copilot-sdk

簡単なメッセージの送信

単純に固定メッセージを投げ、その応答を表示するだけのプログラムを書いてみます。

import asyncio
from copilot import CopilotClient

async def main():
    client = CopilotClient()
    await client.start()

    # モデルの選択
    session = await client.create_session({"model": "gpt-4.1"})
    # メッセージの送信
    response = await session.send_and_wait({"prompt": "What is 2 + 2?"})

    print(response.data.content)

    await client.stop()

asyncio.run(main())

この応答だけが返ってきました。無事使えているようです。
image.png

Copilot CLIのバージョンも上げておかないと、こんな感じでエラーが出てしまいました。

RuntimeError: SDK protocol version mismatch: SDK expects version 2, but server reports version 1. Please update your SDK or server to ensure compatibility.

返信のストリーミング化

上の方法だと応答がすべて返ってくるまで止まってしまうので、ストリーミングで随時応答が見えるようにします。

import asyncio
import sys
from copilot import CopilotClient
from copilot.generated.session_events import SessionEventType

async def main():
    client = CopilotClient()
    await client.start()

    # ストリーミングセッションの作成
    session = await client.create_session({
        "model": "gpt-4.1",
        "streaming": True,  # ストリーミングモードを有効にする
    })

    # イベントハンドラの定義
    def handle_event(event):
        if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
            sys.stdout.write(event.data.delta_content)
            sys.stdout.flush()

    session.on(handle_event)

    await session.send_and_wait({"prompt": "何かちょっと長めの面白い話をしてください。"})

    await client.stop()

asyncio.run(main())

こんな感じで、生成した文章を都度返却し表示してくれます。
Animation2.gif

Toolの利用

カスタムのToolを呼び出すことも可能です。ここでは仮の自作Toolを作成し、それを呼び出すようにCopilotのセッションに渡してあげます。

import asyncio
import random
import sys
from copilot import CopilotClient
from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field

# Pydanticを使用してツールのパラメータを定義
class GetWeatherParams(BaseModel):
    city: str = Field(description="The name of the city to get weather for")

# Copilotが呼び出すことができるツールを定義
@define_tool(description="Get the current weather for a city")
async def get_weather(params: GetWeatherParams) -> dict:
    city = params.city
    # ここではダミーの天気データを返す
    conditions = ["晴れ", "曇り", "", ""]
    temp = random.randint(10, 30)
    condition = random.choice(conditions)
    return {"city": city, "temperature": f"{temp}°C", "condition": condition}

async def main():
    client = CopilotClient()
    await client.start()

    session = await client.create_session({
        "model": "gpt-4.1",
        "streaming": True,
        "tools": [get_weather], # 使いたいツールをセッションに登録
    })

    def handle_event(event):
        if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
            sys.stdout.write(event.data.delta_content)
            sys.stdout.flush()

    session.on(handle_event)

    await session.send_and_wait({
        "prompt": "今日の東京の天気を教えてください。",
    })

    await client.stop()

asyncio.run(main())

10~30℃, ランダムに天気を返却するToolを用意し、それを用いてこのように返却してくれています。

image.png

双方向のやり取り

コマンドライン上で双方向のやり取りができるお天気アプリにしてみます。

...

print("🌤️  天気アシスタント (終了するには 'exit' と入力してください)")
    print("   試してみてください: 'パリの天気は?''東京とニューヨークの天気を比較して'\n")

    while True:
        try:
            user_input = input("You: ")
        except EOFError:
            break

        if user_input.lower() == "exit":
            break

        sys.stdout.write("Copilot: ")
        await session.send_and_wait({"prompt": user_input})
        print("\n")

    await client.stop()

...

こんな形で双方向のやり取りが実現できました。

image.png

感想

GitHub Copilotって今までAPI経由での呼び出しなどができない?少なくとも情報が少なく、OpenAIのサービスなどのようにアプリケーションに組み込むということができにくい状態でした。
それがこのCopilot SDKによってかなり楽に実装できるようになったと感じます。ストリーミングの機能などはSDKで実装するからこその特徴なのかなと思います。
Copilot CLIで使えた機能は基本的に全部使える状態みたいで、今回試していない機能(MCP呼び出し、カスタムエージェント、システムプロンプトなど)も一通り使えるので、このあたり活用しつつローカルで便利なアプリケーションが作れそうです!

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?