The Assistants API allows you to create assistants, manage threads for conversations, and execute runs to generate responses.
Note: The Assistants, Threads, Messages, and Runs APIs are currently marked as beta in this client.
Workflow Summary
- Configure Client: Initialize
OpenAI with your API key. - Create Assistant: Define an assistant using
openAI.assistant(AssistantRequest(...)) specifying name, instructions, tools (e.g., AssistantTool.CodeInterpreter), and a ModelId. - Manage Threads: Create a conversation context using
openAI.thread(). Each end user should typically have their own thread. - Add Messages: Add user input to a thread using
openAI.message(threadId, MessageRequest(...)). - Execute Runs: Start the assistant's processing of the thread using
openAI.createRun(threadId, RunRequest(...)). You can provide additional instructions for the run here. - Poll for Completion: Since runs are asynchronous, poll the status using
openAI.getRun(threadId, runId) until the status reaches Status.Completed. - Retrieve Responses: Fetch the conversation history using
openAI.messages(threadId) and iterate through the content to find MessageContent.Text.
suspend fun main() {
// 1) Configure client
val token = System.getenv("OPENAI_API_KEY")
val openAI = OpenAI(token)
// 2) Create an assistant
val assistant = openAI.assistant(
request = AssistantRequest(
name = "Math Tutor",
instructions = "You are a personal math tutor. Write and run code to answer math questions.",
tools = listOf(AssistantTool.CodeInterpreter),
model = ModelId("gpt-4o-mini")
)
)
// 3) Create a thread
val thread = openAI.thread()
// 4) Add a user message to the thread
openAI.message(
threadId = thread.id,
request = MessageRequest(
role = Role.User,
content = "I need to solve the equation 3x + 11 = 14. Can you help me?"
)
)
// 5) Start a run
val run = openAI.createRun(
threadId = thread.id,
request = RunRequest(
assistantId = assistant.id,
instructions = "Please address the user as Jane Doe."
)
)
// 6) Poll until completed
var retrievedRun: Run
do {
delay(1500)
retrievedRun = openAI.getRun(threadId = thread.id, runId = run.id)
} while (retrievedRun.status != Status.Completed)
// 7) Read assistant messages
val messages = openAI.messages(thread.id)
println("Assistant response:")
for (message in messages) {
val text = message.content.firstOrNull() as? MessageContent.Text ?: continue
println(text.text.value)
}
}