1+ import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
2+
3+ const corsHeaders = {
4+ 'Access-Control-Allow-Origin' : '*' ,
5+ 'Access-Control-Allow-Headers' : 'authorization, x-client-info, apikey, content-type' ,
6+ }
7+
8+ serve ( async ( req ) => {
9+ if ( req . method === 'OPTIONS' ) {
10+ return new Response ( 'ok' , { headers : corsHeaders } )
11+ }
12+
13+ try {
14+ const { code, editPrompt } = await req . json ( )
15+
16+ const openaiApiKey = Deno . env . get ( 'OPENAI_API_KEY' )
17+ if ( ! openaiApiKey ) {
18+ throw new Error ( 'OpenAI API key not configured' )
19+ }
20+
21+ const response = await fetch ( 'https://api.openai.com/v1/chat/completions' , {
22+ method : 'POST' ,
23+ headers : {
24+ 'Authorization' : `Bearer ${ openaiApiKey } ` ,
25+ 'Content-Type' : 'application/json' ,
26+ } ,
27+ body : JSON . stringify ( {
28+ model : 'gpt-4.1-2025-04-14' ,
29+ messages : [
30+ {
31+ role : 'system' ,
32+ content : `You are a C++ code editor. Your task is to modify the provided C++ code based on the user's edit request.
33+
34+ Rules:
35+ 1. Only output the modified C++ code, nothing else
36+ 2. Maintain the original code style and formatting as much as possible
37+ 3. Make only the changes requested by the user
38+ 4. Ensure the code remains syntactically correct
39+ 5. If the request is unclear or impossible, make your best interpretation
40+ 6. Preserve comments and structure unless specifically asked to change them`
41+ } ,
42+ {
43+ role : 'user' ,
44+ content : `Here is the C++ code to edit:
45+
46+ \`\`\`cpp
47+ ${ code }
48+ \`\`\`
49+
50+ Edit request: ${ editPrompt }
51+
52+ Please provide only the modified C++ code:`
53+ }
54+ ] ,
55+ temperature : 0.3 ,
56+ max_tokens : 2000 ,
57+ } ) ,
58+ } )
59+
60+ if ( ! response . ok ) {
61+ throw new Error ( `OpenAI API error: ${ response . status } ` )
62+ }
63+
64+ const data = await response . json ( )
65+ const editedCode = data . choices [ 0 ] ?. message ?. content ?. trim ( ) || ''
66+
67+ // Clean up the response to remove any markdown formatting
68+ const cleanCode = editedCode
69+ . replace ( / ^ ` ` ` c p p \n ? / g, '' )
70+ . replace ( / ^ ` ` ` c \+ \+ \n ? / g, '' )
71+ . replace ( / \n ? ` ` ` $ / g, '' )
72+ . trim ( )
73+
74+ return new Response (
75+ JSON . stringify ( { editedCode : cleanCode } ) ,
76+ {
77+ headers : { ...corsHeaders , 'Content-Type' : 'application/json' } ,
78+ } ,
79+ )
80+ } catch ( error ) {
81+ console . error ( 'Error:' , error )
82+ return new Response (
83+ JSON . stringify ( { error : error . message } ) ,
84+ {
85+ status : 500 ,
86+ headers : { ...corsHeaders , 'Content-Type' : 'application/json' } ,
87+ } ,
88+ )
89+ }
90+ } )
0 commit comments