From 5e435b67dfcb1d0ec3df2a3ae0f0c8c281887fc0 Mon Sep 17 00:00:00 2001 From: Marco Braga Date: Wed, 26 Feb 2025 17:31:08 +0100 Subject: [PATCH] Added .env option to save OpenAI threadId on channel metadata (OPENAI_CHANNEL_THREADS). --- src/agents/openai/OpenAIAgent.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/agents/openai/OpenAIAgent.ts b/src/agents/openai/OpenAIAgent.ts index d91da84..c4c80a9 100644 --- a/src/agents/openai/OpenAIAgent.ts +++ b/src/agents/openai/OpenAIAgent.ts @@ -64,7 +64,25 @@ export class OpenAIAgent implements AIAgent { ], model: 'gpt-4o', }); - this.openAiThread = await this.openai.beta.threads.create(); + + const threadIdFromChannel = process.env.OPENAI_CHANNEL_THREADS as boolean | undefined; + if (threadIdFromChannel && this.channel.data?.openaiThreadId) { + this.openAiThread = await this.openai.beta.threads.retrieve( + this.channel.data?.openaiThreadId as string, + ); + } else { + this.openAiThread = await this.openai.beta.threads.create(); + + if (threadIdFromChannel) { + this.channel.updatePartial({ + set: { openaiThreadId: this.openAiThread.id }, + }); + } + } + + if (!this.openAiThread) { + throw new Error('Could not create or retrieve OpenAI thread'); + } this.chatClient.on('message.new', this.handleMessage); };