Chat completions
POST /v1/chat/completions sends a list of messages to a model. The model writes the next message. The request and the response have the same form as the OpenAI API.
Send a request#
curl "$EMBER_API_URL/v1/chat/completions" \
-H "Authorization: Bearer $EMBER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "<model ID>",
"messages": [
{
"role": "system",
"content": "You answer in one sentence."
},
{
"role": "user",
"content": "What is scale to zero?"
}
],
"temperature": 0.7,
"max_tokens": 256
}'
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ["EMBER_API_URL"] + "/v1",
api_key=os.environ["EMBER_API_KEY"],
)
reply = client.chat.completions.create(
model="<model ID>",
messages=[
{
"role": "system",
"content": "You answer in one sentence."
},
{
"role": "user",
"content": "What is scale to zero?"
}
],
temperature=0.7,
max_tokens=256,
)
print(reply.choices[0].message.content)
import OpenAI from "openai";
const client = new OpenAI({
baseURL: `${process.env["EMBER_API_URL"]}/v1`,
apiKey: process.env["EMBER_API_KEY"],
});
const reply = await client.chat.completions.create({
model: "<model ID>",
messages: [
{
role: "system",
content: "You answer in one sentence.",
},
{
role: "user",
content: "What is scale to zero?",
},
],
temperature: 0.7,
max_tokens: 256,
});
console.log(reply.choices[0]?.message.content);
// Cargo.toml:
// reqwest = { version = "0.13", features = ["json"] }
// serde_json = "1"
// tokio = { version = "1", features = ["full"] }
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = std::env::var("EMBER_API_URL")?;
let key = std::env::var("EMBER_API_KEY")?;
let body = json!({
"model": "<model ID>",
"messages": [
{
"role": "system",
"content": "You answer in one sentence."
},
{
"role": "user",
"content": "What is scale to zero?"
}
],
"temperature": 0.7,
"max_tokens": 256
});
let response = reqwest::Client::new()
.post(format!("{url}/v1/chat/completions"))
.bearer_auth(key)
.json(&body)
.send()
.await?
.error_for_status()?;
let reply: serde_json::Value = response.json().await?;
println!("{}", reply["choices"][0]["message"]["content"].as_str().unwrap_or(""));
Ok(())
}
Messages#
Each message has a role and a content. A request can have up to 2,048 messages.
| Role | Use |
|---|---|
system | Instructions for the model. Put it first. |
user | A message from the person or your application. |
assistant | An earlier answer of the model. |
tool | The result of a tool call. Set tool_call_id. |
The content can be text, or a list of parts. A part is text or an image. An image must be a data: URL of a PNG, JPEG or WebP file. The API refuses remote image URLs.
Sampling#
| Parameter | Range | Effect |
|---|---|---|
temperature | 0 to 2 | Low values give focused answers. High values vary more. |
top_p | 0 to 1 | Use only the most probable tokens up to this total probability. |
max_tokens | 1 to 131,072 | The longest answer in tokens. |
stop | Up to 4 strings | The model stops before it writes one of them. |
seed | An integer | The same seed and request give similar answers. |
n | 1 to 8 | The number of answers. |
presence_penalty | −2 to 2 | Positive values make new topics more likely. |
frequency_penalty | −2 to 2 | Positive values make repeated words less likely. |
Change temperature or top_p, but not both.
Streaming#
Set "stream": true to get the answer in pieces. The response is a server-sent event stream. Each event is data: and a JSON chunk. The last event is data: [DONE].
To get the token counts in the stream, set "stream_options": {"include_usage": true}. For a shared model, the usage chunk also has the cost of the request.
curl "$EMBER_API_URL/v1/chat/completions" \
-H "Authorization: Bearer $EMBER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "<model ID>",
"messages": [
{
"role": "user",
"content": "Count to five."
}
],
"temperature": 0.7,
"max_tokens": 256,
"stream": true
}'
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ["EMBER_API_URL"] + "/v1",
api_key=os.environ["EMBER_API_KEY"],
)
reply = client.chat.completions.create(
model="<model ID>",
messages=[
{
"role": "user",
"content": "Count to five."
}
],
temperature=0.7,
max_tokens=256,
stream=True,
)
for chunk in reply:
print(chunk.choices[0].delta.content or "", end="")
import OpenAI from "openai";
const client = new OpenAI({
baseURL: `${process.env["EMBER_API_URL"]}/v1`,
apiKey: process.env["EMBER_API_KEY"],
});
const reply = await client.chat.completions.create({
model: "<model ID>",
messages: [
{
role: "user",
content: "Count to five.",
},
],
temperature: 0.7,
max_tokens: 256,
stream: true,
});
for await (const chunk of reply) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
// Cargo.toml:
// reqwest = { version = "0.13", features = ["json", "stream"] }
// serde_json = "1"
// tokio = { version = "1", features = ["full"] }
// futures-util = "0.3"
use futures_util::StreamExt;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = std::env::var("EMBER_API_URL")?;
let key = std::env::var("EMBER_API_KEY")?;
let body = json!({
"model": "<model ID>",
"messages": [
{
"role": "user",
"content": "Count to five."
}
],
"temperature": 0.7,
"max_tokens": 256,
"stream": true
});
let response = reqwest::Client::new()
.post(format!("{url}/v1/chat/completions"))
.bearer_auth(key)
.json(&body)
.send()
.await?
.error_for_status()?;
// Server-sent events: one `data: {json}` line for each piece, then `data: [DONE]`.
let mut stream = response.bytes_stream();
let mut buffer: Vec<u8> = Vec::new();
while let Some(chunk) = stream.next().await {
buffer.extend_from_slice(&chunk?);
while let Some(end) = buffer.iter().position(|b| *b == b'\n') {
let line = String::from_utf8_lossy(&buffer[..end]).trim().to_string();
buffer.drain(..=end);
let Some(data) = line.strip_prefix("data: ") else { continue };
if data == "[DONE]" {
return Ok(());
}
let piece: serde_json::Value = serde_json::from_str(data)?;
print!("{}", piece["choices"][0]["delta"]["content"].as_str().unwrap_or(""));
}
}
Ok(())
}
JSON output#
Set response_format to get JSON. Use {"type": "json_object"} for any JSON object. Use {"type": "json_schema", "json_schema": {...}} to give a schema. Also tell the model in a message that you want JSON.
Support for each format depends on the model and its runtime. Examine the answer before you use it.
Tools#
Give the model up to 128 tools in tools. Each tool is a function with a name, a description and JSON Schema parameters. The model can answer with tool_calls. Run the tool in your application. Then send the result in a message with the role tool.
{
"type": "function",
"function": {
"name": "get_weather",
"description": "The weather now in a city",
"parameters": {
"type": "object",
"properties": { "city": { "type": "string" } },
"required": ["city"]
}
}
}
Use tool_choice to let the model choose, to stop tool calls, or to require one tool.
Prompt caching#
Requests that start with the same messages are faster when they go to the same replica. Set prompt_cache_key to the same value for each request of one conversation.
On a shared model, "prompt_cache_retention": "1h" keeps the prompt in the cache for 60 minutes. You pay for each token-minute that is held. A deployment refuses this field.
Response headers#
| Header | Meaning |
|---|---|
X-Request-Id | The ID of the request. Give it to support. |
X-Ember-Region | The region that answered. |
X-Ember-Cold-Start-Ms | The time that a cold start added, if there was one. |
X-Ember-Cost-Micro-Usd | The cost in micro-USD. Only for a shared model without streaming. |
Privacy#
Nuemetrix does not keep prompts or responses in logs. The field user is accepted for compatibility, and then dropped.