The official TypeScript library for the OpenAI API
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Manage persistent conversation state independently of threads. The Conversations API provides a stateful conversation interface where messages and tool calls are stored as items, enabling complex multi-turn interactions with full history management.
Create and manage conversations with persistent state.
/**
* Create a new conversation
* @param params - Conversation creation parameters
* @returns Conversation object with unique identifier
*/
function create(
params?: ConversationCreateParams
): Promise<Conversation>;
/**
* Retrieve conversation information
* @param conversationID - Unique identifier for the conversation
* @returns Conversation object with metadata
*/
function retrieve(conversationID: string): Promise<Conversation>;
/**
* Update conversation metadata
* @param conversationID - Unique identifier for the conversation
* @param params - Update parameters including metadata
* @returns Updated conversation object
*/
function update(
conversationID: string,
params: ConversationUpdateParams
): Promise<Conversation>;
/**
* Delete a conversation (items in the conversation will not be deleted)
* @param conversationID - Unique identifier for the conversation
* @returns Deletion confirmation
*/
function delete(conversationID: string): Promise<ConversationDeletedResource>;
interface ConversationCreateParams {
/** Initial items to include in the conversation context (up to 20 items) */
items?: Array<ResponseInputItem> | null;
/** Set of 16 key-value pairs for storing additional information */
metadata?: Metadata | null;
}
interface ConversationUpdateParams {
/** Set of 16 key-value pairs for storing additional information */
metadata: Metadata | null;
}Usage Examples:
import OpenAI from "openai";
const client = new OpenAI();
// Create a new conversation
const conversation = await client.conversations.create({
metadata: {
user_id: "user_123",
session: "chat_session_1",
},
});
console.log(`Conversation created: ${conversation.id}`);
// Retrieve conversation details
const retrieved = await client.conversations.retrieve(conversation.id);
console.log(`Created at: ${new Date(retrieved.created_at * 1000)}`);
// Update conversation metadata
const updated = await client.conversations.update(conversation.id, {
metadata: {
user_id: "user_123",
session: "chat_session_1",
status: "active",
},
});
// Delete a conversation
const result = await client.conversations.delete(conversation.id);
console.log(`Conversation deleted: ${result.deleted}`);Manage individual items (messages, tool calls, etc.) within conversations.
/**
* Create items in a conversation
* @param conversationID - Unique identifier for the conversation
* @param params - Item creation parameters
* @returns List of created items
*/
function conversations.items.create(
conversationID: string,
params: ItemCreateParams
): Promise<ConversationItemList>;
/**
* Retrieve a single item from a conversation
* @param itemID - Unique identifier for the item
* @param params - Parameters including conversation_id
* @returns Conversation item object
*/
function conversations.items.retrieve(
itemID: string,
params: ItemRetrieveParams
): Promise<ConversationItem>;
/**
* List all items for a conversation
* @param conversationID - Unique identifier for the conversation
* @param params - List parameters for pagination and filtering
* @returns Paginated list of conversation items
*/
function conversations.items.list(
conversationID: string,
params?: ItemListParams
): Promise<ConversationItemsPage>;
/**
* Delete an item from a conversation
* @param itemID - Unique identifier for the item
* @param params - Parameters including conversation_id
* @returns Updated conversation object
*/
function conversations.items.delete(
itemID: string,
params: ItemDeleteParams
): Promise<Conversation>;
interface ItemCreateParams {
/** The items to add to the conversation (up to 20 items at a time) */
items: Array<ResponseInputItem>;
/** Additional fields to include in the response */
include?: Array<ResponseIncludable>;
}
interface ItemRetrieveParams {
/** The ID of the conversation that contains the item */
conversation_id: string;
/** Additional fields to include in the response */
include?: Array<ResponseIncludable>;
}
interface ItemListParams {
/** Additional output data to include in the response */
include?: Array<ResponseIncludable>;
/** The order to return items in ('asc' or 'desc', default 'desc') */
order?: "asc" | "desc";
/** Maximum number of items to return */
limit?: number;
/** Cursor for fetching the next page of results */
after?: string;
/** Cursor for fetching the previous page of results */
before?: string;
}
interface ItemDeleteParams {
/** The ID of the conversation that contains the item */
conversation_id: string;
}Usage Examples:
// Create conversation items (messages)
const items = await client.conversations.items.create(conversation.id, {
items: [
{
type: "message",
role: "user",
content: [
{
type: "input_text",
text: "Hello! Can you help me with Python?",
},
],
},
],
});
console.log(`Added ${items.data.length} items`);
// Retrieve a specific item
const item = await client.conversations.items.retrieve(items.data[0].id, {
conversation_id: conversation.id,
});
// List all items in the conversation
for await (const item of client.conversations.items.list(conversation.id, {
order: "asc",
include: ["message.output_text.logprobs"],
})) {
if (item.type === "message") {
console.log(`${item.role}: ${JSON.stringify(item.content)}`);
}
}
// Delete an item
await client.conversations.items.delete(items.data[0].id, {
conversation_id: conversation.id,
});interface Conversation {
/** The unique ID of the conversation */
id: string;
/** Unix timestamp (seconds) when the conversation was created */
created_at: number;
/** Key-value pairs attached to the conversation (max 16 pairs) */
metadata: unknown;
/** The object type, which is always 'conversation' */
object: "conversation";
}
interface ConversationDeletedResource {
id: string;
deleted: boolean;
object: "conversation.deleted";
}Conversation items can be various types including messages, tool calls, and their outputs:
/** Union type representing all possible conversation item types */
type ConversationItem =
| Message
| ResponseFunctionToolCallItem
| ResponseFunctionToolCallOutputItem
| ResponseFileSearchToolCall
| ResponseFunctionWebSearch
| ImageGenerationCall
| ResponseComputerToolCall
| ResponseComputerToolCallOutputItem
| ResponseReasoningItem
| ResponseCodeInterpreterToolCall
| LocalShellCall
| LocalShellCallOutput
| ResponseFunctionShellToolCall
| ResponseFunctionShellToolCallOutput
| ResponseApplyPatchToolCall
| ResponseApplyPatchToolCallOutput
| McpListTools
| McpApprovalRequest
| McpApprovalResponse
| McpCall
| ResponseCustomToolCall
| ResponseCustomToolCallOutput;interface Message {
/** The unique ID of the message */
id: string;
/** The content of the message */
content: Array<
| ResponseInputText
| ResponseOutputText
| TextContent
| SummaryTextContent
| ReasoningText
| ResponseOutputRefusal
| ResponseInputImage
| ComputerScreenshotContent
| ResponseInputFile
>;
/** The role of the message */
role:
| "unknown"
| "user"
| "assistant"
| "system"
| "critic"
| "discriminator"
| "developer"
| "tool";
/** The status of item */
status: "in_progress" | "completed" | "incomplete";
/** The type of the message, always 'message' */
type: "message";
}interface TextContent {
text: string;
type: "text";
}
interface SummaryTextContent {
/** A summary of the reasoning output from the model so far */
text: string;
/** The type of the object, always 'summary_text' */
type: "summary_text";
}
interface ComputerScreenshotContent {
/** The identifier of an uploaded file that contains the screenshot */
file_id: string | null;
/** The URL of the screenshot image */
image_url: string | null;
/** Specifies the event type, always 'computer_screenshot' */
type: "computer_screenshot";
}interface ConversationItemList {
/** List of conversation items */
data: Array<ConversationItem>;
/** The ID of the first item in the list */
first_id: string;
/** Whether there are more items available */
has_more: boolean;
/** The ID of the last item in the list */
last_id: string;
/** The type of object returned, must be 'list' */
object: "list";
}The include parameter allows you to request additional data in responses:
web_search_call.action.sources - Include sources of web search tool callsweb_search_call.results - Include search results of web search tool callscode_interpreter_call.outputs - Include outputs of Python code executioncomputer_call_output.output.image_url - Include image URLs from computer callsfile_search_call.results - Include search results of file search tool callsmessage.input_image.image_url - Include image URLs from input messagesmessage.output_text.logprobs - Include log probabilities with assistant messagesreasoning.encrypted_content - Include encrypted reasoning tokens for stateless usageimport OpenAI from "openai";
const client = new OpenAI();
async function conversationWorkflow() {
// 1. Create a conversation with initial metadata
const conversation = await client.conversations.create({
metadata: {
user_id: "user_789",
topic: "python_help",
priority: "high",
},
});
console.log(`Conversation started: ${conversation.id}`);
// 2. Add user message
const userMessage = await client.conversations.items.create(conversation.id, {
items: [
{
type: "message",
role: "user",
content: [
{
type: "input_text",
text: "Can you explain list comprehensions in Python?",
},
],
},
],
});
// 3. Get model response using Responses API
const response = await client.responses.create({
model: "gpt-4",
conversation_id: conversation.id,
input: [
{
type: "message",
role: "user",
content: [
{
type: "input_text",
text: "Can you explain list comprehensions in Python?",
},
],
},
],
});
// 4. List all conversation items
console.log("\nConversation history:");
for await (const item of client.conversations.items.list(conversation.id, {
order: "asc",
})) {
if (item.type === "message") {
const textContent = item.content.find((c) => c.type === "output_text");
if (textContent && "text" in textContent) {
console.log(`${item.role}: ${textContent.text.substring(0, 100)}...`);
}
}
}
// 5. Update conversation metadata
await client.conversations.update(conversation.id, {
metadata: {
user_id: "user_789",
topic: "python_help",
priority: "high",
resolved: "true",
resolved_at: new Date().toISOString(),
},
});
// 6. Retrieve specific items
const firstItem = userMessage.data[0];
const retrievedItem = await client.conversations.items.retrieve(
firstItem.id,
{
conversation_id: conversation.id,
include: ["message.output_text.logprobs"],
}
);
console.log(`\nRetrieved item: ${retrievedItem.type}`);
// 7. Clean up (optional)
// Note: Deleting a conversation doesn't delete its items
const deleted = await client.conversations.delete(conversation.id);
console.log(`\nConversation deleted: ${deleted.deleted}`);
return conversation;
}
conversationWorkflow();Conversations are closely integrated with the Responses API:
// Create conversation
const conversation = await client.conversations.create();
// Use conversation_id in Responses API
const response = await client.responses.create({
model: "gpt-4",
conversation_id: conversation.id,
input: [
{
type: "message",
role: "user",
content: [{ type: "input_text", text: "Hello!" }],
},
],
});
// Items are automatically added to the conversation
const items = await client.conversations.items.list(conversation.id);
console.log(`Conversation now has ${items.data.length} items`);include parameter allows requesting additional data like log probabilitiesorder parameter controlling sort directionInstall with Tessl CLI
npx tessl i tessl/npm-openai