By Sankalpa Abeygunawardhana (Human) with assistance of AI
"I want AI to do my laundry and dishes so that I can do art and writing, not for AI to do my art and writing so that I can do my laundry and dishes."
🧔People talking about AI and its capabilities more than anything this days. AI Capabilites of Drawing pictures, Singing, film making and lots and lots. And also in other sides Humans start warring about there job future as its gradually replace by AI and AI powered robots. There are lots of doutes debates going all arounds.
I wanted to find out where AI is in day today activites of my job.
As a programmrs one of the usuall task is application which is developing integration with different other platforms.
So I wanted to try integreate and see OpenAI platform using only get help from ChatGPT. Which popular virtual assistant tool of OpenAI and I think it should be the best tool get assistant when integrating OpenAI.
In this experiment I try to act as much as not a ‘Senior programmer’ and try to get resolve all the issues and questions I have only using ‘ChatGPT’ as assuming it as a ‘Human Senior Programmer’.
🧔In this experiment, I aim to build a small web app for programmers, allowing them to input their code and generate documentation using OpenAI’s capabilities.
🧔 Hi
🤖 Hi there! How's it going?
🧔 not bad
🤖 Glad to hear that! Anything on your mind today?
🧔 I want to create NextJs app with OpenAI integration, Could you help?
🤖 Absolutely! I can help you with that. Do you have a specific feature in mind for the app, or are you looking for a general setup guide to integrate OpenAI into a Next.js project?
🧔 Yes, App should have a text area which users can enter any type script or javascript code, using OpenAI app should generate the documentation
🤖 That sounds like a great project! Here's a step-by-step guide to help you create a Next.js app that takes TypeScript or JavaScript code input from a user and generates documentation using OpenAI's API:
🧔ChatGPT provided a 6-step guide to achieve this, with a 7th step as an enhancement.
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
🧔Creted NextJs App with following parameter.
PS D:\Sankalpa\Personal\blog\NextJs-Solr> npx create-next-app nextjs-solr
√ Would you like to use TypeScript? ... No / Yes
√ Would you like to use ESLint? ... No / Yes
√ Would you like to use Tailwind CSS? ... No / Yes
√ Would you like to use `src/` directory? ... No / Yes
√ Would you like to use App Router? (recommended) ... No / Yes
√ Would you like to customize the default import alias (@/*)? ... No / Yes
Creating a new Next.js app in D:\Sankalpa\Personal\blog\NextJs-Solr\nextjs-solr.
npm install openai
npx typescript --init
npm install --save-dev @types/react @types/node
.env.local
File🤖NEXT_PUBLIC_OPENAI_API_KEY=your_openai_api_key_here
// pages/index.js or index.tsx
import { useState } from 'react';
export default function Home() {
const [code, setCode] = useState('');
const [documentation, setDocumentation] = useState('');
const handleGenerateDoc = async () => {
const response = await fetch('/api/generate-doc', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
});
const data = await response.json();
setDocumentation(data.documentation);
};
return (
<div style=>
<h1>Code Documentation Generator</h1>
<textarea
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="Enter your TypeScript or JavaScript code here..."
rows={10}
style=
/>
<button onClick={handleGenerateDoc} style=>
Generate Documentation
</button>
{documentation && (
<div style=>
<h2>Generated Documentation</h2>
<pre style=>
{documentation}
</pre>
</div>
)}
</div>
);
}
//pages/api/generate-doc.js or generate-doc.ts:
import { Configuration, OpenAIApi } from 'openai';
const configuration = new Configuration({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export default async function handler(req, res) {
const { code } = req.body;
try {
const response = await openai.createCompletion({
model: 'text-davinci-003', // or any other model suitable for code tasks
prompt: `Generate documentation for the following code:\n\n${code}`,
max_tokens: 150,
});
const documentation = response.data.choices[0].text.trim();
res.status(200).json({ documentation });
} catch (error) {
res.status(500).json({ error: 'Failed to generate documentation' });
}
}
npm run dev
🧔After creating the app using the steps above, I encountered some errors. Here’s how I resolved them with the help of ChatGPT.
🧔As humans, we are prone to making mistakes, and errors can occur at any time. For instance, I tested an error by purposely creating pages/index.js
under /app/src/pages/index.js
. When setting up the Next.js solution, I chose to create it with the src
folder.
Here’s how I tried to resolve that issue with the help of ChatGPT:
🧔 When I try to access the page which I created in step 4 its return '404 This page could not be found' error
🤖 The "404 This page could not be found" error typically occurs if the page file isn't located correctly or there's an issue with the routing. Let's troubleshoot this:
🧔And provided six troubleshooting points to check.
🤖
🧔I know that ‘Check the File Location’ is part of the answer, but I needed to get that directly from ChatGPT. So, I asked the following question again.
🧔 I created next app with 'src' folder is that the issue?
🧔However, I’m unsure if I provided too much information to ChatGPT 🙂 in this question.
🤖 Yes, having a src directory can change where Next.js looks for your pages. By default, if you create a src folder, Next.js will expect your pages directory to be inside the src folder.
🧔Provided troubleshooting points to check.
🤖
🧔I corrected the structure, but the errors continue.
🧔This time, a package compatibility issue occurred. Following the instructions, I installed the latest version (openai@4.56.0), but the generated code snippet was not compatible with the latest library.
🧔 in step 5 I am getting following error Module '"openai"' has no exported member 'Configuration'. Did you mean to use 'import Configuration from "openai"' instead?
🤖 It looks like the error is due to how the OpenAI package is being imported. The issue might arise from a discrepancy in the package's version or its TypeScript definitions. Let's address this by making sure the import statement is correct.
🤖
🧔None of the above options resolved the issue.And I checked again with ChatGPT.
🧔 I am using openai@4.56.0 version, which is latest, and non of the above resolve my issue
🤖 It seems the latest version of the OpenAI library (openai@4.56.0) has some changes in how the classes are exported. Let's address this with the correct import pattern for this version.
🤖
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
});
export default async function handler(req, res) {
const { code } = req.body;
try {
const response = await openai.chat.completions.create({
model: 'gpt-4', // or the model you intend to use
messages: [
{
role: 'system',
content: 'Generate documentation for the following code:',
},
{
role: 'user',
content: code,
},
],
});
const documentation = response.choices[0].message.content.trim();
res.status(200).json({ documentation });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Failed to generate documentation' });
}
}
🧔I used TypeScript, but the provided solution was in JavaScript.
🧔 I am using TS,
🤖 Given that you're using TypeScript with the latest OpenAI package (openai@4.56.0), here’s how to properly set up and use the OpenAI API with TypeScript:
🤖
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
});
import { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { code } = req.body;
try {
const response = await openai.chat.completions.create({
model: 'gpt-4', // Specify the model you want to use
messages: [
{ role: 'system', content: 'Generate documentation for the following code:' },
{ role: 'user', content: code },
],
});
const documentation = response.choices[0].message.content.trim();
res.status(200).json({ documentation });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Failed to generate documentation' });
}
}
🧔I’m still encountering an optional chaining error.
🧔 now its complain about 'const documentation = response.choices[0].message.content.trim();' line 'Object is possibly 'null'.ts'
🤖 The TypeScript error 'Object is possibly 'null' is a common issue when dealing with optional properties or API responses that might not always return the expected structure. To handle this safely, you should check if the object exists and handle the null or undefined case appropriately.
Safely Accessing response.choices[0].message.content
🧔 ok, with that its resolve
🤖 Great to hear that resolved the issue! If you have any more questions or need further assistance with your project, feel free to ask.
🧔I finally got a working solution, but it still has some runtime errors
🧔 now when I try to generate document for a simple type script program, its return ' POST http://localhost:3000/api/generate-doc 500 (Internal Server Error)'
🤖 A 500 Internal Server Error generally indicates something went wrong on the server side. Let's troubleshoot this step-by-step:
🤖
🧔 Beyond this point, the remaining errors were due to my free subscription. I’ve chosen not to list them all here to avoid making this article unnecessarily lengthy.
Review the full conversation here.
🧔 I tried the same scenario on two other popular platforms but couldn’t get very far.
Experimental integration with Claude and Next.js had to stop due to a runtime Cross-Origin issue.
I couldn’t continue the integration with the Google Gemini platform because the provided NPM package was not available in the NPM registry.
Review the full conversation here.
I believe that if I had provided more details to the AI, I might have received better outputs in some of the scenarios above, such as explaining how I created the Next.js app.
Additionally, I think that understanding own libraries and related issues is a matter of time for the AI.
In conclusion, I believe…
We developed the code based on the business requirements using only human effort.
We are coding based on business requirements with the assistance of AI.
AI will code based on the business requirements, with human assistance.