Skip to content

Commit f8833f9

Browse files
updated api & template tasks
1 parent b05bd84 commit f8833f9

26 files changed

+2759
-1182
lines changed

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

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,10 @@ export async function POST(req: NextRequest) {
130130
)
131131
}
132132

133-
// Create model client
134133
let modelClient: LanguageModel
135134
try {
136135
console.log(`[Enhance Text API ${requestId}] Creating model client: ${defaultModel.providerId}/${defaultModel.id}`)
137-
modelClient = getModelClient(defaultModel, {}) as LanguageModel
136+
modelClient = await getModelClient(defaultModel, {}) as LanguageModel
138137
} catch (error: any) {
139138
logError("Model client creation failed", error, { requestId, provider: defaultModel.providerId, modelId: defaultModel.id })
140139
return NextResponse.json(
@@ -148,7 +147,6 @@ export async function POST(req: NextRequest) {
148147
)
149148
}
150149

151-
// Generate enhanced text using streamObject for compatibility
152150
try {
153151
console.log(`[Enhance Text API ${requestId}] Generating enhanced text`)
154152

@@ -180,7 +178,6 @@ Make it more clear, engaging, and well-structured while keeping the same general
180178
temperature: 0.7,
181179
})
182180

183-
// Wait for the complete object
184181
const finalResult = await result.object
185182

186183
console.log(`[Enhance Text API ${requestId}] Enhancement completed successfully`)

app/api/chat/route.ts

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
import type { Duration } from "@/lib/duration"
22
import type { LLMModel, LLMModelConfig } from "@/lib/models"
3-
import { getModelClient } from "@/lib/models"
3+
import { getModelClient } from "@/lib/models" // Assuming getModelClient is a named export
44
import { toEnhancedPrompt } from "@/lib/enhanced-prompt"
55
import ratelimit from "@/lib/ratelimit"
66
import { fragmentSchema as schema } from "@/lib/schema"
7-
import type { TemplatesDataObject, TemplateId } from "@/lib/templates" // Import TemplateId
8-
import templatesDataFromFile from "@/lib/templates" // Import the actual templates data
7+
import type { TemplatesDataObject } from "@/lib/templates"
98
import { ProjectAnalyzer, type ProjectStructure } from "@/lib/project-analyzer"
109
import { streamObject, type LanguageModel, type CoreMessage } from "ai"
1110
import { logError, generateRequestId, validateRequestData } from "@/lib/debug"
@@ -47,7 +46,7 @@ export async function POST(req: Request) {
4746
messages,
4847
userID,
4948
teamID,
50-
selectedTemplateId, // Changed from 'template' to 'selectedTemplateId'
49+
template,
5150
model,
5251
config,
5352
uploadedFiles,
@@ -56,7 +55,7 @@ export async function POST(req: Request) {
5655
messages: CoreMessage[]
5756
userID: string
5857
teamID: string
59-
selectedTemplateId: TemplateId // Type is now TemplateId (string)
58+
template: TemplatesDataObject
6059
model: LLMModel
6160
config: LLMModelConfig
6261
uploadedFiles?: File[]
@@ -127,14 +126,12 @@ export async function POST(req: Request) {
127126
}
128127
} catch (error) {
129128
logError("Rate limiting check failed", error, { requestId })
130-
// Continue without rate limiting if it fails
131129
}
132130

133-
// Create model client with enhanced error handling
134131
let modelClient: LanguageModel
135132
try {
136133
console.log(`[Chat API ${requestId}] Creating model client for: ${model.providerId}/${model.id}`)
137-
modelClient = getModelClient(model, config) as LanguageModel
134+
modelClient = await getModelClient(model, config) as LanguageModel
138135
console.log(`[Chat API ${requestId}] Model client created successfully`)
139136
} catch (error: any) {
140137
logError("Model client creation failed", error, { requestId, provider: model.providerId, modelId: model.id })
@@ -168,12 +165,10 @@ export async function POST(req: Request) {
168165
try {
169166
if (projectStructure && userPrompt) {
170167
console.log(`[Chat API ${requestId}] Generating enhanced prompt with project context`)
171-
// Pass the full templatesDataFromFile to toEnhancedPrompt
172-
systemPrompt = toEnhancedPrompt(templatesDataFromFile, userPrompt, projectStructure)
168+
systemPrompt = toEnhancedPrompt(template, userPrompt, projectStructure)
173169
} else {
174170
console.log(`[Chat API ${requestId}] Using standard prompt generation`)
175-
// Pass the full templatesDataFromFile to generateFallbackPrompt
176-
systemPrompt = generateFallbackPrompt(templatesDataFromFile)
171+
systemPrompt = generateFallbackPrompt(template)
177172
}
178173

179174
console.log(`[Chat API ${requestId}] System prompt generated`)
@@ -193,10 +188,8 @@ export async function POST(req: Request) {
193188
)
194189
}
195190

196-
// Prepare model parameters from config
197191
const { model: _modelFromConfig, apiKey: _apiKeyFromConfig, ...providerSpecificConfig } = config
198192

199-
// Clean up undefined values from provider-specific config
200193
const cleanProviderSpecificConfig = Object.fromEntries(
201194
Object.entries(providerSpecificConfig).filter(([_, value]) => value !== undefined),
202195
)
@@ -306,20 +299,18 @@ export async function POST(req: Request) {
306299
}
307300

308301
function generateFallbackPrompt(template: TemplatesDataObject): string {
302+
const validTemplates = Object.entries(template)
303+
.filter(([_, t]) => typeof t === 'object' && t !== null && 'instructions' in t && 'lib' in t)
304+
.map(([id, t], index) => {
305+
const templateObject = t as { instructions: string; file?: string | null; lib: string[]; port?: number | null };
306+
return `${index + 1}. ${id}: "${templateObject.instructions}". File: ${templateObject.file || 'none'}. Dependencies: ${templateObject.lib.join(', ')}. Port: ${templateObject.port || 'none'}.`;
307+
});
308+
309309
return `You are an expert software engineer with deep knowledge of modern web development, programming languages, frameworks, and best practices.
310310
311311
Generate production-ready code based on the user's requirements using the following templates:
312312
313-
${Object.entries(template).map(([id, t], index) => {
314-
const instructions = "instructions" in t
315-
? t.instructions
316-
: (t.files as any).instructions;
317-
const port = "port" in t
318-
? t.port
319-
: (t.files as any).port;
320-
const fileNames = Object.keys(t.files).join(', ');
321-
return `${index + 1}. ${id}: "${instructions}". Files: ${fileNames || 'none'}. Dependencies: ${t.lib.join(', ')}. Port: ${port ?? 'none'}.`;
322-
}).join('\n')}
313+
${validTemplates.join('\n')}
323314
324315
IMPORTANT GUIDELINES:
325316
- Write clean, maintainable, and well-documented code
@@ -332,4 +323,4 @@ IMPORTANT GUIDELINES:
332323
- Include proper security measures
333324
334325
Generate complete, functional code that fulfills the user's request.`
335-
}
326+
}

app/api/index.ts

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,49 @@
1-
import 'dotenv/config'
2-
import { Sandbox } from '@e2b/code-interpreter'
1+
import 'dotenv/config';
2+
import { Sandbox, SandboxOpts } from '@e2b/code-interpreter';
33

44
async function main() {
5-
const sbx = await Sandbox.create() // By default the sandbox is alive for 5 minutes
6-
const execution = await sbx.runCode('print("hello world")') // Execute Python inside the sandbox
7-
console.log(execution.logs)
5+
let sbx: Sandbox | undefined = undefined;
86

9-
const files = await sbx.files.list('/')
10-
console.log(files)
7+
try {
8+
const sandboxOptions: SandboxOpts = { timeoutMs: 300000 };
9+
sbx = await Sandbox.create(sandboxOptions);
10+
console.log('Sandbox created successfully.');
11+
12+
const codeToRun = 'print("hello world")';
13+
console.log(`Executing code: ${codeToRun}`);
14+
const execution = await sbx.runCode(codeToRun); // Execute Python inside the sandbox
15+
16+
console.log('Execution logs:');
17+
execution.logs.stdout.forEach(log => console.log(`[STDOUT] ${log}`));
18+
execution.logs.stderr.forEach(log => console.error(`[STDERR] ${log}`));
19+
20+
if (execution.error) {
21+
console.error('Execution error:', execution.error);
22+
} else {
23+
console.log('Execution results:', execution.results);
24+
}
25+
26+
console.log('Listing files in /:');
27+
const files = await sbx.files.list('/');
28+
console.log(files);
29+
30+
} catch (error) {
31+
console.error('An error occurred:', error);
32+
// Depending on the application, you might want to exit or handle the error differently
33+
// process.exit(1);
34+
} finally {
35+
if (sbx) {
36+
console.log('Closing preview...');
37+
try {
38+
await (sbx as any).close();
39+
console.log('Sandbox closed successfully.');
40+
} catch (closeError) { // Updated variable name
41+
console.error('Error closing sandbox:', closeError); // Updated log message
42+
}
43+
}
44+
}
1145
}
1246

1347
main()
48+
.then(() => console.log('Script finished.'))
49+
.catch(error => console.error('Unhandled error in main:', error));

0 commit comments

Comments
 (0)