Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new example: Contextual Chatbot using OpenAI, Astro, and Netlify + Blob storage #51

Merged
merged 5 commits into from
Apr 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
840 changes: 840 additions & 0 deletions examples/ai-chat-blob-context/.cursor/rules/netlify-development.mdc

Large diffs are not rendered by default.

27 changes: 27 additions & 0 deletions examples/ai-chat-blob-context/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# build output
dist/

# generated types
.astro/

# dependencies
node_modules/

# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*

# environment variables
.env
.env.production

# macOS-specific files
.DS_Store

# jetbrains setting folder
.idea/

# Local Netlify folder
.netlify
4 changes: 4 additions & 0 deletions examples/ai-chat-blob-context/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"recommendations": ["astro-build.astro-vscode"],
"unwantedRecommendations": []
}
11 changes: 11 additions & 0 deletions examples/ai-chat-blob-context/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}
Empty file.
17 changes: 17 additions & 0 deletions examples/ai-chat-blob-context/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// @ts-check
import { defineConfig } from 'astro/config';

import tailwindcss from '@tailwindcss/vite';
import netlify from '@astrojs/netlify';

import react from '@astrojs/react';

// https://astro.build/config
export default defineConfig({
vite: {
plugins: [tailwindcss()]
},

adapter: netlify(),
integrations: [react()]
});
75 changes: 75 additions & 0 deletions examples/ai-chat-blob-context/netlify/functions/chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type { Context } from "@netlify/functions";
import { getDeployStore } from "@netlify/blobs";
import OpenAI from "openai";

const CHAT_KEY = "current-chat";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

interface ChatMessage {
role: "user" | "assistant";
content: string;
}

export default async function(req: Request, context: Context) {
if (req.method !== "POST") {
return new Response("Method Not Allowed", { status: 405 });
}

try {
const { message, newConversation } = await req.json();
const store = getDeployStore("chat-history");


if (newConversation) {
await store.setJSON(CHAT_KEY, []);
return new Response(JSON.stringify({ success: true }));
}

if (!message) {
return new Response("Message is required", { status: 400 });
}

// Get history and update with user message
const history = (await store.get(CHAT_KEY, { type: "json" })) as ChatMessage[] || [];
const updatedHistory = [...history, { role: "user", content: message }];

// Stream the AI response
const stream = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: updatedHistory,
stream: true,
});

return new Response(
new ReadableStream({
async start(controller) {
let assistantMessage = '';
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content || "";
assistantMessage += text;
controller.enqueue(new TextEncoder().encode(text));
}

await store.setJSON(CHAT_KEY, [
...updatedHistory,
{ role: "assistant", content: assistantMessage }
]);
controller.close();
},
}),
{
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
},
}
);

} catch (error) {
console.error("Error:", error);
return new Response(JSON.stringify({ error: "Internal Server Error" }), {
status: 500,
});
}
}
Loading