> 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 限制](/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 – 获取天气数据

**方法名称**\
`获取天气`

**方法描述**\
`获取指定城市的当前天气数据`

**输入描述**

```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>

#### **与角色一起测试**

激活后，在与角色的对话中测试该方法。\
如下方截图所示，角色正确返回了 Roma 和 Wrangell 的当前天气。

<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 Document Format
    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"创建工单失败：{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 Tokens](https://id.atlassian.com/manage-profile/security/api-tokens).
* **JIRA\_PROJECT\_KEY** – 可在你的项目 URL 中或项目名称旁找到。
* **ISSUE\_TYPE** – 必须与你的 Jira 项目中有效的类型一致（Story、Task、Bug）。

**测试输入**

```json
{
  "summary": "这是用于测试工单创建的内容",
  "description": "使用 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
