Skip to content

Commit

Permalink
Merge pull request #5 from xavimondev/v2
Browse files Browse the repository at this point in the history
fix error handling
  • Loading branch information
xavimondev authored Jun 18, 2024
2 parents c00e444 + 09ab42c commit ed6df52
Showing 1 changed file with 14 additions and 41 deletions.
55 changes: 14 additions & 41 deletions apps/web/app/api/code-generation/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,9 @@ import { cookies } from 'next/headers'
import { streamText } from 'ai'
import { createOpenAI } from '@ai-sdk/openai'
import { PROMPT } from '@/prompt'
// import { Ratelimit } from "@upstash/ratelimit";
// import { Redis } from "@upstash/redis";
// import { TOTAL_GENERATIONS } from "@/constants";

export const runtime = 'edge'

// const ratelimit =
// process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN
// ? new Ratelimit({
// redis: new Redis({
// url: process.env.UPSTASH_REDIS_REST_URL,
// token: process.env.UPSTASH_REDIS_REST_TOKEN,
// }),
// limiter: Ratelimit.slidingWindow(TOTAL_GENERATIONS, "1440 m"), // 1 per day
// analytics: true,
// })
// : false;

export async function POST(req: Request) {
let customApiKey = cookies().get('api-key')?.value

Expand Down Expand Up @@ -51,27 +36,6 @@ export async function POST(req: Request) {
customApiKey = process.env.OPENAI_API_KEY
}

// const hasCustomApiKey = customApiKey && customApiKey.trim().length > 0;

// if (ratelimit) {
// const ip = req.headers.get("x-real-ip") ?? "local";

// const { success, limit, reset, remaining } = await ratelimit.limit(ip);
// if (!success) {
// return NextResponse.json(
// { message: "You have reached your request limit for the day." },
// {
// status: 429,
// headers: {
// "X-RateLimit-Limit": limit.toString(),
// "X-RateLimit-Remaining": remaining.toString(),
// "X-RateLimit-Reset": reset.toString(),
// },
// }
// );
// }
// }

const openai = createOpenAI({
apiKey: customApiKey,
compatibility: 'strict'
Expand Down Expand Up @@ -103,13 +67,22 @@ export async function POST(req: Request) {

return result.toAIStreamResponse()
} catch (error) {
let errorMessage = 'An error has ocurred with API Completions. Please try again.'
// console.log(Object.keys(error))
// @ts-ignore
if (error.status === 401) {
const statusCode = error?.lastError?.statusCode ?? error.statusCode
let errorMessage = 'An error has ocurred with API Completions. Please try again.'

if (statusCode === 401) {
errorMessage = 'The provided API Key is invalid. Please enter a valid API Key.'
} else if (statusCode === 429) {
errorMessage = 'You exceeded your current quota, please check your plan and billing details.'
}
// @ts-ignore
const { name, status, headers } = error
return NextResponse.json({ name, status, headers, message: errorMessage }, { status })

return NextResponse.json(
{
message: errorMessage
},
{ status: statusCode }
)
}
}

0 comments on commit ed6df52

Please sign in to comment.