Skip to main content

Настройка агента Copilot для взаимодействия с платформой Copilot

Узнайте, как взаимодействовать с платформой Copilot путем отправки и получения событий, отправленных сервером, с помощью Агент Copilot.

Агенты Copilot взаимодействует с платформой Copilot в виде событий, отправляемых сервером (SSEs). Вместо того чтобы ожидать от платформы Copilot запрашивать обновление от агента или наоборот, вы можете использовать SSEs для отправки и получения обновлений на платформу в режиме реального времени.

Дополнительные сведения о SSES см. в документации по mdn.

Отправка событий, отправленных сервером

Агент должен отправлять только одну SSE для каждого взаимодействия с платформой Copilot. Существует четыре предопределенных SSES, которые может отправлять агент:

copilot_confirmation

copilot_confirmation SSE отправляет пользователю запрос на подтверждение действия. Эта служба SSE отправляется через тип события и поле данных. См. следующий код для примера copilot_confirmation SSE:

TypeScript
event: copilot_confirmation
data: {
    "type": "action",

Currently, action is the only supported value for type in copilot_confirmation.

    "title": "Turn off feature flag",

Title of the confirmation dialog shown to the user.

    "message": "Are you sure you wish to turn off the `copilot` feature flag?",

Confirmation message shown to the user.

    "confirmation": {
        "id": "id-123",
        "other": "identifier-as-needed",
    }
}

Optional field for the agent to include any data needed to uniquely identify this confirmation and take action once the decision is received from the client.

//
event: copilot_confirmation
data: {
    // Currently, `action` is the only supported value for `type` in `copilot_confirmation`.
    "type": "action",
    // Title of the confirmation dialog shown to the user.
    "title": "Turn off feature flag",
    // Confirmation message shown to the user.
    "message": "Are you sure you wish to turn off the `copilot` feature flag?",
    // Optional field for the agent to include any data needed to uniquely identify this confirmation and take action once the decision is received from the client.
    "confirmation": {
        "id": "id-123",
        "other": "identifier-as-needed",
    }
}

После того, как пользователь принимает или закрывает подтверждение, агент получает сообщение, аналогичное следующему примеру:

TypeScript
{
    "copilot_confirmations": [
        {
            "state": "accepted",

A string containing the state of the confirmation. This value is either accepted or dismissed.

            "confirmation": {
                "id": "id-123",
                "other": "identifier-as-needed",
            }
        }
    ]
}

An array of strings containing data identifying the relevant action.

//
{
    "copilot_confirmations": [
        {
            // A string containing the state of the confirmation. This value is either `accepted` or `dismissed`.
            "state": "accepted",
            // An array of strings containing data identifying the relevant action.
            "confirmation": {
                "id": "id-123",
                "other": "identifier-as-needed",
            }
        }
    ]
}

На основе значений в этом сообщении агент может завершить или отменить соответствующее действие.

copilot_errors

copilot_errors SSE отправляет платформу Copilot список возникших ошибок. Эта служба SSE отправляется через тип события и поле данных. См. следующий код для примера copilot_errors SSE:

TypeScript
event: copilot_errors
data: [{
    "type": "function",

A string that specifies the error's type. type can have a value of reference, function or agent.

    "code": "recentchanges",

A string controlled by the agent describing the nature of an error.

    "message": "The repository does not exist",

A string that specifies the error message shown to the user.

    "identifier": "github/hello-world"
}]

A string that serves as a unique identifier to link the error with other resources such as references or function calls.

//
event: copilot_errors
data: [{
    // A string that specifies the error's type. `type` can have a value of `reference`, `function` or `agent`.
    "type": "function",
    // A string controlled by the agent describing the nature of an error.
    "code": "recentchanges",
    // A string that specifies the error message shown to the user.
    "message": "The repository does not exist",
    // A string that serves as a unique identifier to link the error with other resources such as references or function calls.
    "identifier": "github/hello-world"
}]

copilot_references

Примечание.

Ссылки на отрисовку в настоящее время не поддерживаются для Copilot Chat в GitHub Mobile. Расширения, зависящие от ссылочной памяти для создания ответов, по-прежнему будут работать, но ссылки не будут отображаться пользователю.

copilot_references SSE отправляет пользователю список ссылок, используемых для создания ответа. Эта служба SSE отправляется через тип события и поле данных. См. следующий код для примера copilot_references SSE:

TypeScript
event: copilot_references
data: [{
    "type": "blackbeard.story",

A string that specifies the type of the reference.

    "id": "snippet",

A string that specifies the ID of the reference.

    "data": {
        "file": "story.go",
        "start": "0",
        "end": "13",
        "content": "func main()...writeStory()..."
    },

An optional field where the agent can include any data needed to uniquely identify this reference.

    "is_implicit": false,

An optional boolean that indicates if the reference was passed implicitly or explicitly.

    "metadata": {
        "display_name": "Lines 1-13 from story.go",
        "display_icon": "icon",
        "display_url": "http://blackbeard.com/story/1",
    }
}]

An optional field for the agent to include any metadata to display in the user's environment. If any of the below required fields are missing, then the reference will not be rendered in the UI.

//
event: copilot_references
data: [{
    // A string that specifies the type of the reference.
    "type": "blackbeard.story",
    // A string that specifies the ID of the reference.
    "id": "snippet",
    // An optional field where the agent can include any data needed to uniquely identify this reference.
    "data": {
        "file": "story.go",
        "start": "0",
        "end": "13",
        "content": "func main()...writeStory()..."
    },
    // An optional boolean that indicates if the reference was passed implicitly or explicitly.
    "is_implicit": false,
    // An optional field for the agent to include any metadata to display in the user's environment. If any of the below required fields are missing, then the reference will not be rendered in the UI.
    "metadata": {
        "display_name": "Lines 1-13 from story.go",
        "display_icon": "icon",
        "display_url": "http://blackbeard.com/story/1",

    }
}]

По умолчанию SSE

По умолчанию SSE отправляет пользователю общее сообщение чата. Эта служба SSE не именуется и отправляется исключительно через поле данных. См. следующий код для примера SSE по умолчанию:

data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-3.5-turbo-0125", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]}

Получение событий, отправленных сервером

Так же, как агент отправляет SSEs на платформу Copilot, он также получает resp_message SSE от платформы. Эта служба SSE содержит список сообщений от пользователя, а также необязательные данные, связанные с каждым из событий SSE, которые агент может отправлять. См. следующий пример кода для примера запроса curl на агент, содержащий сообщение:

curl --request POST \
    --url $AGENT_URL \
    --header 'Accept: application/json' \
    --header 'Content-Type: application/json' \
    --header "X-GitHub-Token: $RUNTIME_GENERATED_TOKEN" \
    --data '{
        "messages": [
            {
                "role": "user",
                "content": "What is a closure in javascript?",
                "copilot_references": []
            }
        ]
    }'

Следующие шаги

Теперь, когда вы узнаете, как данные Агент Copilot взаимодействуют с платформой Copilot, вы можете узнать, как интегрировать агент с API GitHub . См . раздел AUTOTITLE.