curl --request POST \
--url https://api.apiyi.com/v1/rerank \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data @- <<EOF
{
"model": "bge-reranker-v2-m3",
"query": "What are the must-see attractions in Hangzhou?",
"documents": [
"West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.",
"The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.",
"Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples."
]
}
EOFimport requests
url = "https://api.apiyi.com/v1/rerank"
payload = {
"model": "bge-reranker-v2-m3",
"query": "What are the must-see attractions in Hangzhou?",
"documents": ["West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.", "The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.", "Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples."]
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
model: 'bge-reranker-v2-m3',
query: 'What are the must-see attractions in Hangzhou?',
documents: [
'West Lake is Hangzhou\'s most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.',
'The Bund in Shanghai sits along the Huangpu River and is the city\'s signature landmark.',
'Lingyin Temple, in Hangzhou\'s West Lake district, is one of China\'s best-known Buddhist temples.'
]
})
};
fetch('https://api.apiyi.com/v1/rerank', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.apiyi.com/v1/rerank",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'model' => 'bge-reranker-v2-m3',
'query' => 'What are the must-see attractions in Hangzhou?',
'documents' => [
'West Lake is Hangzhou\'s most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.',
'The Bund in Shanghai sits along the Huangpu River and is the city\'s signature landmark.',
'Lingyin Temple, in Hangzhou\'s West Lake district, is one of China\'s best-known Buddhist temples.'
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.apiyi.com/v1/rerank"
payload := strings.NewReader("{\n \"model\": \"bge-reranker-v2-m3\",\n \"query\": \"What are the must-see attractions in Hangzhou?\",\n \"documents\": [\n \"West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.\",\n \"The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.\",\n \"Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples.\"\n ]\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.apiyi.com/v1/rerank")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"bge-reranker-v2-m3\",\n \"query\": \"What are the must-see attractions in Hangzhou?\",\n \"documents\": [\n \"West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.\",\n \"The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.\",\n \"Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples.\"\n ]\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.apiyi.com/v1/rerank")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"bge-reranker-v2-m3\",\n \"query\": \"What are the must-see attractions in Hangzhou?\",\n \"documents\": [\n \"West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.\",\n \"The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.\",\n \"Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples.\"\n ]\n}"
response = http.request(request)
puts response.read_body{
"results": [
{
"document": {
"text": "West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda."
},
"index": 0,
"relevance_score": 0.97265625
},
{
"document": {
"text": "Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples."
},
"index": 2,
"relevance_score": 0.1181640625
}
],
"usage": {
"prompt_tokens": 70,
"total_tokens": 91
}
}Справочник Rerank API
справочник API rerank bge-reranker-v2-m3 и интерактивная песочница: параметры /v1/rerank, структура ответа, таблица кодов ошибок и заметки по отладке.
curl --request POST \
--url https://api.apiyi.com/v1/rerank \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data @- <<EOF
{
"model": "bge-reranker-v2-m3",
"query": "What are the must-see attractions in Hangzhou?",
"documents": [
"West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.",
"The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.",
"Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples."
]
}
EOFimport requests
url = "https://api.apiyi.com/v1/rerank"
payload = {
"model": "bge-reranker-v2-m3",
"query": "What are the must-see attractions in Hangzhou?",
"documents": ["West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.", "The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.", "Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples."]
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
model: 'bge-reranker-v2-m3',
query: 'What are the must-see attractions in Hangzhou?',
documents: [
'West Lake is Hangzhou\'s most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.',
'The Bund in Shanghai sits along the Huangpu River and is the city\'s signature landmark.',
'Lingyin Temple, in Hangzhou\'s West Lake district, is one of China\'s best-known Buddhist temples.'
]
})
};
fetch('https://api.apiyi.com/v1/rerank', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.apiyi.com/v1/rerank",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'model' => 'bge-reranker-v2-m3',
'query' => 'What are the must-see attractions in Hangzhou?',
'documents' => [
'West Lake is Hangzhou\'s most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.',
'The Bund in Shanghai sits along the Huangpu River and is the city\'s signature landmark.',
'Lingyin Temple, in Hangzhou\'s West Lake district, is one of China\'s best-known Buddhist temples.'
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.apiyi.com/v1/rerank"
payload := strings.NewReader("{\n \"model\": \"bge-reranker-v2-m3\",\n \"query\": \"What are the must-see attractions in Hangzhou?\",\n \"documents\": [\n \"West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.\",\n \"The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.\",\n \"Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples.\"\n ]\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.apiyi.com/v1/rerank")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"bge-reranker-v2-m3\",\n \"query\": \"What are the must-see attractions in Hangzhou?\",\n \"documents\": [\n \"West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.\",\n \"The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.\",\n \"Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples.\"\n ]\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.apiyi.com/v1/rerank")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"bge-reranker-v2-m3\",\n \"query\": \"What are the must-see attractions in Hangzhou?\",\n \"documents\": [\n \"West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda.\",\n \"The Bund in Shanghai sits along the Huangpu River and is the city's signature landmark.\",\n \"Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples.\"\n ]\n}"
response = http.request(request)
puts response.read_body{
"results": [
{
"document": {
"text": "West Lake is Hangzhou's most famous attraction, known for Broken Bridge, Su Causeway and Leifeng Pagoda."
},
"index": 0,
"relevance_score": 0.97265625
},
{
"document": {
"text": "Lingyin Temple, in Hangzhou's West Lake district, is one of China's best-known Buddhist temples."
},
"index": 2,
"relevance_score": 0.1181640625
}
],
"usage": {
"prompt_tokens": 70,
"total_tokens": 91
}
}Bearer sk-your-api-key в
Authorization, затем нажмите кнопку отправки — тело примера уже заполнено.Справочник параметров
| Параметр | Тип | Обязательный | Примечания |
|---|---|---|---|
model | string | ✓ | Всегда bge-reranker-v2-m3, чувствительно к регистру (неверное имя возвращает 503, а не 404) |
query | string | ✓ | Поисковый запрос. Пустая строка возвращает 400 query is required |
documents | string[] | ✓ | Кандидаты. Только обычный массив строк; пустой массив возвращает 400 |
top_n | int | Возвращает top N. Если не указан / 0 / отрицательный, возвращается все; строка возвращает 400 | |
return_documents | bool | ⚠️ Не влияет на этот канал — текст всегда возвращается как эхо |
max_chunks_per_doc, rank_fields, truncate, …) молча игнорируются, а не отклоняются.
Примечания к ответу
{
"results": [
{ "document": { "text": "..." }, "index": 0, "relevance_score": 0.97265625 }
],
"usage": { "prompt_tokens": 70, "total_tokens": 91,
"input_tokens": 0, "output_tokens": 0 }
}
index— исходная позиция документа в массивеdocuments, который вы отправили. Используйте её, чтобы найти объект своего документа; не сопоставляйте по возвращённомуtext.relevance_score— диапазон 0–1. Сопоставимо только внутри одного запроса. Не сопоставимо между запросами, а в кросс-языковых случаях систематически ниже. См. обсуждение порога в обзоре.resultsвсегда отсортирован поrelevance_scoreпо убыванию; значенияindexполные и уникальные.- Считывайте usage из
prompt_tokens(query учитывается один раз + все документы) иtotal_tokens(query учитывается для каждой пары);input_tokens/output_tokensна этом канале всегда 0. Этот раунд не смог подтвердить по тарификации, какое поле является платным — считайте счёт из консоли авторитетным.
Коды ошибок
| HTTP | Сообщение | Причина и решение |
|---|---|---|
| 400 | query is required | query отсутствует или это пустая строка |
| 400 | documents is required | documents отсутствует или это пустой массив |
| 400 | Input should be a valid string | Вы передали объекты в documents; используйте обычные строки |
| 400 | cannot unmarshal string into ... top_n of type int | top_n была строкой; передайте integer |
| 400 | This model's maximum context length is 8192 tokens | Одна пара query-document превышает 8192 token; разбейте на части и повторите |
| 401 | Invalid token. | Неверный API key или отсутствует заголовок Authorization |
| 429 | upstream load saturated | Вы достигли upstream quota (TPM 20,000 / RPM 120). Оба варианта возвращают это же сообщение: ① более 4–5 одновременных выполняющихся запросов; ② более 20,000 накопленных token за минуту (один запрос на 1000 кандидатов уже превышает этот предел). Ограничьте параллельные запросы до 4, добавьте backoff и планируйте свои token. Эта quota расширяется — обратитесь в поддержку APIYI, если вам нужны большие объемы |
| 503 | Current group ... has no available channels for model | Имя модели указано с ошибкой (с учетом регистра) или у группы действительно нет канала. Сначала проверьте написание |
Content-Type: text/plain), шлюз вообще не читает поле model и возвращает тот же 503
с пустым именем модели — это выглядит как недоступность канала, но ею не является./rerank, и /v2/rerank (значение по умолчанию в Cohere v2 SDK)
возвращают HTTP 200 с HTML домашней страницы сайта, что на стороне клиента выглядит как
ответ, который невозможно разобрать. https://api.apiyi.com/v1/rerank — это единственный допустимый path.Заметки по отладке
Не тестируйте только на 3 кандидатах
Не тестируйте только на 3 кандидатах
Низкие оценки в межъязыковых тестах — это ожидаемо
Низкие оценки в межъязыковых тестах — это ожидаемо
Есть минимальный порог задержки около 2 секунд
Есть минимальный порог задержки около 2 секунд
Во время отладки можно исчерпать квоту
Во время отладки можно исчерпать квоту
Авторизации
Add the Authorization: Bearer YOUR_API_KEY request header
Тело
Always bge-reranker-v2-m3 (case-sensitive; a wrong name returns 503)
"bge-reranker-v2-m3"
The search query. An empty string returns 400
Candidate documents. Plain string array only — passing Cohere-style
[{"text": "..."}] objects returns 400. Cannot be empty. Keep to 100 or fewer.
Return the top N results. Omitting it, or passing 0 or a negative number, returns all. Must be an integer — a string returns 400. Does not affect usage: every candidate is scored regardless.
2
Whether to echo the document text in results.
Note: this parameter currently has no effect on this channel — document.text
is always echoed. If response size matters, map results back by index yourself
rather than relying on this flag to trim the payload.
true
Была ли эта страница полезной?