Пример инструмента настройки Dify
1. Погода (JSON)
{
"openapi": "3.1.0",
"info": {
"title": "Get weather data",
"description": "Retrieves current weather data for a location.",
"version": "v1.0.0"
},
"servers": [
{
"url": "https://weather.example.com"
}
],
"paths": {
"/location": {
"get": {
"description": "Get temperature for a specific location",
"operationId": "GetCurrentWeather",
"parameters": [
{
"name": "location",
"in": "query",
"description": "The city and state to retrieve the weather for",
"required": true,
"schema": {
"type": "string"
}
}
],
"deprecated": false
}
}
},
"components": {
"schemas": {}
}
}
Этот код представляет собой JSON-файл спецификации OpenAPI, описывающей API для получения данных о погоде. В двух словах, API позволяет пользователю запрашивать данные о погоде для определенного места.
"openapi": "3.1.0"
: Это указывает на то, что используемая версия спецификации OpenAPI - 3.1.0."info"
: В этом разделе содержится основная информация об API, включая название, описание и версию."servers"
: В этом разделе перечислены URL-адреса серверов для API."paths"
: В этом разделе определяются пути и операции API. В этом примере есть операция GET с путем/location
, который используется для получения погоды для определенного места. Для этой операции требуется файл с именемlocation
Параметр запроса, который является обязательным, имеет тип string."components"
: Этот раздел используется для определения шаблонов, используемых в API, но в данном примере он пуст.
В спецификации OpenAPIparameters
массив, определяющий входные параметры для операций API.parameters
определяет файл с именемlocation
Параметр запроса, который является обязательным, имеет тип string. Каждый параметр представляет собой объект, содержащий следующие свойства:
"name"
: Имя параметра."in"
: Местоположение параметра. Это может быть"query"
,"header"
,"path"
возможно"cookie"
."description"
: Описание параметра."required"
: Если дляtrue
Этот параметр необходим, если"schema"
: Тип данных параметра.
Ниже показаны 4 случая с учетом положения параметров:
- параметр заголовка для передачи ключа API в заголовке запроса.
- параметр path для указания идентификатора объекта, который нужно получить по пути URL.
- Параметр cookie, используемый для передачи идентификатора сеанса пользователя в cookie.
- Параметр запроса, добавляемый к URL, обычно используется для фильтрации информации.
Создайте пользовательский интерфейс инструмента:

Интерфейс интерфейса тестового инструмента:

2. Зоомагазин (YAML)
# Taken from https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v3.0/petstore.yaml
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: https://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
maximum: 100
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
maxItems: 100
items:
$ref: "#/components/schemas/Pet"
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
pet.yaml
это файл спецификации OpenAPI, который описывает и определяет интерфейс к API под названием "Swagger Petstore". В этом файле используется формат YAML, который является стандартом сериализации человекочитаемых данных для записи конфигурационных файлов. Этот файл дает четкое определение интерфейса API, чтобы разработчики знали, как взаимодействовать с API "Swagger Petstore". Основные части файла включают:
openapi
: Это поле определяет версию используемой спецификации OpenAPI, в данном случае "3.0.0".info
: В этом разделе содержится основная информация об API, включая версию, название и лицензию.servers
: В этом разделе задается URL-адрес сервера для API.paths
: В этом разделе определены все пути и операции API. Например./pets
Путь состоит из двух операций:get
ответить пениемpost
.get
Операция используется для перечисления всех домашних животных.post
Операции используются для создания нового питомца. Каждая операция имеет свои параметры, ответы и другие детали.components
: В этом разделе определены схемы многократного использования, которые могут быть использованы вpaths
Цитируется в разделе. Например.Pet
, иPets
ответить пениемError
Режим.

Преобразуйте приведенный выше файл YAML в формат JSON:
{
"openapi": "3.0.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"license": {
"name": "MIT"
}
},
"servers": [
{
"url": "https://petstore.swagger.io/v1"
}
],
"paths": {
"/pets": {
"get": {
"summary": "List all pets",
"operationId": "listPets",
"tags": ["pets"],
"parameters": [
{
"name": "limit",
"in": "query",
"description": "How many items to return at one time (max 100)",
"required": false,
"schema": {
"type": "integer",
"maximum": 100,
"format": "int32"
}
}
],
"responses": {
"200": {
"description": "A paged array of pets",
"headers": {
"x-next": {
"description": "A link to the next page of responses",
"schema": {
"type": "string"
}
}
},
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pets"
}
}
}
},
"default": {
"description": "unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
},
"post": {
"summary": "Create a pet",
"operationId": "createPets",
"tags": ["pets"],
"responses": {
"201": {
"description": "Null response"
},
"default": {
"description": "unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/pets/{petId}": {
"get": {
"summary": "Info for a specific pet",
"operationId": "showPetById",
"tags": ["pets"],
"parameters": [
{
"name": "petId",
"in": "path",
"required": true,
"description": "The id of the pet to retrieve",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Expected response to a valid request",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pet"
}
}
}
},
"default": {
"description": "unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Pet": {
"type": "object",
"required": ["id", "name"],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"Pets": {
"type": "array",
"maxItems": 100,
"items": {
"$ref": "#/components/schemas/Pet"
}
},
"Error": {
"type": "object",
"required": ["code", "message"],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}
}
3. Шаблон заготовки
{
"openapi": "3.1.0",
"info": {
"title": "Untitled",
"description": "Your OpenAPI specification",
"version": "v1.0.0"
},
"servers": [
{
"url": ""
}
],
"paths": {},
"components": {
"schemas": {}
}
}
Примечание: кажется, что формат JSON выглядит более интуитивно понятным.

Учебник по структурированному выводу:Как использовать объект jsonarray в Dify?
© заявление об авторских правах
Авторское право на статью Круг обмена ИИ Пожалуйста, не воспроизводите без разрешения.
Похожие статьи
Нет комментариев...