|
| 1 | +import dotenv from "dotenv"; |
| 2 | +import clerk from "@clerk/clerk-sdk-node"; |
| 3 | +import { NextResponse } from "next/server"; |
| 4 | +import { currentUser } from "@clerk/nextjs"; |
| 5 | +import { rateLimit } from "@/app/utils/rateLimit"; |
| 6 | +import {Md5} from 'ts-md5' |
| 7 | +import ConfigManager from "@/app/utils/config"; |
| 8 | + |
| 9 | +dotenv.config({ path: `.env.local` }); |
| 10 | + |
| 11 | +function returnError(code: number, message: string) { |
| 12 | + return new NextResponse( |
| 13 | + JSON.stringify({ Message: message }), |
| 14 | + { |
| 15 | + status: code, |
| 16 | + headers: { |
| 17 | + "Content-Type": "application/json", |
| 18 | + }, |
| 19 | + } |
| 20 | + ); |
| 21 | +} |
| 22 | + |
| 23 | +export async function POST(req: Request) { |
| 24 | + let clerkUserId; |
| 25 | + let user; |
| 26 | + let clerkUserName; |
| 27 | + const { prompt, isText, userId, userName } = await req.json(); |
| 28 | + const companionName = req.headers.get("name"); |
| 29 | + |
| 30 | + // Load the companion config |
| 31 | + const configManager = ConfigManager.getInstance(); |
| 32 | + const companionConfig = configManager.getConfig("name", companionName); |
| 33 | + if (!companionConfig) { |
| 34 | + return returnError(404, `Hi, we were unable to find the configuration for a companion named ${companionName}.`) |
| 35 | + } |
| 36 | + |
| 37 | + // Make sure we're not rate limited |
| 38 | + const identifier = req.url + "-" + (userId || "anonymous"); |
| 39 | + const { success } = await rateLimit(identifier); |
| 40 | + if (!success) { |
| 41 | + console.log("INFO: rate limit exceeded"); |
| 42 | + return returnError(429, `Hi, the companions can't talk this fast.`) |
| 43 | + } |
| 44 | + |
| 45 | + if (!process.env.STEAMSHIP_API_KEY) { |
| 46 | + return returnError(500, `Please set the STEAMSHIP_API_KEY env variable and make sure ${companionName} is connected to an Agent instance that you own.`) |
| 47 | + } |
| 48 | + |
| 49 | + console.log(`Companion Name: ${companionName}`) |
| 50 | + console.log(`Prompt: ${prompt}`); |
| 51 | + |
| 52 | + if (isText) { |
| 53 | + clerkUserId = userId; |
| 54 | + clerkUserName = userName; |
| 55 | + } else { |
| 56 | + user = await currentUser(); |
| 57 | + clerkUserId = user?.id; |
| 58 | + clerkUserName = user?.firstName; |
| 59 | + } |
| 60 | + |
| 61 | + if (!clerkUserId || !!!(await clerk.users.getUser(clerkUserId))) { |
| 62 | + console.log("user not authorized"); |
| 63 | + return new NextResponse( |
| 64 | + JSON.stringify({ Message: "User not authorized" }), |
| 65 | + { |
| 66 | + status: 401, |
| 67 | + headers: { |
| 68 | + "Content-Type": "application/json", |
| 69 | + }, |
| 70 | + } |
| 71 | + ); |
| 72 | + } |
| 73 | + |
| 74 | + // Create a chat session id for the user |
| 75 | + const chatSessionId = Md5.hashStr(userId || "anonymous"); |
| 76 | + |
| 77 | + // Make sure we have a generate endpoint. |
| 78 | + // TODO: Create a new instance of the agent per user if this proves advantageous. |
| 79 | + const agentUrl = companionConfig.generateEndpoint |
| 80 | + if (!agentUrl) { |
| 81 | + return returnError(500, `Please add a Steamship 'generateEndpoint' to your ${companionName} configuration in companions.json.`) |
| 82 | + } |
| 83 | + |
| 84 | + // Invoke the generation. Tool invocation, chat history management, backstory injection, etc is all done within this endpoint. |
| 85 | + // To build, deploy, and host your own multi-tenant agent see: https://www.steamship.com/learn/agent-guidebook |
| 86 | + const response = await fetch(agentUrl, { |
| 87 | + method: "POST", |
| 88 | + headers: { |
| 89 | + "Content-Type": "application/json", |
| 90 | + "Authorization": `Bearer ${process.env.STEAMSHIP_API_KEY}` |
| 91 | + }, |
| 92 | + body: JSON.stringify({ |
| 93 | + question: prompt, |
| 94 | + chat_session_id: chatSessionId |
| 95 | + }) |
| 96 | + }); |
| 97 | + |
| 98 | + if (response.ok) { |
| 99 | + const responseText = await response.text() |
| 100 | + const responseBlocks = JSON.parse(responseText) |
| 101 | + return NextResponse.json(responseBlocks) |
| 102 | + } else { |
| 103 | + return returnError(500, await response.text()) |
| 104 | + } |
| 105 | +} |
0 commit comments