postMessage method

Future<List<GptAssistantMessage>> postMessage({
  1. required String content,
  2. List<String> fileIds = const [],
})

Sends a message to the assistant. This will take care of creating the conversation thread as well as the run for each of the messages sent. It will also handle the periodic checks on the progress of the assistant and return when the assistant has completed. When done it returns all the messages in the assistant conversation.

Implementation

Future<List<GptAssistantMessage>> postMessage(
    {required String content, List<String> fileIds = const []}) async {
  if (runId != null) {
    throw Exception("Assistant busy.");
  }

  // If there is no thread active thread create it.
  if (threadId == null) {
    // Create thread
    GptThread currentThread = await client.createThread(
      request: CreateGptThreadRequest(
          /*
        messages: [
          GptThreadMessage(role: GptThreadRole.user, content: content)
        ],
        */
          ),
    );
    threadId = currentThread.id;
  }

  // Add message to thread
  GptAssistantMessage addedMessage = await client.createMessage(
    threadId: threadId!,
    request: CreateGptMessageRequest(
        fileIds: fileIds, content: content, role: GptThreadRole.user),
  );

  GptRun run = await client.createRun(
    threadId: threadId!,
    request: CreateGptRunRequest(
      assistantId: assistantId,
    ),
  );
  runId ??= run.id;

  // Add the user message to the history so it is reflected on the state update.
  List<GptAssistantMessage> currentHistory =
      List.of(_messageHistory ?? [], growable: true)..insert(0, addedMessage);
  do {
    _conversationProgressStream.add(AssistantConversationProgress(
        assistantId: assistantId,
        status: run.status,
        messages: currentHistory));
    await Future.delayed(statusCheckPeriod);
    run = await client.retrieveRun(threadId: threadId!, runId: runId!);
  } while (_isRunFinished(run: run));

  List<GptAssistantMessage> messages = await client.listMessages(
      threadId: threadId!, request: GetGptListRequest());

  _messageHistory = messages;

  _conversationProgressStream.add(AssistantConversationProgress(
      assistantId: assistantId,
      status: run.status,
      messages: _messageHistory!));

  runId = null;
  return messages;
}