Skip to content

Commit

Permalink
connect to supabase
Browse files Browse the repository at this point in the history
  • Loading branch information
Stan370 committed Sep 6, 2024
1 parent 3be60e6 commit bd29741
Show file tree
Hide file tree
Showing 6 changed files with 243 additions and 84 deletions.
2 changes: 2 additions & 0 deletions app/api/chat/openai/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { getServerConfig } from "@/config/server";
import { ServerRuntime } from "next";
import OpenAI from "openai";
import { OpenAIStream, StreamingTextResponse } from 'ai';


export const runtime: ServerRuntime = "edge";

Expand Down
50 changes: 36 additions & 14 deletions app/chat/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,27 +31,49 @@ const Chat = () => {
// Function to handle sending a message
const sendMessage = async () => {
const log = document.getElementById('chat-log');

if (message.trim()) {
setConversations([...conversations,
{ role: "user", content: message }]);

// Call API route and add AI message to conversations
const response = await fetch("/api/chat/openai", {
method: "POST",
body: message,
});
const data = await response.json();
if (data) {
{ role: "user", content: message }
]);

try {
// Call API route and add AI message to conversations
const response = await fetch("/api/chat/openai", {
method: "POST",
body: message,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
console.log(data);

// Add the assistant's response to the conversation
setConversations([
...conversations,
{ role: "assistant", content: data},
{ role: "assistant", content: data },
]);
} catch (error) {
console.error("Error during fetch:", error);
if (error instanceof TypeError && error.cause?.name === 'ConnectTimeoutError') {
console.error("Connection timeout error. Please check your network connection.");
// You can also update the UI to show a message to the user
setConversations([
...conversations,
{ role: "assistant", content: "Connection timeout error. Please check your network connection." },
]);
} else {
setConversations([
...conversations,
{ role: "assistant", content: "An error occurred while sending the message. Please check your OPENAI API KEY in the setting page." },
]);
}
}
// Reset the message input
setMessage("");
};
}
}
};
// Message input handler
const handleMessageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setMessage(event.target.value);
Expand Down
9 changes: 7 additions & 2 deletions config/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ declare global {
NEXT_PUBLIC_AZURE_GPT_35_TURBO_ID: string;
NEXT_PUBLIC_AZURE_GPT_45_VISION_ID: string;
NEXT_PUBLIC_AZURE_GPT_45_TURBO_ID: string;
NEXT_PUBLIC_SUPABASE_URL: string;
NEXT_PUBLIC_SUPABASE_ANON_KEY: string;
}
}
}
Expand All @@ -40,6 +42,8 @@ declare global {
NEXT_PUBLIC_AZURE_GPT_35_TURBO_ID,
NEXT_PUBLIC_AZURE_GPT_45_VISION_ID,
NEXT_PUBLIC_AZURE_GPT_45_TURBO_ID,
NEXT_PUBLIC_SUPABASE_URL,
NEXT_PUBLIC_SUPABASE_ANON_KEY,
} = process.env;

return {
Expand All @@ -57,9 +61,10 @@ declare global {
azureGpt35TurboId: NEXT_PUBLIC_AZURE_GPT_35_TURBO_ID,
azureGpt45VisionId: NEXT_PUBLIC_AZURE_GPT_45_VISION_ID,
azureGpt45TurboId: NEXT_PUBLIC_AZURE_GPT_45_TURBO_ID,
supabaseUrl: NEXT_PUBLIC_SUPABASE_URL,
supabaseAnonKey: NEXT_PUBLIC_SUPABASE_ANON_KEY,
};
};

// const express = require("express");
// const bodyParser = require("body-parser");
// const sqlite3 = require("sqlite3").verbose();
Expand Down Expand Up @@ -107,4 +112,4 @@ declare global {
// app.listen(port, () => {
// console.log(`Server is running on http://localhost:${port}`);
// });


81 changes: 13 additions & 68 deletions lib/supabase.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,17 @@
// import { createClient } from "@supabase/supabase-js";
import { createClient } from "@supabase/supabase-js";

// interface Client {
// url?: string;
// key?: string;
// }
interface Client {
url?: string;
key?: string;
}

// const client: Client = {
// url: process.env.NEXT_PUBLIC_SUPABASE_URL,
// key: process.env.SUPABASE_ANON_KEY
// };
const client: Client = {
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
key: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
};

// if (!client.url || !client.key) {
// throw new Error("Missing Supabase credentials");
// }
if (!client.url || !client.key) {
throw new Error("Missing Supabase credentials");
}

// export const supabaseClient = createClient(client.url!, client.key!);

// import { NextPage } from "next";
// import { useState } from "react";


// const Embeddings: NextPage = () => {
// const [urls, setUrls] = useState<string[]>([]);
// const [loading, setLoading] = useState(false);

// const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
// e.preventDefault();
// setLoading(true);

// const response = await fetch("/api/generate-embeddings", {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify({ urls })
// });

// setLoading(false);

// if (!response.ok) {
// // Handle error
// }
// };

// return (
// <div className="flex flex-col items-center max-w-xl m-auto text-center">
// <h1 className="w-full my-5 text-2xl font-bold sm:text-4xl ">
// Generate embeddings
// </h1>
// <p className="mb-4">
// Paste a list of URLs below to geneate embeddings using the OpenAI API, and add the embeddings to the Supabase embeddings table.
// </p>
// <form onSubmit={handleSubmit}>
// <textarea
// className="w-full h-[150px] textarea textarea-bordered"
// placeholder="Enter URLs here"
// value={urls.join("\n")}
// onChange={(e) => setUrls(e.target.value.split("\n"))}
// />
// <button
// className="my-4 btn btn-primary"
// type="submit"
// disabled={loading}
// >
// Generate Embeddings
// </button>
// </form>
// {loading && <div>Loading...</div>}
// </div>
// );
// };

// export default Embeddings;
export const supabaseClient = createClient(client.url!, client.key!);
Loading

0 comments on commit bd29741

Please sign in to comment.