> 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** 该功能使你的角色能够与实时数据源和第三方服务智能交互。无论是获取实时天气更新、跟踪体育比分，还是在 Jira 和 Trello 等平台中创建工单，此功能都支持无缝的基于 API 的集成。只需几个配置步骤，你的角色就能获取数据、触发工作流并执行自动化操作，从而显著提升能力。

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

***

## 配置与使用

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

导航到 **外部 API** 仪表板中的该部分。在这里，你可以查看现有的 API 方法，启用或停用它们，并创建新方法。要添加新的 API 方法，点击 **添加 API 方法**.

<figure><img src="/files/9aed50c359bd10b8cfafcec2c22fce91b786c61b" alt=""><figcaption></figcaption></figure>

***

### 2. 创建 API 方法

**方法字段概览**

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

<figure><img src="/files/b0a79ef03184aef500823efc0c7732468cae0e17" 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="/files/b0a79ef03184aef500823efc0c7732468cae0e17" alt=""><figcaption></figcaption></figure>

#### **激活该方法**

如果测试通过，点击 **保存更改**，返回主 API 列表，并通过切换 **连接** 为绿色来启用该方法。

<figure><img src="/files/739b9b0bb46ff774989ad2131eec97320084cc42" alt=""><figcaption></figcaption></figure>

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

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

<figure><img src="/files/d777d36f104bb64a4b1dbd858addb58cb8482346" 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"创建工单失败：{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": "这是用于测试工单创建的",
  "description": "使用外部 API 创建"
}
```

点击 **测试 API**.

**成功输出示例：**

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

<figure><img src="/files/b770e85d7dd045cc1cb21c8d9d77ea3ec33ec62c" alt=""><figcaption></figcaption></figure>

**激活该方法**\
如果测试通过，点击 **保存更改**，返回主 API 列表，并通过切换 **连接** 为绿色来启用该方法。

<figure><img src="/files/a2ecb5d1174d80968b18c0d3ba16ffa761cff1ec" alt=""><figcaption></figcaption></figure>

**与角色一起测试**\
激活后，在与角色的对话中测试该方法。\
如下图所示，角色成功创建了一个 Jira 工单并返回了工单键。

<figure><img src="/files/9f9428ac535b2d2cc9c1c11ec3f68973a8324fbb" 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.12
{% 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 dynamically by asking a question.

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

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

The question should be specific, self-contained, and written in natural language.
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.
