Skip to content

Commit 3535eff

Browse files
updated api routes & projects
1 parent 9883003 commit 3535eff

File tree

24 files changed

+3187
-781
lines changed

24 files changed

+3187
-781
lines changed

app/api/ai/chat/route.ts

Lines changed: 12 additions & 151 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,6 @@ interface ChatRequest {
2727

2828
interface ChatResponse {
2929
message: string
30-
suggestions?: {
31-
type: 'code' | 'refactor' | 'explain' | 'debug'
32-
content: string
33-
description: string
34-
}[]
3530
codeBlocks?: {
3631
language: string
3732
code: string
@@ -88,14 +83,8 @@ async function generateContextualResponse(
8883
history: ChatRequest['history'],
8984
sandboxId?: string,
9085
): Promise<ChatResponse> {
91-
const apiKey = process.env.OPENAI_API_KEY
92-
if (!apiKey) {
93-
throw new Error('OpenAI API key not configured')
94-
}
95-
9686
const { file, content, language, selection, cursorPosition } = context
9787

98-
// Build context-aware system prompt
9988
const systemPrompt = `You are an expert coding assistant specializing in ${language} development. You help developers write better code, debug issues, explain concepts, and optimize performance.
10089
10190
**Current Context:**
@@ -150,136 +139,35 @@ The user is asking about this code. Help them effectively.`
150139
]
151140

152141
try {
153-
const response = await fetch('https://api.openai.com/v1/chat/completions', {
142+
const response = await fetch('/api/ai/enhance-text', {
154143
method: 'POST',
155144
headers: {
156-
'Authorization': `Bearer ${apiKey}`,
157145
'Content-Type': 'application/json',
158146
},
159147
body: JSON.stringify({
160-
model: 'gpt-4',
161-
messages,
162-
temperature: 0.3,
163-
max_tokens: 2000,
164-
tools: [
165-
{
166-
type: 'function',
167-
function: {
168-
name: 'analyze_code',
169-
description: 'Analyze code for issues, optimizations, or explanations',
170-
parameters: {
171-
type: 'object',
172-
properties: {
173-
analysis_type: {
174-
type: 'string',
175-
enum: ['debug', 'optimize', 'explain', 'refactor', 'security'],
176-
description: 'Type of code analysis to perform'
177-
},
178-
code_snippet: {
179-
type: 'string',
180-
description: 'The code snippet to analyze'
181-
},
182-
suggestions: {
183-
type: 'array',
184-
items: {
185-
type: 'object',
186-
properties: {
187-
type: { type: 'string' },
188-
description: { type: 'string' },
189-
code: { type: 'string' },
190-
line: { type: 'number' }
191-
}
192-
}
193-
}
194-
},
195-
required: ['analysis_type', 'code_snippet']
196-
}
197-
}
198-
},
199-
{
200-
type: 'function',
201-
function: {
202-
name: 'generate_code',
203-
description: 'Generate new code based on requirements',
204-
parameters: {
205-
type: 'object',
206-
properties: {
207-
requirement: {
208-
type: 'string',
209-
description: 'What the code should accomplish'
210-
},
211-
language: {
212-
type: 'string',
213-
description: 'Programming language for the code'
214-
},
215-
code: {
216-
type: 'string',
217-
description: 'The generated code'
218-
},
219-
explanation: {
220-
type: 'string',
221-
description: 'Explanation of how the code works'
222-
}
223-
},
224-
required: ['requirement', 'language', 'code']
225-
}
226-
}
227-
}
228-
],
229-
tool_choice: 'auto'
148+
textToEnhance: message,
149+
context: { file, content, language, selection, cursorPosition },
150+
history: messages,
151+
sandboxId,
230152
}),
231153
})
232154

233155
if (!response.ok) {
234-
throw new Error(`OpenAI API error: ${response.statusText}`)
156+
throw new Error(`Enhance Text API error: ${response.statusText}`)
235157
}
236158

237159
const result = await response.json()
238-
const assistantMessage = result.choices[0]?.message
239-
240-
if (!assistantMessage) {
241-
throw new Error('No response from AI')
242-
}
160+
const enhancedText = result.enhancedText
243161

244-
// Process function calls if any
245-
const toolCalls = assistantMessage.tool_calls
246-
let responseMessage = assistantMessage.content || ''
247-
let suggestions: ChatResponse['suggestions'] = []
248-
let codeBlocks: ChatResponse['codeBlocks'] = []
249-
250-
if (toolCalls) {
251-
for (const toolCall of toolCalls) {
252-
const functionName = toolCall.function.name
253-
const functionArgs = JSON.parse(toolCall.function.arguments)
254-
255-
if (functionName === 'analyze_code') {
256-
suggestions.push({
257-
type: functionArgs.analysis_type,
258-
content: functionArgs.code_snippet,
259-
description: `Code analysis: ${functionArgs.analysis_type}`
260-
})
261-
262-
if (functionArgs.suggestions) {
263-
suggestions.push(...functionArgs.suggestions.map((s: any) => ({
264-
type: s.type,
265-
content: s.code,
266-
description: s.description
267-
})))
268-
}
269-
} else if (functionName === 'generate_code') {
270-
codeBlocks.push({
271-
language: functionArgs.language,
272-
code: functionArgs.code,
273-
description: functionArgs.explanation || functionArgs.requirement
274-
})
275-
}
276-
}
162+
if (!enhancedText) {
163+
throw new Error('No enhanced text from AI')
277164
}
278165

279166
// Extract code blocks from response if any
280167
const codeBlockRegex = /```(\w+)\n([\s\S]*?)```/g
281168
let match
282-
while ((match = codeBlockRegex.exec(responseMessage)) !== null) {
169+
const codeBlocks: ChatResponse['codeBlocks'] = []
170+
while ((match = codeBlockRegex.exec(enhancedText)) !== null) {
283171
codeBlocks.push({
284172
language: match[1],
285173
code: match[2].trim(),
@@ -288,8 +176,7 @@ The user is asking about this code. Help them effectively.`
288176
}
289177

290178
return {
291-
message: responseMessage,
292-
suggestions: suggestions.length > 0 ? suggestions : undefined,
179+
message: enhancedText,
293180
codeBlocks: codeBlocks.length > 0 ? codeBlocks : undefined
294181
}
295182

@@ -299,36 +186,10 @@ The user is asking about this code. Help them effectively.`
299186
// Fallback response
300187
return {
301188
message: "I'm having trouble processing your request right now. Could you please try rephrasing your question or check if there are any syntax errors in your code?",
302-
suggestions: [{
303-
type: 'debug',
304-
content: 'Check for syntax errors and ensure your code follows proper formatting',
305-
description: 'Basic debugging suggestion'
306-
}]
307189
}
308190
}
309191
}
310192

311-
async function executeInSandbox(sandboxId: string | undefined, command: string): Promise<string> {
312-
if (!sandboxId) {
313-
return 'Error: Sandbox ID not provided.'
314-
}
315-
316-
// This is a placeholder for actual sandbox execution logic.
317-
// In a real implementation, you would make an API call to your sandbox service.
318-
console.log(`Executing command in sandbox ${sandboxId}: ${command}`)
319-
320-
// Simulate a command execution
321-
if (command.startsWith('ls')) {
322-
return 'file1.txt\nfile2.js\nnode_modules/'
323-
} else if (command.startsWith('cat')) {
324-
return `Content of ${command.split(' ')[1]}`
325-
} else if (command.startsWith('npm install')) {
326-
return 'Successfully installed packages.'
327-
}
328-
329-
return `Command executed: ${command}`
330-
}
331-
332193
async function storeChatInteraction(
333194
userId: string,
334195
interaction: {

app/api/ai/enhance-text/route.ts

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,6 @@ const rateLimitMaxRequests = process.env.RATE_LIMIT_MAX_REQUESTS
1616
: 20
1717
const ratelimitWindow = process.env.RATE_LIMIT_WINDOW ? (process.env.RATE_LIMIT_WINDOW as Duration) : "1h"
1818

19-
const enhanceRequestSchema = z.object({
20-
textToEnhance: z.string().min(1).max(2000)
21-
})
22-
2319
const enhanceResponseSchema = z.object({
2420
enhancedText: z.string(),
2521
reasoning: z.string().optional()
@@ -51,27 +47,25 @@ export async function POST(req: NextRequest) {
5147
const { textToEnhance } = body
5248

5349

54-
const cookieStore = cookies()
50+
const cookieStore = await cookies()
5551
const supabase = createServerClient(
5652
process.env.NEXT_PUBLIC_SUPABASE_URL!,
5753
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
5854
{
5955
cookies: {
60-
async get(name: string) {
61-
return (await cookieStore).get(name)?.value
62-
},
63-
async set(name: string, value: string, options: CookieOptions) {
64-
try {
65-
(await cookieStore).set(name, value, options)
66-
} catch (error) {
67-
console.warn(`Failed to set cookie '${name}':`, error)
68-
}
56+
getAll() {
57+
return cookieStore.getAll()
6958
},
70-
async remove(name: string) {
59+
setAll(cookiesToSet) {
7160
try {
72-
(await cookieStore).delete(name)
61+
cookiesToSet.forEach(({ name, value, options }) =>
62+
cookieStore.set(name, value, options)
63+
)
7364
} catch (error) {
74-
console.warn(`Failed to delete cookie '${name}':`, error)
65+
// The `setAll` method was called from a Server Component.
66+
// This can be ignored if you have middleware refreshing
67+
// user sessions.
68+
console.warn(`Failed to set cookie(s):`, error)
7569
}
7670
},
7771
},
@@ -118,7 +112,7 @@ export async function POST(req: NextRequest) {
118112
}
119113

120114

121-
const defaultModel = modelsList.models.find(m => m.providerId === "openai" && m.id === "gpt-4o") ||
115+
const defaultModel = modelsList.models.find(m => m.providerId === "google" && m.id === "gemini-2.5-flash") ||
122116
modelsList.models.find(m => m.providerId === "anthropic" && m.id === "claude-3-5-sonnet-20241022") ||
123117
modelsList.models[0]
124118

@@ -132,7 +126,7 @@ export async function POST(req: NextRequest) {
132126
let modelClient: LanguageModel
133127
try {
134128
console.log(`[Enhance Text API ${requestId}] Creating model client: ${defaultModel.providerId}/${defaultModel.id}`)
135-
modelClient = await getModelClient(defaultModel, {}) as LanguageModel
129+
modelClient = getModelClient(defaultModel, {}) as LanguageModel
136130
} catch (error: any) {
137131
logError("Model client creation failed", error, { requestId, provider: defaultModel.providerId, modelId: defaultModel.id })
138132
return NextResponse.json(

0 commit comments

Comments
 (0)