API
Информация для разработчиков.
NEW API DOCS:
Общая информация
На основе этого API вы можете создать свою программу, запрещенно использовать maria темплейты для проведения трансляций.
Во избежании утечки токена все запросы производите только через https!
Models
llm (gpt-3.5-turbo ссылается на эту модель) - мультиязычная модель, подходит для чата и instruct.
llm-vision-english (gpt-4-vision-preview ссылается на эту модель) - англоязычная модель, может распозновать изображения.
Получение токена
В вашей программе обязательно должна присутствовать возможность вставить свой API токен, вход по логину и паролю опциональная.
POST /api/v1/token/ с именем пользователя и паролем
curl --data "username=Vanya&password=123" https://bestwaifu.top/api/v1/token/
Вернет {"token": "MY_SUPER_TOKEN"}. Сохраните токен для последующих запросов.
Получение изображения
POST /api/v1/image
POST /sdapi/v1/txt2img
Authorization: Bearer MY_SUPER_TOKEN
Пример json:
{
# обязательные
"model": "sd1.5",
"text": "Космос и звёзды",
# или SD теги, только если не задан text
"prompt": "stars",
"negative_prompt": "",
# не обязательные (по умолчанию), n_iter - количество изображений 1-12, width и height 320-752px должно делиться на 8
"steps": 25,
"width": 512,
"height": 512,
"n_iter": 1,
# Для дополнительной информации о запросе
"name": "my_super_request_name", # reason (completion, embedding, summarization) just information.
"caller_name": "my_super_answer", # function (module) that called it: user.module. For example "vanya123.completion".
"program_name": "my_super_program", # program name: user.program. For example "vanya123.webgui".
}
Получение ответа
https://github.com/ollama/ollama/blob/main/docs/openai.md
Добавлена поддержка vision!
POST /v1/chat/completions
POST /api/v1/completion/chat
Authorization: Bearer MY_SUPER_TOKEN
Пример запроса на python:
from openai import OpenAI
BESTWAIFU_API_KEY = 'write here your servet key'
client = OpenAI(base_url='https://bestwaifu.top/v1', api_key=BESTWAIFU_API_KEY)
stream = client.chat.completions.create(
model="llm",
messages=[{"role": "user", "content": "Say this is a test"}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
Пример запроса со зрением на python:
path = './test.jpeg'
def encode_image(image_path):
with open(image_path, 'rb') as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
base64_image = self.encode_image(path)
image_url = f"data:image/jpeg;base64,{base64_image}"
response = client.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": image_url
},
},
{"type": "text", "text": text},
],
}
],
)
answer_text = response.choices[0].message.content
print(answer_text)
Пример json:
{
# обязательные
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": "You are assistant, your name is Alice"}
{"role": "user", "content": "Hello"}
],
# Для дополнительной информации о запросе
"name": "my_super_request_name", # reason (completion, embedding, summarization) just information.
"caller_name": "my_super_answer", # function (module) that called it: user.module. For example "vanya123.completion".
"program_name": "my_super_program", # program name: user.program. For example "vanya123.webgui".
# обязательные для темплейтов
"template_model": "gpt-3.5-turbo",
"language_code": "ru",
# не обязательные
"stream": false,
"return_type": "json", # json or sse, default sse
"temperature": 1.0,
"max_tokens": 1000,
"presence_penalty": 0.0,
"frequency_penalty": 0.0,
"logit_bias": {12345: 10}
"log_probs": false,
"response_format": "auto",
"seed": 1,
"stop": ["Мария:"],
"tool_choice": "auto",
"tools": # ?
"top_logprobs": 0,
"top_p": 0.0
}
Ответ потоковый json (content_type='application/x-ndjson'): {}\n{}\n{} (Для json ответа передайте "return_type": "json")
Ответ потоковый sse: data: {}\n\ndata: {}\n\ndata {}\n\ndata: [DONE]\n\n.
Пример ответа json:
# первая и последняя строчка содержит информацию по запросу
{"uid": 1, "text": "", "finish_reason": null}\n
{"text": "", "finish_reason": null}\n
{"text": "\\u041f\\u0440", "finish_reason": null}\n
{"text": "\\u0438\\u0432", "finish_reason": null}\n
{"text": "\\u0435\\u0442", "finish_reason": null}\n
{"text": "!", "finish_reason": null}\n
{"text": " \\u041a", "finish_reason": null}\n
{"text": "\\u0430\\u043a", "finish_reason": null}\n
{"text": " \\u044f", "finish_reason": null}\n
{"text": " \\u043c", "finish_reason": null}\n
{"text": "\\u043e\\u0433", "finish_reason": null}\n
{"text": "\\u0443", "finish_reason": null}\n
{"text": " \\u043f\\u043e\\u043c", "finish_reason": null}\n
{"text": "\\u043e\\u0447", "finish_reason": null}\n
{"text": "\\u044c", "finish_reason": null}\n
{"text": " \\u0432", "finish_reason": null}\n
{"text": "\\u0430\\u043c", "finish_reason": null}\n
{"text": " \\u0441", "finish_reason": null}\n
{"text": "\\u0435\\u0433", "finish_reason": null}\n
{"text": "\\u043e\\u0434", "finish_reason": null}\n
{"text": "\\u043d\\u044f", "finish_reason": null}\n
{"text": "?", "finish_reason": null}\n
{"text": null, "finish_reason": "stop"}\n
{"tokens_in": 20, "waifutokens_in": 200, "tokens_out": 20, "waifutokens_out": 300}
Ошибка во время получения частей, нужно повторить запрос:
{"text": "", "finish_reason": null}'
{"text": "\\u041f\\u0440", "finish_reason": null}
{"text": "\\u0438\\u0432", "finish_reason": null}
{"text": "\\u0435\\u0442", "finish_reason": null}
{"text": "!", "finish_reason": null}
{'error': 'getting chunk error'}
400 - Ошибка запроса перед генерацией ответа, ответ не потоковый json:
{"error": "not enough waifutokens", "waifutokens": 11, "waifutokens_in": 83}
400 - неверные данные:
{"error": "name not specified"}
429 - Too many requests, wait in seconds:
{
"error": "too many requests",
"wait": 20
}
500 - ошибка со стороны сервера или введены неверные данные.
Использование темплейтов
Ответ от Марии:
"messages": [
{"role": "system", "template": "maria_system"}
{"role": "user", "content": "Hello"}
]
История сообщений:
coming soon
Описание из Openai:
messages: A list of messages comprising the conversation so far.
[Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models).
model: ID of the model to use. See the
[model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility)
table for details on which models work with the Chat API.
frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their
existing frequency in the text so far, decreasing the model's likelihood to
repeat the same line verbatim.
[See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details)
logit_bias: Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in the
tokenizer) to an associated bias value from -100 to 100. Mathematically, the
bias is added to the logits generated by the model prior to sampling. The exact
effect will vary per model, but values between -1 and 1 should decrease or
increase likelihood of selection; values like -100 or 100 should result in a ban
or exclusive selection of the relevant token.
logprobs: Whether to return log probabilities of the output tokens or not. If true,
returns the log probabilities of each output token returned in the `content` of
`message`. This option is currently not available on the `gpt-4-vision-preview`
model.
max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat
completion.
The total length of input tokens and generated tokens is limited by the model's
context length.
[Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
for counting tokens.
presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on
whether they appear in the text so far, increasing the model's likelihood to
talk about new topics.
[See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details)
response_format: An object specifying the format that the model must output. Compatible with
[GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and
all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`.
Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the
message the model generates is valid JSON.
**Important:** when using JSON mode, you **must** also instruct the model to
produce JSON yourself via a system or user message. Without this, the model may
generate an unending stream of whitespace until the generation reaches the token
limit, resulting in a long-running and seemingly "stuck" request. Also note that
the message content may be partially cut off if `finish_reason="length"`, which
indicates the generation exceeded `max_tokens` or the conversation exceeded the
max context length.
seed: This feature is in Beta. If specified, our system will make a best effort to
sample deterministically, such that repeated requests with the same `seed` and
parameters should return the same result. Determinism is not guaranteed, and you
should refer to the `system_fingerprint` response parameter to monitor changes
in the backend.
stop: Up to 4 sequences where the API will stop generating further tokens.
temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
make the output more random, while lower values like 0.2 will make it more
focused and deterministic.
We generally recommend altering this or `top_p` but not both.
tool_choice: Controls which (if any) function is called by the model. `none` means the model
will not call a function and instead generates a message. `auto` means the model
can pick between generating a message or calling a function. Specifying a
particular function via
`{"type": "function", "function": {"name": "my_function"}}` forces the model to
call that function.
`none` is the default when no functions are present. `auto` is the default if
functions are present.
tools: A list of tools the model may call. Currently, only functions are supported as a
tool. Use this to provide a list of functions the model may generate JSON inputs
for.
top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return
at each token position, each with an associated log probability. `logprobs` must
be set to `true` if this parameter is used.
top_p: An alternative to sampling with temperature, called nucleus sampling, where the
model considers the results of the tokens with top_p probability mass. So 0.1
means only the tokens comprising the top 10% probability mass are considered.
We generally recommend altering this or `temperature` but not both.