Skip to content

Use Convex + Hono to power chat app #3

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
62 changes: 15 additions & 47 deletions convex/http.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { httpRouter } from "convex/server";
import { httpAction } from "./_generated/server";
import { Hono } from "hono";
import { HonoWithConvex, HttpRouterWithHono } from "convex-helpers/server/hono";
import { ActionCtx } from "./_generated/server";
import { cors } from "hono/cors";
import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";

export const chat = httpAction(async (ctx, req) => {
const app: HonoWithConvex<ActionCtx> = new Hono();

// See the [guide on Stack](https://stack.convex.dev/hono-with-convex)
// for tips on using Hono for HTTP endpoints.

app.use("/api/*", cors());

app.post("/api/chat", async (c) => {
// Extract the `messages` from the body of the request
const { messages } = await req.json();
const { messages } = await c.req.json();

// Call the language model
const result = await streamText({
Expand All @@ -19,48 +28,7 @@ export const chat = httpAction(async (ctx, req) => {
});

// Respond with the stream
return result.toAIStreamResponse({
headers: {
// e.g. https://mywebsite.com, configured on your Convex dashboard
"Access-Control-Allow-Origin": "*",
Vary: "origin",
},
});
});

const http = httpRouter();

http.route({
path: "/api/chat",
method: "POST",
handler: chat,
});

http.route({
path: "/api/chat",
method: "OPTIONS",
handler: httpAction(async (_, request) => {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
const headers = request.headers;
if (
headers.get("Origin") !== null &&
headers.get("Access-Control-Request-Method") !== null &&
headers.get("Access-Control-Request-Headers") !== null
) {
return new Response(null, {
headers: new Headers({
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Digest",
"Access-Control-Max-Age": "86400",
}),
});
} else {
return new Response();
}
}),
return result.toAIStreamResponse();
});

// Convex expects the router to be the default export of `convex/http.js`.
export default http;
export default new HttpRouterWithHono(app);
Loading