Generate chat completions - Writer AI Studio
Chat Completion Endpoint
The chat completion endpoint allows you to create a conversation between a user and an AI-assisted chat model. This guide introduces the chat completion endpoint and shows how to create a multi-turn conversation with an LLM, where the conversation history is preserved so the model understands the context of the conversation.
You need an API key to access the Writer API. Get an API key by following the steps in the API quickstart. We recommend setting the API key as an environment variable in a .env file with the name WRITER_API_KEY.
Chat Completion Versus Text Generation
The chat completion endpoint is similar to the text generation endpoint, but it is designed to handle conversations between a user and an LLM. The chat completion endpoint can generate single messages, or create more complex conversations between a user and an LLM. The text generation endpoint is designed to generate a single text response based on a given prompt. Additionally, the chat completion endpoint offers tool calling, which you can use to access other LLMs, Knowledge Graphs, and custom functions.
Endpoint Overview
URL:POST https://api.writer.com/v1/chat
Using the /chat endpoint results in charges for model usage. See the pricing page for more information.
Example cURL Request
curl --location 'https://api.writer.com/v1/chat' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $WRITER_API_KEY" \
--data '{
"model": "palmyra-x5",
"messages": [
{
"role": "user",
"content": "You are an expert at writing concise product descriptions for an E-Commerce Retailer"
},
{
"role": "assistant",
"content": "Okay, great I can help write these descriptions. Do you have a specific product in mind?"
},
{
"role": "user",
"content": "Please write a one sentence product description for a cozy, stylish sweater suitable for both casual and formal occasions"
}
]
}'
Example Python Code
from writerai import Writer
# Initialize the client. If you don't pass the `api_key` parameter,
# the client looks for the `WRITER_API_KEY` environment variable.
client = Writer()
chat_response = client.chat.chat(
messages=[
{
"role": "user",
"content": "You are an expert at writing concise product descriptions for an E-Commerce Retailer"
},
{
"role": "assistant",
"content": "Okay, great I can help write these descriptions. Do you have a specific product in mind?"
},
{
"role": "user",
"content": "Please write a one sentence product description for a cozy, stylish sweater suitable for both casual and formal occasions"
}
],
model="palmyra-x5"
)
print(chat_response.choices[0].message.content)
Example JavaScript Code
import { Writer } from 'writer-sdk';
// Initialize the Writer client. If you don't pass the `apiKey` parameter,
// the client looks for the `WRITER_API_KEY` environment variable.
const client = new Writer();
const chatResponse = await client.chat.chat({
messages: [
{
role: "user",
content: "You are an expert at writing concise product descriptions for an E-Commerce Retailer"
},
{
role: "assistant",
content: "Okay, great I can help write these descriptions. Do you have a specific product in mind?"
},
{
role: "user",
content: "Please write a one sentence product description for a cozy, stylish sweater suitable for both casual and formal occasions"
}
],
model: 'palmyra-x5'
});
console.log(chatResponse.choices[0].message.content);
Request Body
Below are the required and commonly used optional parameters for the text generation endpoint.
| Parameter | Type | Description |
|---|---|---|
model |
string | Required. The ID of the model to use for the chat completion. This can be a Palmyra model like palmyra-x5 or palmyra-x4, or an external model configured for your organization. |
messages |
array | Required. The conversation history. |
messages[].role |
string | Required. The role of the message sender. Can be user, assistant, system, or tool. system messages are system prompts, used to provide instructions to the model. tool messages are the result of a tool call, and contain the output of the tool call. |
messages[].content |
string | Required. The content of the message. |
temperature |
float | Temperature influences the randomness in generated text. Defaults to 1. Increase the value for more creative responses, and decrease the value for more predictable responses. |
stream |
Boolean | A Boolean value that indicates whether to stream the response. Defaults to false. |
Response Parameters
Non-streaming Response
If you set the stream parameter to false, the response is delivered as a single JSON object. It contains several parameters describing the response, including the choices array, which contains the generated text.
| Parameter | Type | Description |
|---|---|---|
model |
string | The ID of the model used to generate the response. |
choices |
array | An array containing one object with the generated text and additional information. |
choices[0].message.content |
string | The generated text. |
Streaming Response
If you set the stream parameter to true, the response is delivered as server-sent events. The event contains several parameters. The content of the chunk is in the choices[0].delta.content parameter.
Sample Application
The following sample application uses the Python and JavaScript SDKs to create a command-line chatbot. The application asks the user for input, passes the conversation history to the LLM, and streams the response from the LLM. It loops until the user enters the message exit.
Best Practices
Follow these best practices to ensure that your chatbot behaves as expected:
- Use system messages: Including a system message can guide the behavior of the assistant, setting expectations for its tone and responsiveness.
- Maintain context: Ensure that all relevant parts of the conversation are included in the
messagesarray to maintain context, as the model doesn’t retain memory of past interactions. - Handle errors gracefully: Implement error handling for various HTTP status codes and API-specific errors such as rate limits or malformed requests.
- Manage conversational flow: Regularly review the conversation’s context and adjust it to keep interactions relevant and concise, especially under the model’s token limit.
Next Steps
Now that you’ve created a chatbot, learn how to add tool calling to your application to enhance the functionality with other LLMs, Knowledge Graphs, and custom functions.