Mở rộng Dựa trên API

Các nhà phát triển có thể mở rộng khả năng của các module thông qua module mở rộng API. Các module mở rộng hiện được hỗ trợ bao gồm:

  • moderation

  • external_data_tool

Trước khi mở rộng khả năng của module, chuẩn bị một API và một Khóa API để xác thực, có thể cũng tự động được tạo ra bởi ChatX. Ngoài việc phát triển các khả năng tương ứng của module, hãy tuân theo các đặc tả dưới đây để ChatX có thể gọi API của bạn một cách chính xác.

Thêm tiện ích mở rộng API

Thông số kỹ thuật API

ChatX sẽ gọi API của bạn theo các đặc tả sau đây:

POST {Your-API-Endpoint}
Header
Giá trị
Mô tả

Content-Type

application/json

Nội dung yêu cầu được trình bày dưới dạng JSON.

Authorization

Bearer {api_key}

API Key được chuyển đổi thành token. Bạn cần phân tích api_key và xác minh xem nó có khớp với API Key được cung cấp không để đảm bảo an ninh của API.

Request Body

{
    "point":  string, // Extension point, different modules may contain multiple extension points
    "params": {
        ...  // Parameters passed to each module's extension point
    }
}

API Response

{
    ...  // For the content returned by the API, see the specific module's design specifications for different extension points.
}

Kiểm tra

Khi cấu hình Phần mở rộng dựa trên API trong ChatX, ChatX sẽ gửi một yêu cầu đến Điểm cuối API để xác minh tính khả dụng của API. Khi Điểm cuối API nhận được point=ping, API nên trả về result=pong, như sau:

Header

Content-Type: application/json
Authorization: Bearer {api_key}

Request Body

{
    "point": "ping"
}

Phản hồi API dự kiến

{
    "result": "pong"
}

\

Ví dụ

Ở đây, chúng tôi lấy công cụ dữ liệu ngoại vi làm ví dụ, trong đó kịch bản là lấy thông tin thời tiết từ bên ngoài dựa trên vùng miền làm ngữ cảnh.

Các đặc tả API

POST https://fake-domain.com/api/dify/receive

Header

Content-Type: application/json
Authorization: Bearer 123456

Request Body

{
    "point": "app.external_data_tool.query",
    "params": {
        "app_id": "61248ab4-1125-45be-ae32-0ce91334d021",
        "tool_variable": "weather_retrieve",
        "inputs": {
            "location": "London"
        },
        "query": "How's the weather today?"
    }
}

Phản hồi API

{
    "result": "City: London\nTemperature: 10°C\nRealFeel®: 8°C\nAir Quality: Poor\nWind Direction: ENE\nWind Speed: 8 km/h\nWind Gusts: 14 km/h\nPrecipitation: Light rain"
}

Mã thử nghiệm

Mã nguồn dựa trên framework Python FastAPI.

Cài đặt các phụ thuộc.

pip install 'fastapi[all]' uvicorn

Viết mã theo các đặc tả giao diện.

from fastapi import FastAPI, Body, HTTPException, Header
from pydantic import BaseModel

app = FastAPI()


class InputData(BaseModel):
    point: str
    params: dict


@app.post("/api/dify/receive")
async def dify_receive(data: InputData = Body(...), authorization: str = Header(None)):
    """
    Receive API query data from Dify.
    """
    expected_api_key = "123456"  # TODO Your API key of this API
    auth_scheme, _, api_key = authorization.partition(' ')

    if auth_scheme.lower() != "bearer" or api_key != expected_api_key:
        raise HTTPException(status_code=401, detail="Unauthorized")

    point = data.point

    # for debug
    print(f"point: {point}")

    if point == "ping":
        return {
            "result": "pong"
        }
    if point == "app.external_data_tool.query":
        return handle_app_external_data_tool_query(params=data.params)
    # elif point == "{point name}":
        # TODO other point implementation here

    raise HTTPException(status_code=400, detail="Not implemented")


def handle_app_external_data_tool_query(params: dict):
    app_id = params.get("app_id")
    tool_variable = params.get("tool_variable")
    inputs = params.get("inputs")
    query = params.get("query")

    # for debug
    print(f"app_id: {app_id}")
    print(f"tool_variable: {tool_variable}")
    print(f"inputs: {inputs}")
    print(f"query: {query}")

    # TODO your external data tool query implementation here, 
    #  return must be a dict with key "result", and the value is the query result
    if inputs.get("location") == "London":
        return {
            "result": "City: London\nTemperature: 10°C\nRealFeel®: 8°C\nAir Quality: Poor\nWind Direction: ENE\nWind "
                      "Speed: 8 km/h\nWind Gusts: 14 km/h\nPrecipitation: Light rain"
        }
    else:
        return {"result": "Unknown city"}

Khởi chạy dịch vụ API.

Cổng mặc định là 8000. Địa chỉ hoàn chỉnh của API là: http://127.0.0.1:8000/api/chatx/receivevới Khóa API được định cấu hình '123456'.

uvicorn main:app --reload --host 0.0.0.0

Cấu hình API này trong ChatX.

Chọn phần mở rộng API này trong ứng dụng.

Khi gỡ lỗi ứng dụng, ChatX sẽ yêu cầu API được cấu hình và gửi nội dung sau (ví dụ):

{
    "point": "app.external_data_tool.query",
    "params": {
        "app_id": "61248ab4-1125-45be-ae32-0ce91334d021",
        "tool_variable": "weather_retrieve",
        "inputs": {
            "location": "London"
        },
        "query": "How's the weather today?"
    }
}

Phản hồi API:

{
    "result": "City: London\nTemperature: 10°C\nRealFeel®: 8°C\nAir Quality: Poor\nWind Direction: ENE\nWind Speed: 8 km/h\nWind Gusts: 14 km/h\nPrecipitation: Light rain"
}

Gỡ lỗi cục bộ

Vì phiên bản đám mây của ChatX không thể truy cập vào các dịch vụ API mạng nội bộ, bạn có thể sử dụng Ngrok để tiết lộ điểm cuối dịch vụ API cục bộ của mình cho internet công cộng để gỡ lỗi mã cục bộ dựa trên đám mây. Các bước là:

  1. Truy cập trang web chính thức của Ngrok tại https://ngrok.com, đăng ký và tải xuống tệp Ngrok.

  1. Sau khi tải xuống, đi đến thư mục tải xuống. Giải nén gói và chạy tập lệnh khởi tạo theo hướng dẫn:

$ unzip /path/to/ngrok.zip
$ ./ngrok config add-authtoken 你的Token
  1. Kiểm tra cổng dịch vụ API cục bộ của bạn.

Chạy lệnh sau để bắt đầu:

$ ./ngrok http [port number]

Khi khởi động thành công, bạn sẽ thấy một cái gì đó giống như sau:

  1. Tìm địa chỉ 'Forwarding', như tên miền mẫu https://177e-159-223-41-52.ngrok-free.app, và sử dụng nó như là tên miền công cộng của bạn.

  • Ví dụ, để tiết lộ dịch vụ đang chạy cục bộ của bạn, thay thế URL ví dụ http://127.0.0.1:8000/api/chatx/receive với https://177e-159-223-41-52.ngrok-free.app/api/chatx/receive.

Bây giờ, điểm cuối API này có thể truy cập công cộng. Bạn có thể cấu hình điểm cuối này trong ChatX để gỡ lỗi cục bộ. Đối với các bước cấu hình, hãy tham khảo tài liệu hoặc hướng dẫn thích hợp.

Triển khai phần mở rộng API với Cloudflare Workers

Chúng tôi khuyến nghị bạn sử dụng Cloudflare Workers để triển khai phần mở rộng API của mình, vì Cloudflare Workers có thể dễ dàng cung cấp một địa chỉ công cộng và có thể sử dụng miễn phí.

Tiết lộ Phần mở rộng API trên Internet công cộng bằng Cloudflare Workers