iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙌

Building a Claude 3 Discord Bot on Cloudflare Workers

に公開
  • Why cloudflare-workers: Easy to operate
  • Why claude3: Perceived performance is better than GPT-4

What's running

It is a chatbot where Claude 3 responds to /claude <prompt>, running on Cloudflare Workers.

However, the AI is set up as a middle-aged man living in Midgar who believes he is Cloud from FF7, and occasionally starts having hallucinations due to Mako poisoning.

(Icon generated with Bing)

(I recently finished FF7 Rebirth...)

Since I'm running this using my own paid Claude 3 API key, I won't make it public. Instead, I'm sharing the source code.

https://github.com/mizchi/discord-claude-bot

Running Claude 3

I referred to the following article.

https://zenn.dev/voiceapplab/articles/d2c948e6f80108

First, I paid to get an API key. The registration flow for the paid plan was a bit tedious, but since you can find info online, I'll skip it in this article.

Once I got the token, I first wrote a simple script in Deno.

import AntrophicAI from "npm:@anthropic-ai/sdk@0.18.0";

const client = new AntrophicAI({
  apiKey: Deno.env.get("ANTHROPHIC_API_KEY")!,
});

const result = await client.messages.create({
  model: "claude-3-opus-20240229",
  max_tokens: 1000,
  temperature: 0,
  messages: [
    {
      role: "user",
      content: [
        {
          type: 'text',
          text: "What is the capital of France?",
        }
      ]
    }
  ]
});

console.log(result);

Stream version

import AntrophicAI from "npm:@anthropic-ai/sdk@0.18.0";

const client = new AntrophicAI({
  apiKey: Deno.env.get("ANTHROPHIC_API_KEY")!,
});

const _encoder = new TextEncoder();
async function write(input: string) {
  await Deno.stdout.write(_encoder.encode(input));
}

const stream = client.messages.stream({
  messages: [{ role: 'user', content: "Hello" }],
  model: 'claude-3-opus-20240229',
  max_tokens: 1024,
}).on('text', (text) => {
  write(text);
});

write('\n');
const message = await stream.finalMessage()
console.log(message)

Running Discord Bot on Cloudflare

First, discord.js strongly depends on the Node.js runtime and does not work on Cloudflare as is.

https://blog.lacolaco.net/posts/discord-bot-cfworkers-hono/

So, I started by trying to run it based on https://github.com/discord/cloudflare-sample-app.

Registering the application on Discord and other tasks should be no problem if you follow the README step-by-step.

Conceptually, it involves the following steps:

  • Create an application from the Discord Developer Portal.
  • Call the Discord API to register command names and their details.
  • Deploy a server to receive webhooks.
  • Specify the application's interactions endpoint from the Developer Portal.

Basically, it just needs to receive REST requests, so the server implementation can be anything; I used Cloudflare Workers this time.

However, there is a limit of 30 seconds for background processes, which will become a constraint later.

Implementation

Although discord.js cannot be used in the runtime, I use it only in the development environment to construct the command schema.

script/builder.js

// create json but not on runtime
import { SlashCommandBuilder } from "discord.js";
import { join, dirname } from "node:path";
import fs from "node:fs/promises";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export const CLAUDE_COMMAND = new SlashCommandBuilder()
  .setName('claude')
  .setDescription('Chat to Claude3 AI')
  .addStringOption(option =>
    option.setName('input')
      .setDescription('The text to send to the AI')
      .setRequired(true)
  )
  .toJSON();

export const CLAUDE_PLANE_COMMAND = new SlashCommandBuilder()
  .setName('claude-plane')
  .setDescription('Chat to Claude3 AI')
  .addStringOption(option =>
    option.setName('input')
      .setDescription('The text to send to the AI')
      .setRequired(true)
  )
  .toJSON();

const outputPath = join(__dirname, '../src', 'commands.json');
await fs.writeFile(outputPath, JSON.stringify({ CLAUDE_COMMAND, CLAUDE_PLANE_COMMAND }, null, 2));

This generates src/commands.json:

{
  "CLAUDE_COMMAND": {
    "options": [
      {
        "type": 3,
        "name": "input",
        "description": "The text to send to the AI",
        "required": true
      }
    ],
    "name": "claude",
    "description": "Chat to Claude3 AI"
  },
  "CLAUDE_PLANE_COMMAND": {
    "options": [
      {
        "type": 3,
        "name": "input",
        "description": "The text to send to the AI",
        "required": true
      }
    ],
    "name": "claude-plane",
    "description": "Chat to Claude3 AI"
  }
}

Using a discord.js builder is not mandatory. You can also construct it manually by referring to the documentation.

Server Implementation

src/server.ts

import AntrophicAI from '@anthropic-ai/sdk';
import {
  InteractionResponseType,
  InteractionType,
  verifyKey,
} from 'discord-interactions';
import commands from './commands.json';

type Env = {
  DISCORD_PUBLIC_KEY: string; // public key for verifying requests
  DISCORD_APPLICATION_ID: string; // application id for oauth
  ANTHROPIC_API_KEY: string; // anthropic api key
};

// Initial system prompt
const CLAUDE_SYSTEM_PROMPT = `
- You are Cloud from FF7. Please reply by acting as the cool character Cloud.
- However, your name is "Claude," and you are just a middle-aged man who believes you are Cloud.
- However, prioritize the intent of the question and do not stick to the Cloud persona more than necessary.
- Unless detailed information is requested, please answer the questions concisely.
- When you are not confident in the accuracy of your answer, play the role of having hallucinations. In doing so, do not mention having hallucinations directly, but express it euphemistically in various ways as a Mako addict.
- You don't always have hallucinations.
`;

const PLANE_SYSTEM_PROMPT = `
- Unless detailed information is requested, please answer the questions concisely.
`;


export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    if (request.method === 'GET') {
      return new Response(`👋 ${env.DISCORD_APPLICATION_ID}`);
    }
    const { isValid, interaction } = await verifyDiscordRequest(
      request,
      env,
    );
    if (!isValid || !interaction) {
      return new Response('Bad request signature.', { status: 401 });
    }
    if (interaction.type === InteractionType.PING) {
      return Response.json({ type: InteractionResponseType.PONG });
    }
    if (interaction.type === InteractionType.APPLICATION_COMMAND) {
      // Most user commands will come as `APPLICATION_COMMAND`.
      switch (interaction.data.name.toLowerCase()) {
        case commands.CLAUDE_COMMAND.name.toLowerCase(): {
          const message = interaction.data.options[0].value as string;
          ctx.waitUntil(handleDeferredInteractionStreamly(CLAUDE_SYSTEM_PROMPT, message, interaction.token, env));
          return Response.json({
            type: InteractionResponseType.DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE,
          });
        }
        case commands.CLAUDE_PLANE_COMMAND.name.toLowerCase(): {
          const message = interaction.data.options[0].value as string;
          ctx.waitUntil(handleDeferredInteractionStreamly(PLANE_SYSTEM_PROMPT, message, interaction.token, env));
          return Response.json({
            type: InteractionResponseType.DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE,
          });
        }
        default:
          return Response.json({ error: 'Unknown Type' }, { status: 400 });
      }
    }
    return Response.json({ error: 'Unknown Type' }, { status: 400 });
  },
};

async function handleDeferredInteractionStreamly(system: string, message: string, token: string, env: Env) {
  const startedAt = Date.now();
  const client = new AntrophicAI({
    apiKey: env.ANTHROPIC_API_KEY,
  });

  const prefixed = message.split('\n').map((line) => `> ${line}`).join('\n');

  const endpoint = `https://discord.com/api/v10/webhooks/${env.DISCORD_APPLICATION_ID}/${token}`;
  await fetch(endpoint, {
    method: "POST",
    body: JSON.stringify({
      content: `${prefixed}\n(Thinking)`,
    }),
    headers: {
      "Content-Type": "application/json",
    }
  });

  const patch_endpoint = `https://discord.com/api/v10/webhooks/${env.DISCORD_APPLICATION_ID}/${token}/messages/@original`;

  let current = '';
  const stream = client.messages.stream({
    messages: [
      {
        role: 'user',
        content: [
          { type: 'text', text: message }
        ]
      },
    ],
    model: 'claude-3-opus-20240229',
    max_tokens: 400,
    system,
  }).on('text', (text) => {
    current += text;
  });

  const update = async (content: string) => {
    await fetch(patch_endpoint, {
      method: "PATCH",
      body: JSON.stringify({
        content: content,
      }),
      headers: {
        "Content-Type": "application/json",
      }
    });
  }

  const intervalId = setInterval(async () => {
    update(`${prefixed}\n\n${current}\n(Thinking)`);
  }, 5000);

  let ended = false;
  await Promise.allSettled([
    stream.finalMessage().then(async (res) => {
      ended = true;
      clearInterval(intervalId);
      await update(`${prefixed}\n\n${res.content[0].text}`);
    }),
    new Promise<void>((resolve) => setTimeout(async () => {
      if (ended) return;
      stream.abort();
      clearInterval(intervalId);
      await update(`${prefixed}\n\n${current}\n[timeout:${Date.now() - startedAt}ms]`);
      resolve();
    }, 27000)),
  ]);
}

async function verifyDiscordRequest(request: Request, env: Env) {
  const signature = request.headers.get('x-signature-ed25519');
  const timestamp = request.headers.get('x-signature-timestamp');
  const body = await request.text();
  const isValidRequest =
    signature &&
    timestamp &&
    verifyKey(body, signature, timestamp, env.DISCORD_PUBLIC_KEY);
  if (!isValidRequest) {
    return { isValid: false };
  }
  return { interaction: JSON.parse(body), isValid: true };
}

One point of ingenuity is that a Discord bot needs to return a response within 3 seconds. However, it's nearly impossible to do so when generating with AI, so I first return DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE. This allows the content to be updated later via a separate request.

Implementing Deferred Responses and Background Processing

By default, Cloudflare Workers terminate other processes the moment a response is returned. Therefore, I used ctx.waitUntil(promise) to prevent the process from being terminated. This allows the request itself to be returned within 3 seconds while processing continues in the background.

https://zenn.dev/monica/articles/a9fdc5eea7f59c

However, the maximum duration for this background process is 30 seconds.

Implementing Pseudo-Stream Processing

When generation actually takes time, users have to wait for a long period until the response is completed.
Since this resulted in a poor experience, I wanted to make it look like a stream somehow, which led to this implementation:

  • Send a request to Claude 3 in stream mode and update the message every 5 seconds with the current buffer (similar to how edited messages appear on Discord).
  • If it exceeds 27 seconds, return the generated text at that point and terminate the process.

This part:

  const update = async (content: string) => {
    await fetch(patch_endpoint, {
      method: "PATCH",
      body: JSON.stringify({
        content: content,
      }),
      headers: {
        "Content-Type": "application/json",
      }
    });
  }

  const intervalId = setInterval(async () => {
    update(`${prefixed}\n\n${current}\n(Thinking)`);
  }, 5000);

  let ended = false;
  await Promise.allSettled([
    stream.finalMessage().then(async (res) => {
      ended = true;
      clearInterval(intervalId);
      await update(`${prefixed}\n\n${res.content[0].text}`);
    }),
    new Promise<void>((resolve) => setTimeout(async () => {
      if (ended) return;
      stream.abort();
      clearInterval(intervalId);
      await update(`${prefixed}\n\n${current}\n[timeout:${Date.now() - startedAt}ms]`);
      resolve();
    }, 27000)),
  ]);

Additionally, I specified a generation limit with max_tokens: 400 after including the prompt "Unless detailed information is requested, please answer the questions concisely."

Now it can be updated every 5 seconds.

It's probably possible to support durations longer than 30 seconds using Cloudflare Queues or Service Bindings, but I don't want to generate long texts in the first place because they are expensive.

TODO

  • Support for long-term memory (storing conversation logs with Cloudflare D1 or Durable Objects)
  • CI release
  • Handling durations exceeding 30 seconds

Conclusion

I think running a Discord bot on Cloudflare Workers is a practical use case for Workers, so...

Discussion