Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Руководство [8.17] ›REST API ›API для вывода

API для выполнения вывода

Справочник по новым API

Для получения самых актуальных данных об API обратитесь к API для вывода.

Выполняет задачу вывода на входном тексте с помощью конечной точки вывода.

API для вывода позволяют использовать определенные сервисы, такие как встроенные модели машинного обучения (ELSER, E5), модели, загруженные через Eland, Cohere, OpenAI, Azure, Google AI Studio, Google Vertex AI, Anthropic, Watsonx.ai или Hugging Face. Для встроенных моделей и моделей, загруженных через Eland, API для вывода предлагают альтернативный способ использования и управления обученными моделями. Однако, если вы не планируете использовать API для вывода для использования этих моделей или хотите использовать модели, не относящиеся к NLP, используйте API моделей машинного обучения.

Запрос

POST /_inference/<inference_id>

POST /_inference/<task_type>/<inference_id>

Предварительные условия

  • Требуется monitor_inference право доступа к кластеру (встроенные inference_admin и inference_user роли предоставляют это право)

Описание

API для выполнения вывода позволяет использовать модели машинного обучения для выполнения определённых задач с данными, предоставляемыми в качестве входных данных. API возвращает ответ с результатами задач. Конечная точка вывода, которую вы используете, может выполнять одну конкретную задачу, определённую при создании конечной точки с помощью API создания API вывода.

Параметры пути

<inference_id>
(Обязательный, строка) Уникальный идентификатор конечной точки вывода.
<task_type>
(Необязательный, строка) Тип задачи вывода, которую выполняет модель.

Параметры запроса

timeout
(Необязательный, таймаут) Управляет временем ожидания завершения вывода. По умолчанию 30 секунд.

Тело запроса

input

(Обязательный, строка или массив строк) Текст, на котором необходимо выполнить задачу вывода. input может быть одной строкой или массивом.

Конечные точки вывода для типа задачи completion в настоящее время поддерживают только одну строку в качестве входных данных.

query
(Обязательный, строка) Только для rerank конечных точек вывода. Текст поискового запроса.
task_settings
(Необязательный, объект) Параметры задачи для отдельного запроса на вывод. Эти параметры специфичны для <task_type>, который вы указали, и переопределяют параметры задачи, указанные при инициализации службы.

Примеры

Пример с завершением

В следующем примере выполняется завершение на примере вопроса.

resp = client.inference.inference(
    task_type="completion",
    inference_id="openai_chat_completions",
    input="What is Elastic?",
)
print(resp)
response = client.inference.inference(
  task_type: 'completion',
  inference_id: 'openai_chat_completions',
  body: {
    input: 'What is Elastic?'
  }
)
puts response
const response = await client.inference.inference({
  task_type: "completion",
  inference_id: "openai_chat_completions",
  input: "What is Elastic?",
});
console.log(response);
POST _inference/completion/openai_chat_completions
{
  "input": "What is Elastic?"
}

API возвращает следующий ответ:

{
  "completion": [
    {
      "result": "Elastic is a company that provides a range of software solutions for search, logging, security, and analytics. Their flagship product is Elasticsearch, an open-source, distributed search engine that allows users to search, analyze, and visualize large volumes of data in real-time. Elastic also offers products such as Kibana, a data visualization tool, and Logstash, a log management and pipeline tool, as well as various other tools and solutions for data analysis and management."
    }
  ]
}
Пример с переранжированием

В следующем примере выполняется переранжирование на примере входных данных.

resp = client.inference.inference(
    task_type="rerank",
    inference_id="cohere_rerank",
    input=[
        "luke",
        "like",
        "leia",
        "chewy",
        "r2d2",
        "star",
        "wars"
    ],
    query="star wars main character",
)
print(resp)
response = client.inference.inference(
  task_type: 'rerank',
  inference_id: 'cohere_rerank',
  body: {
    input: [
      'luke',
      'like',
      'leia',
      'chewy',
      'r2d2',
      'star',
      'wars'
    ],
    query: 'star wars main character'
  }
)
puts response
const response = await client.inference.inference({
  task_type: "rerank",
  inference_id: "cohere_rerank",
  input: ["luke", "like", "leia", "chewy", "r2d2", "star", "wars"],
  query: "star wars main character",
});
console.log(response);
POST _inference/rerank/cohere_rerank
{
  "input": ["luke", "like", "leia", "chewy","r2d2", "star", "wars"],
  "query": "star wars main character"
}

API возвращает следующий ответ:

{
  "rerank": [
    {
      "index": "2",
      "relevance_score": "0.011597361",
      "text": "leia"
    },
    {
      "index": "0",
      "relevance_score": "0.006338922",
      "text": "luke"
    },
    {
      "index": "5",
      "relevance_score": "0.0016166499",
      "text": "star"
    },
    {
      "index": "4",
      "relevance_score": "0.0011695103",
      "text": "r2d2"
    },
    {
      "index": "1",
      "relevance_score": "5.614787E-4",
      "text": "like"
    },
    {
      "index": "6",
      "relevance_score": "3.7850367E-4",
      "text": "wars"
    },
    {
      "index": "3",
      "relevance_score": "1.2508839E-5",
      "text": "chewy"
    }
  ]
}
Пример с разреженным вложением

В следующем примере выполняется разреженное вложение на примере предложения.

resp = client.inference.inference(
    task_type="sparse_embedding",
    inference_id="my-elser-model",
    input="The sky above the port was the color of television tuned to a dead channel.",
)
print(resp)
response = client.inference.inference(
  task_type: 'sparse_embedding',
  inference_id: 'my-elser-model',
  body: {
    input: 'The sky above the port was the color of television tuned to a dead channel.'
  }
)
puts response
const response = await client.inference.inference({
  task_type: "sparse_embedding",
  inference_id: "my-elser-model",
  input:
    "The sky above the port was the color of television tuned to a dead channel.",
});
console.log(response);
POST _inference/sparse_embedding/my-elser-model
{
  "input": "The sky above the port was the color of television tuned to a dead channel."
}

API возвращает следующий ответ:

{
  "sparse_embedding": [
    {
      "port": 2.1259406,
      "sky": 1.7073475,
      "color": 1.6922266,
      "dead": 1.6247464,
      "television": 1.3525393,
      "above": 1.2425821,
      "tuned": 1.1440028,
      "colors": 1.1218185,
      "tv": 1.0111054,
      "ports": 1.0067928,
      "poem": 1.0042328,
      "channel": 0.99471164,
      "tune": 0.96235967,
      "scene": 0.9020516,
      (...)
    },
    (...)
  ]
}
Пример с вложением текста

В следующем примере выполняется вложение текста на примере предложения с использованием интеграции Cohere.

resp = client.inference.inference(
    task_type="text_embedding",
    inference_id="my-cohere-endpoint",
    input="The sky above the port was the color of television tuned to a dead channel.",
    task_settings={
        "input_type": "ingest"
    },
)
print(resp)
const response = await client.inference.inference({
  task_type: "text_embedding",
  inference_id: "my-cohere-endpoint",
  input:
    "The sky above the port was the color of television tuned to a dead channel.",
  task_settings: {
    input_type: "ingest",
  },
});
console.log(response);
POST _inference/text_embedding/my-cohere-endpoint
{
  "input": "The sky above the port was the color of television tuned to a dead channel.",
  "task_settings": {
    "input_type": "ingest"
  }
}

API возвращает следующий ответ:

{
  "text_embedding": [
    {
      "embedding": [
        {
          0.018569946,
          -0.036895752,
          0.01486969,
          -0.0045204163,
          -0.04385376,
          0.0075950623,
          0.04260254,
          -0.004005432,
          0.007865906,
          0.030792236,
          -0.050476074,
          0.011795044,
          -0.011642456,
          -0.010070801,
          (...)
        },
        (...)
      ]
    }
  ]
}

© 2023-2025 Elasticsearch
As of September 2024, Elasticsearch is available under a choice of three licenses: the Server Side Public License (SSPL), the Elastic License, or the AGPLv3 (OSI approved).
Elasticsearch and the Elasticsearch logo are trademarks of Elasticsearch B.V., registered in the U.S. and in other countries.
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/post-inference-api.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API