> 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": "晴空"
}
```

<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": "使用外部 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 %}

***

## 结论

通过配置外部 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.
