DEV Community

Cover image for How to use Chatgpt better
Thiago Mota dos Santos
Thiago Mota dos Santos

Posted on

How to use Chatgpt better

I use ChatGPT quite a bit, and I believe it's a great way to obtain information on various concepts. I can ask it to generate lists, perform operations based on input, or tasks that might take some time to do manually.

Using chatgpt to programming

The same concept applies here, Let's say you have a JSON that comes from an API with many fields.

{ 
   "name": "John Doe",   
   "age": 30,   
   "birth_date": "1992-05-15",   
   "height": 1.75,   
   "married": false 
}
Enter fullscreen mode Exit fullscreen mode

For example, we want to create a type this api response

Input to the GPT: Create a type in typescript with this json.

Response:

type Person = {
  name: string;
  age: number;
  birth_date: Date;
  height: number;
  married: boolean;
};

Enter fullscreen mode Exit fullscreen mode

If this json was a field with many values, the gpt, or some tool that this work would be very useful

The real problem

What has been addressed are quite simple cases, GPT would hardly make mistakes, but when the code we send as input is more "complex," the chance of it generating a strange response is very high. This happens because AI, in general, is very good at following specific instructions and bad at understanding the "context" of our code. If your code is extensive, this problem becomes as clear as daylight – how will GPT have context for your business rule? And even if you input the complete specifications of your code each time, it would take a long time.

context

Our goal is to do this:

gpt own context

Consider this random code:

useEffect(() => {
  const fetchData = async () => {
    const res = await fetch(`/api/payout_details?payout_reference=${payoutWithdraw.payout_reference}`, {
      method: 'GET',
    });

    const item = payersData[0];

    if (!item) return null;

    if (res.ok) {
      const data = await res.json();

      if (data.data.errors || data.data.code === 'MethodNotAllowed') return;

      const filteredDataDone = data.data.filter((order) =>
        order.order_id === item.order_id && order.status === 'done'
      );

      const payersCollection = collection(db, 'payers');

      const payersQuery = query(
        payersCollection,
        where('id', '==', user!.uid),
        orderBy('timestamp', 'desc'),
        where('successful_payment', '==', true),
        where('payout_successful', '==', false),
      );

      const payerSnapshot = await getDocs(payersQuery);

      let totalAmount = 0;

      payersData.forEach((payer) => {
        if (!payer.payout_successful) {
          totalAmount += parseFloat(payer.amount);
        }
      });

      const roundedTotal = Number(totalAmount.toFixed(2));

      newBalanceLiquid(totalAmount);

      setTotalBalance(roundedTotal);

      if (!filteredDataDone || filteredDataDone.length === 0) return;

      .........
      ........
    }
  };
  fetchData();
}, []);
Enter fullscreen mode Exit fullscreen mode

This strange code does many things at once for action x to be performed. The likelihood of the AI being able to understand your code is very low.

Small batch

I recommend against pasting your code and expecting some magical solution from the AI – you'd want to avoid unexpected outcomes, right? So, what should you do when you encounter a genuinely challenging problem?

what to do?

Small batch.

In other words, you abstract the behavior of your code, remove everything that is not important, and request a reconstruction from GPT. Then you should:

-Analyze the response and truly understand the problem
-Ask for improvements or add only a small part of your real context

example input:

Given an array of objects containing information about people, including name (name), age (idade), status (status: "new" or "done"), identification (id), balance (balance), and whether they were successful (successful: true or false), develop a React code. This code should perform the following:

  1. Compare the provided ID with the IDs of the objects in the array.
  2. If an object has a corresponding ID and its status is "done", store that object in a variable.
  3. Maintain a state that calculates the sum of balances (balance) only for objects that have successful as true.

Response:


const DataComponent = ({ data, idToCompare }) => {
  // State to store objects that match the ID and have a status of 'done'
  const [filteredData, setFilteredData] = useState([]);

  // State to store the sum of balances where 'successful' is true
  const [sumSuccessfulBalances, setSumSuccessfulBalances] = useState(0);

  // Effect to filter the data when the 'data' or 'idToCompare' property changes
  useEffect(() => {
    // Filter objects based on the comparison of ID and status 'done'
    const filtered = data.filter(obj => obj.id === idToCompare && obj.status === 'done');
    setFilteredData(filtered);
  }, [data, idToCompare]);

  // Effect to calculate the sum of balances where 'successful' is true in the filtered data
  useEffect(() => {
    // Calculate the sum of balances where 'successful' is true
    const sum = filteredData.reduce((total, obj) => (obj.successful ? total + obj.balance : total), 0);
    setSumSuccessfulBalances(sum);
  }, [filteredData]);

Enter fullscreen mode Exit fullscreen mode

Note that even in this small example, the response is not so good, so you should just analyze and try to understand your problem.

Perplexity

Perplexity It's an interesting tool to use, it's like a GPT but with internet access, and with each input you send, it provides an article or video for you to delve deeper into your problem

Wrapping up

Use small batches when working with artificial intelligence; treat them as a learning tool, not as a magical being that will solve all your problems miraculously.

X (Twitter): https://twitter.com/Thzinhdev
Photo Possessed Photography at Unsplash

Top comments (0)