Tutorial: Chatbot in AstroJS with CloudFlare Workers AI (Part 2) - Coding the Backend
In this part of the tutorial, we will create a new API route in AstroJS to handle the requests from the client.
To streamline the process, we’ll create a single endpoint that accepts HTTP POST requests. This endpoint will receive the user’s message, forward it to the AI model, process the AI’s response, and return it to the client as a ReadableStream
.
Let’s create a new file named chatbot.ts
within the src/pages/api/
directory.
To begin, we’ll define the POST endpoint and handle the incoming client request:
We’ll extract the messages from the incoming request, parse them as a JSON object, and combine them with a system message (e.g., “You are a friendly assistant”). These messages will be formatted as a RoleScopedChatInput[]
array, a CloudFlare-specific type for model interactions.
This type should be available to you if you correctly configured the project as specified in the previous part of this tutorial.
To interact with the CloudFlare Model API, we’ll execute the following code:
To access the AI model we follow the next steps:
-
Environment Variable Retrieval: We leverage the
locals
object to access the previously configured environment variable namedAI
(refer to the prior tutorial section for setup details). This variable allows us to connect to the CloudFlare AI model. -
Error Handling: The code incorporates error-catching mechanisms to handle potential issues during AI model invocation. This is specially relevant when using a beta CloudFlare AI model.
-
Query to the model (Lines 11-14): These crucial lines make the actual API call to the CloudFlare AI model. Notably, the stream argument is set to true, indicating that the response should be returned as a
ReadableStream
.
The last step consists of preprocess the data a bit before sending it back to the client:
Each ReadableStream
chunk consists of a string formatted as data: {"response": "Hello, how are you?", "p": "abcdeaf.."}
. The stream concludes with a data: [DONE]
message. Our code extracts the “response” field from each chunk, encodes it, and transmits it to the client.
With this final data processing step, we’ve successfully completed the backend portion of our chatbot project. The next and final tutorial part will focus on creating the Astro component responsible for receiving the server response and displaying it within the browser.