> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/convai-playground/character-customization/external-api.md).

# 外部 API

了解如何集成和配置外部 API 功能，使角色能够访问实时信息、创建任务并与第三方平台交互。

## 简介

此 **外部 API** 功能可让您的角色智能地与实时数据源和第三方服务交互。无论是获取实时天气更新、追踪体育赛事比分，还是在 Jira 和 Trello 等平台中创建工单，此功能都能实现无缝的 API 集成。只需几个配置步骤，您的角色就能获取数据、触发工作流并执行自动化操作，从而大幅提升能力。

{% embed url="<https://www.youtube.com/watch?v=Ep1yUeu91FE>" %}

在编写方法之前，请先浏览 [外部 API 限制](https://docs.convai.com/api-docs/zh/convai-playground/character-customization/external-api/external-api-limitations.md) —了解支持的模型、Python 运行时、允许使用的库、输入架构以及每个角色的上限。API 参考文档中也链接到了同一页面。

***

## 配置和使用

### 1. 访问外部 API 页面

在控制面板中前往 **外部 API** 部分。在这里，您可以查看现有的 API 方法、启用或停用这些方法，以及创建新方法。要添加新的 API 方法，请点击 **添加 API 方法**.

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FcuDTHJE5qW2Olt7VLQYg%2FScreenshot%202025-08-09%20222338.png?alt=media&amp;token=e356bab4-a518-421d-9be2-9e06fb470405" alt=""><figcaption></figcaption></figure>

***

### 2. 创建 API 方法

**方法字段概览**

* **方法名称** – 选择现有模板，或为您的方法输入一个唯一名称。
* **方法描述** – 简要说明此方法的功能。
* **输入描述（JSON 格式）** – 定义必需的输入参数及其说明。
* **实现代码** – 编写用于实现 API 逻辑的 Python 代码。
* **输入** – 输入用于验证方法的测试参数。
* **输出** – 点击 **测试 API**.

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2F1B61FhWE2wDzVEelrm9w%2FScreenshot%202025-08-09%20222520.png?alt=media&amp;token=4c256d26-9373-4595-ae6a-f56822ef1d1b" alt=""><figcaption></figcaption></figure>

***

## 示例 1 – 获取天气数据

**方法名称**\
`Get Weather`

**方法描述**\
`Fetches current weather data for a given city`

**输入描述**

```json
{
    "parameters": {
        "city": {
            "type": "string",
            "description": "要获取天气信息的城市名称（例如：'London'、'New York'、'Tokyo'）"
        }
    },
    "required": [
        "city"
    ]
}
```

**实现代码**

```python
import requests

API_KEY = "<your-api-key>"

def handle_event(data):
    city = data.get("city")
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}"
    response = requests.get(url)
    weather_data = response.json()
    return {"weather": weather_data["weather"][0]["description"]}
```

**设置说明**

1. 在以下网站注册： [OpenWeatherMap](https://openweathermap.org/) 并获取你的 API 密钥。
2. 替换 `<your-api-key>` 代码中的占位内容为你的密钥。

**测试输入**

```json
{
  "city": "New York"
}
```

点击 **测试 API**.

**成功的输出示例：**

```json
{
  "weather": "clear sky"
}
```

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2F1B61FhWE2wDzVEelrm9w%2FScreenshot%202025-08-09%20222520.png?alt=media&amp;token=4c256d26-9373-4595-ae6a-f56822ef1d1b" alt=""><figcaption></figcaption></figure>

#### **启用该方法**

如果测试通过，请点击 **保存更改**，返回主 API 列表，然后切换 **连接** 使其变为绿色。

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FeDo9ll7ToGd9hH5RjBWr%2FScreenshot%202025-08-09%20222055.png?alt=media&amp;token=583e69d7-4cf8-49dc-9bc6-84345d12b64d" alt=""><figcaption></figcaption></figure>

#### **与角色进行测试**

启用后，在与角色的对话中测试该方法。\
如下面的屏幕截图所示，该角色正确返回了罗马和兰格尔当前的天气。

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2F3OibIcWvoDDlhgvS19jG%2FScreenshot%202025-08-09%20155243.png?alt=media&amp;token=69d5a27d-d63d-4288-80ac-2a6c056e1d55" alt=""><figcaption></figcaption></figure>

***

## 示例 2 – 创建 Jira 支持工单

**方法名称**\
`创建支持工单`

**方法描述**\
`在 Jira 上创建支持工单`

**输入描述**

```json
{
    "parameters": {
        "summary": {
            "type": "string",
            "description": "Jira 工单的简短标题"
        },
        "description": {
            "type": "string",
            "description": "Jira 问题的详细描述"
        }
    },
    "required": [
        "summary",
        "description"
    ]
}
```

**实现代码**

```python
import requests
from requests.auth import HTTPBasicAuth
import json

# Jira 配置
JIRA_DOMAIN = "mycompany.atlassian.net"  # 替换为你的 Jira 域名
EMAIL = "user@example.com"               # 替换为你的 Atlassian 账户邮箱
API_TOKEN = "abc123xyz456..."            # 替换为你的 Jira API 令牌
JIRA_PROJECT_KEY = "EX"                  # 替换为你的 Jira 项目键
ISSUE_TYPE = "Story"                     # 问题类型：Story、Task 或 Bug

API_ENDPOINT = f"https://{JIRA_DOMAIN}/rest/api/3/issue"

# JIRA 所需的标准标头。
headers = {"Accept": "application/json", "Content-Type": "application/json"}

def create_jira_ticket(ticket_data):
    """
    使用提供的 ticket_data 字典创建 JIRA 工单。

    预期的 ticket_data 键：
      - summary: (str) 问题的简要摘要。
      - description: (str) 问题的详细描述。

    返回：
      - 成功创建工单时返回 JSON 响应。
      - 发生错误时返回错误消息。
    """
    # 将纯文本描述转换为 Atlassian 文档格式
    description_adf = {
        "version": 1,
        "type": "doc",
        "content": [
            {
                "type": "paragraph",
                "content": [
                    {"type": "text", "text": ticket_data.get("description", "")}
                ],
            }
        ],
    }

    # 为 JIRA 问题构造请求负载
    payload = {
        "fields": {
            "project": {"key": JIRA_PROJECT_KEY},
            "summary": ticket_data.get("summary"),
            "description": description_adf,
            "issuetype": {"name": ISSUE_TYPE},
        }
    }

    # 将请求负载转换为 JSON 字符串
    payload_json = json.dumps(payload)

    # 向 JIRA API 端点发送 POST 请求
    response = requests.post(
        API_ENDPOINT,
        data=payload_json,
        headers=headers,
        auth=HTTPBasicAuth(EMAIL, API_TOKEN),
    )

    # 检查是否成功创建（HTTP 201 Created）
    if response.status_code == 201:
        return response.json()
    else:
        return {"error": f"Failed to create ticket: {response.status_code}"}


def handle_event(data):
    return create_jira_ticket(data)
```

**在哪里查找所需值**

* **JIRA\_DOMAIN** – 可在 Jira 账户 URL 中找到。例如：\
  `https://mycompany.atlassian.net` → `JIRA_DOMAIN = "mycompany.atlassian.net"`
* **EMAIL** – Atlassian 登录邮箱。
* **API\_TOKEN** – 在此处创建： [Atlassian API 令牌](https://id.atlassian.com/manage-profile/security/api-tokens).
* **JIRA\_PROJECT\_KEY** – 可在项目 URL 中找到，或查看项目名称旁的信息。
* **ISSUE\_TYPE** – 必须是 Jira 项目中有效的问题类型（Story、Task、Bug）。

**测试输入**

```json
{
  "summary": "This is to test ticket creation",
  "description": "Created using External API"
}
```

点击 **测试 API**.

**成功的输出示例：**

```json
{
  "id": "10004",
  "key": "EX-5",
  "self": "https://mycompany.atlassian.net/rest/api/3/issue/10004"
}
```

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FFFQFn3xKRpZU1dmqvlTw%2Fimage.png?alt=media&amp;token=4eb9086a-ff07-496c-90b2-8b5857d7f26e" alt=""><figcaption></figcaption></figure>

**启用该方法**\
如果测试通过，请点击 **保存更改**，返回主 API 列表，然后切换 **连接** ，使其变为绿色以启用该方法。

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FIchI8ffgB2yv5oF2XkXc%2FScreenshot%202025-08-09%20164455.png?alt=media&amp;token=ac07c7b5-0d68-4170-83a4-c14bcba0c03d" alt=""><figcaption></figcaption></figure>

**使用角色进行测试**\
激活后，请在与角色的对话中测试此方法。\
如下方截图所示，该角色成功创建了一个 Jira 工单，并返回了工单密钥。

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FThTEgrGnh2fHdyzAUmWe%2FScreenshot%202025-08-09%20164924.png?alt=media&amp;token=9467982f-3d96-4619-b029-6b4c38c6e76d" alt=""><figcaption></figcaption></figure>

***

## 限制与支持的环境

{% hint style="warning" %}
**支持的 LLM 模型**: GPT-4o、GPT-4o-mini、Claude-3.5、Claude 4.0
{% endhint %}

{% hint style="warning" %}
**最长执行时间**: 5 秒
{% endhint %}

{% hint style="warning" %}
**Python 版本**: 3.11
{% endhint %}

{% hint style="warning" %}
**可用的库**: 标准库 + requests
{% endhint %}

***

## 总结

通过配置 External API 功能，您可以将角色转变为强大的数据驱动型助手。无论是获取实时天气信息，还是直接在对话中创建 Jira 工单，可实现的功能都非常丰富。这种集成能力可支持高度交互、自动化且智能的工作流。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/convai-playground/character-customization/external-api.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
