Testing AI to create an application

Hello everyone, I'm Grigory Tumakov, CTO at Morisot Digital.

Recently told, how we at the company “touched” neural networks for applied development tasks. But no serious conclusions could be drawn there.

Therefore, I decided not to stop there. If there are tools, they need to be tested on some real problem.

Further in the article is my experience of comparing three AI tools for an applied task: Phind, ChatGPT, Machinet.

Idea and prompt

Create a page using JS and html to get weather by city name. The page should have a form for filling out the name of the city and a “Find out the weather” button. Don't forget to take CORS issues into account.

It should work like this:

  1. The user enters the name of the city.

  2. Based on the city name, you need to request longitude and latitude using this API

    curl -X POST
    -H "Content-Type: application/json"
    -H "Accept: application/json"
    -H "Authorization: Token {API_TOKEN}"
    -H "X-Secret: {SECRET_TOKEN}"
    -d '[ "{Название города}" ]'
    https://cleaner.dadata.ru/api/v1/clean/address

  1. Next, longitude and latitude must be substituted into the request – https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}

  2. Display the result of an API call.

For comparison, I loaded the prompt into each of the three neural networks.

I'll tell you what happened.

ChatGPT

*Here is some example HTML and JavaScript code that implements the functionality you describe:*


<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Get weathertitle>
head>
<body>
<h2>Check the weatherh2>
<form id=”weatherForm”>
<label for=”cityInput”>Enter the city name:label><br>
<input type=”text” id=”cityInput” name=”cityInput”><br>
<button type=”submit”>Check the weatherbutton>
form>
<div id=”weatherResult”>div>

<script>
document.getElementById('weatherForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent default form submission

var city ​​= document.getElementById('cityInput').value.trim();
if (city === '') {
alert('Please enter the city name.');
return;
}

fetchCoordinates(city)
.then(function(coordinates) {
return fetchWeather(coordinates.lat, coordinates.lon);
})
.then(function(weather) {
displayWeather(weather);
})
.catch(function(error) {
console.error('An error occurred:', error);
});
});

function fetchCoordinates(city) {
var apiToken = '{API_TOKEN}';
var secretToken = '{SECRET_TOKEN}';

return fetch('https://cleaner.dadata.ru/api/v1/clean/address', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Token' + apiToken,
'X-Secret': secretToken
},
body: JSON.stringify([city])
})
.then(function(response) {
if (!response.ok) {
throw new Error('Error while getting city coordinates.');
}
return response.json();
})
.then(function(data) {
var coordinates = data[0].geo_lat && data[0].geo_lon ? { lat: data[0].geo_lat, lon: data[0].geo_lon } : null;
if (!coordinates) {
throw new Error('Coordinates for the specified city were not found.');
}
return coordinates;
});
}

function fetchWeather(lat, lon) {
var apiKey = '{API_KEY}';

return fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}`)
.then(function(response) {
if (!response.ok) {
throw new Error('Error while retrieving weather data.');
}
return response.json();
});
}

function displayWeather(weather) {
var weatherResultDiv = document.getElementById('weatherResult');
weatherResultDiv.innerHTML = '';

var cityName = weather.name;
var weatherDescription = weather.weather && weather.weather[0] ? weather.weather[0].description: '';
var temperature = weather.main && weather.main.temp ? Math.round(weather.main.temp – 273.15) : '';

var weatherInfo = document.createElement('p');
weatherInfo.textContent = `Weather in ${cityName}: ${weatherDescription}, Temperature: ${temperature}°C`;
weatherResultDiv.appendChild(weatherInfo);
}
script>
body>
html>

*Please note that you must replace `{API_TOKEN}`, `{SECRET_TOKEN}` and `{API_KEY}` with your actual values. Also, be aware that without using a server to bypass CORS, you may run into security issues if you try to execute this code in a browser.*

Obviously, this code will not give us a result, we will get a CORS error.

Therefore, I asked to come up with a solution to this problem.

Here's what ChatGPT suggested

*To bypass the CORS error when accessing the API from the client side, you can use a server proxy. For example, you can create a simple server using Node.js that will proxy requests to the `cleaner.dadata.ru` API and pass the result back to the client.*

*Here is an example code for a server in Node.js:*

const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(cors());

app.post('/getCoordinates', async (req, res) => {
try {
const cityName = req.body.cityName;
const response = await fetch('https://cleaner.dadata.ru/api/v1/clean/address', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Token {API_TOKEN}',
'X-Secret': '{SECRET_TOKEN}'
},
body: JSON.stringify([cityName])
});

const data = await response.json();
const coordinates = data[0].geo_lat && data[0].geo_lon ? { lat: data[0].geo_lat, lon: data[0].geo_lon } : null;

if (coordinates) {
res.json(coordinates);
} else {
res.status(404).json({ error: 'Coordinates not found for the provided city name' });
}
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

*Code changes:*

1. *Added the `express` library for creating a server.*

2. *Added the `node-fetch` library for executing HTTP requests on the server.*

3. *Added the `cors` library to handle CORS policies.*

4. *The route `/getCoordinates` has been created, which accepts a POST request with the name of the city, sends a request to the `cleaner.dadata.ru` API via the server, receives the coordinates of the city and sends them back to the client.*

*On the client side, you now need to contact the server to get the city coordinates, then use the received coordinates to request the weather to the `api.openweathermap.org` API.*

<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Weather Apptitle>
head>
<body>
<h1>Weather Apph1>
<form id=”cityForm”>
<label for=”cityName”>Enter city name:label>
<input type=”text” id=”cityName” name=”cityName”>
<button type=”submit”>Get Weatherbutton>
form>
<div id=”weatherData”>div>

<script>
document.getElementById('cityForm').addEventListener('submit', async (event) => {
event.preventDefault();

const cityName = document.getElementById('cityName').value;
const response = await fetch('http://localhost:3000/getCoordinates', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ cityName })
});

const data = await response.json();

if (data.error) {
document.getElementById('weatherData').textContent = data.error;
} else {
const weatherResponse = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${data.lat}&lon=${data.lon}&appid={API key}`);
const weatherData = await weatherResponse.json();
document.getElementById('weatherData').textContent = JSON.stringify(weatherData, null2);
}
});
script>
body>
html>

*The client JavaScript now makes a request to the server to get the city coordinates, then uses those coordinates to query the weather to the `api.openweathermap.org` API.*

Unfortunately, I get the error again.

Error [ERR_REQUIRE_ESM]: require() of ES Module …/ai/chat-gpt/node_modules/node-fetch/src/index.js from …/ai/chat-gpt/server.js not supported. Instead change the require of index.js in …/ai/chat-gpt/server.js to a dynamic import() which is available in all CommonJS modules. at Object. (…/ai/chat-gpt/server.js:50:15) { code: 'ERR_REQUIRE_ESM' }

I ask for correction and receive a new block of code indicating the need to install axios.

const express = require('express');
const axios = require('axios');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(cors());
app.use(express.json());

app.post('/getCoordinates', async (req, res) => {
try {
const cityName = req.body.cityName;
const response = await axios.post('https://cleaner.dadata.ru/api/v1/clean/address', [cityName],{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Token {API_TOKEN}',
'X-Secret': '{SECRET_TOKEN}'
}
});

const data = response.data;
const coordinates = data[0].geo_lat && data[0].geo_lon ? { lat: data[0].geo_lat, lon: data[0].geo_lon } : null;

if (coordinates) {
res.json(coordinates);
} else {
res.status(404).json({ error: 'Coordinates not found for the provided city name' });
}
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

And finally I get the desired result, the application works

I will ask you to format the response received from the API.

*Output a beautiful response from the API so that it is clear what the current weather is, wind speed, and so on*

Find

I load the prompt and immediately see the differences in the result. Phind chose to separate the html and js code into different files, which is good news.

Unfortunately, I don't get a working program on the first request, so I ask you to add a web server to bypass the CORS problem. I see that Phind gives more detailed answers and offers several options.

I'll try the first option first. I ask how to use it and receive fairly detailed instructions.

After changing the code, I try to start the server, but I get the already familiar error.

“`

Error [ERR_REQUIRE_ESM]: require() of ES Module …/ai/chat-gpt/node_modules/node-fetch/src/index.js from …/ai/chat-gpt/server.js not supported. Instead change the require of index.js in …/ai/chat-gpt/server.js to a dynamic import() which is available in all CommonJS modules. at Object. (…/ai/chat-gpt/server.js:50:15) { code: 'ERR_REQUIRE_ESM' }

“`

I ask for a bug fix and get a much better response than ChatGPT, it's detailed and explains the problem.

I try to use the proposed solution – everything works.

I would like to ask you to display the response from the API beautifully so that it is clear what the weather is like, the wind, etc.

I edit the code and try to get the data.

Now I'm testing the second proposed option. I apply the changes and launch.

But an error appears – please correct it.

Again I receive a detailed answer with an explanation of the error and several solutions, but now I already know that the first solution will help, so I do not continue.

Machinet

I load the prompt and get the response:

*Okay, I can help you create a page to get weather by city name using JavaScript and HTML. First, you'll need to create the HTML markup for the page. Here is a code example:*


<html>
<head>
<title>Getting weathertitle>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”>script>
head>
<body>
<h1>Getting weather by city nameh1>
<form id=”weatherForm”>
<label for=”cityInput”>Enter the city name:label>
<input type=”text” id=”cityInput” required>
<button type=”submit”>Check the weatherbutton>
form>
<div id=”weatherResult”>div>

<script>
// Form submission event handler
$(“#weatherForm”).submit(function(event) {
event.preventDefault(); // Prevent the form from being submitted

var city ​​= $(“#cityInput”).val(); // Get the value of the input field

// Query to get longitude and latitude
$.ajax({
url: “https://cleaner.dadata.ru/api/v1/clean/address”,
type: “POST”,
headers: {
“Content-Type”: “application/json”,
“Accept”: “application/json”,
“Authorization”: “Token {API_TOKEN}”,
“X-Secret”: “{SECRET_TOKEN}”
},
data: JSON.stringify([city]),
success: function(response) {
var latitude = response[0].geo_lat;
var longitude = response[0].geo_lon;

// Request for weather
$.ajax({
url: “https://api.openweathermap.org/data/2.5/weather”,
type: “GET”,
data: {
lat: latitude,
lon:longitude,
appid: “{API key}”
},
success: function(weatherData) {
// Output the result of calling the API
$(“#weatherResult”).html(“Current weather in the city ” + city + “: ” + weatherData.weather[0].description);
},
error: function() {
$(“#weatherResult”).html(“Error retrieving weather”);
}
});
},
error: function() {
$(“#weatherResult”).html(“Error while retrieving city coordinates”);
}
});
});
script>
body>
html>

*In this example we use jQuery to make AJAX requests easier. When submitting a form, we first send a request to get the city's longitude and latitude using the Dadata API, and then use the resulting coordinates to query the weather using the OpenWeatherMap API. The result is displayed in the element with id “weatherResult”.*

*Please note that you will need to replace {API_TOKEN}, {SECRET_TOKEN} and {API key} with the corresponding values ​​obtained when registering with the relevant services.*

I'm trying to run the code and execute the request. I get a CORS error again, I ask to correct it using the same text as in the previous neural networks – and I get an interesting answer.

I choose the second approach.

I try to start the server and get an error.

app.use(corsAnywhere({
^
TypeError: corsAnywhere is not a function

Please correct it.

After the fixes, the server actually started. But when executing the request I get a new error, I ask again to fix it.

I apply the changes and try to run the request again, but again I get the error.

I'm trying to give more information about the error.

Unfortunately, I don't get any solution, only recommendations. There is no point in continuing here.

results

Machinet performed the task worst of all; it failed to produce a working solution. Perhaps she can help with simpler tasks.

If you choose between ChatGPT and Phind, then I would prefer Phind, since it gave more detailed answers and offered more options for solving problems.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *