Você já bateu papo com o ChatGPT pelo site ou pelo app. Mas e se um programa pudesse fazer isso sozinho, 24 horas por dia, sem cansar e sem pedir lanche? É exatamente o que uma API permite. Em 2023 eu testei isso para responder mensagens automaticamente, e neste post conto como funciona — e onde mora o perigo.

⚠️ Antes de começar (sério, leia)

  • Pelos Termos de Uso da OpenAI, é preciso ter pelo menos 13 anos, e quem tem menos de 18 precisa de autorização dos pais ou responsáveis.
  • Usar a API custa dinheiro (cobra por uso). Faça os testes junto com um adulto.
  • A chave da API é como uma senha: nunca coloque em print, no GitHub ou no grupo da turma.

API: o garçom da internet

Pense num restaurante. Você (o programa) não entra na cozinha (os servidores da OpenAI): você faz o pedido ao garçom (a API), ele leva até a cozinha e volta com o prato (a resposta). API é isso: um jeito combinado de um programa pedir coisas para outro.

E o que tem na cozinha? Um modelo de linguagem grande (LLM): um programa treinado com uma montanha de textos para prever qual palavra vem depois da outra. É tipo o autocompletar do seu celular, só que tomou muito Toddy.

O código (versão 2026)

Primeiro instale a biblioteca oficial com pip install openai. Depois guarde sua chave numa variável de ambiente chamada OPENAI_API_KEY (assim ela não fica escrita no código).

from openai import OpenAI

client = OpenAI()  # lê a chave da variável de ambiente OPENAI_API_KEY

MODELO = "NOME-DO-MODELO"  # escolha um modelo atual na lista oficial (link nas fontes)

resposta = client.chat.completions.create(
    model=MODELO,
    messages=[
        {"role": "system", "content": "Você é um monitor de informática paciente e bem-humorado. Responda em até 3 frases."},
        {"role": "user", "content": "O que é uma variável em programação?"},
    ],
)

print(resposta.choices[0].message.content)

Repare nos papéis das mensagens:

  • system: define a personalidade e as regras (“seja paciente”, “responda curto”).
  • user: a pergunta de quem está usando.
  • assistant: as respostas anteriores da IA, se você quiser manter a conversa.

No meu teste original, a mensagem de sistema dizia algo como “você é um advogado de sindicato; responda a dúvida do professor”. Funcionou bem para rascunhar respostas — mas toda resposta passava pelos meus olhos antes de ser enviada.

E imagens?

Os modelos mais novos são multimodais: entendem texto e imagem. No experimento, enviei uma foto convertida em Base64 (um jeito de transformar arquivo em texto) e perguntei “o que tem nesta imagem?”. A resposta veio em segundos. O passo a passo atualizado está no guia de visão da OpenAI.

🧠 Os 4 cuidados de quem usa IA de verdade

  1. Ela pode inventar. Isso se chama alucinação). Sempre confira datas, números e nomes.
  2. Privacidade: não envie dados pessoais (seus ou de outras pessoas) para a API.
  3. Humano no comando: use a IA para rascunhar; quem decide e assina é você.
  4. Chave escondida: variável de ambiente sempre. Vazou? Apague a chave no painel e gere outra.

🎯 Desafio

Troque a mensagem de sistema para “Você é um pirata que ensina matemática” e peça para explicar frações. Depois tente “Responda só com emojis”. Mudar o comportamento da IA só com texto é o que chamam de engenharia de prompt.

💼 Onde isso te leva

Segundo o Relatório Futuro do Trabalho 2025 do Fórum Econômico Mundial, especialistas em IA e machine learning estão entre as três profissões que mais crescem no mundo até 2030. Saber integrar IA em programas é o primeiro degrau.

📚 Fontes e para ir além

📝 Publicado originalmente em 29 de novembro de 2023. Revisado, reescrito e com fontes conferidas em outubro de 2026.

Este artigo foi útil ?
SimNão

54 Replies to “Conversando com a IA: como um programa em Python fala com o ChatGPT”

  1. Example disse:

    A clear and useful article. It helped me understand the subject from a different angle.

  2. rafaelrjp disse:

    🎯 Desafio valendo: troque a mensagem de sistema para “Você é um pirata que ensina matemática” e me conta aqui a resposta mais engraçada que saiu! 🏴‍☠️

  3. rafaelrjp disse:

    🔐 Lembrete de segurança: nunca cole sua chave de API em código que vai para o GitHub nem em print de tela. Se vazar, apague a chave no painel e gere outra. Melhor prevenir do que pagar a conta dos outros!

  4. Dongstar disse:

    Good article. It is very unfortunate that over the last years, the travel industry has already been able to to take on terrorism, SARS, tsunamis, flu virus, swine flu, as well as the first ever real global economic collapse. Through all of it the industry has proven to be sturdy, resilient along with dynamic, discovering new tips on how to deal with difficulty. There are generally fresh complications and opportunities to which the field must just as before adapt and respond.

  5. I was just searching for this information for some time. After 6 hours of continuous Googleing, finally I got it in your web site. I wonder what is the lack of Google strategy that do not rank this type of informative websites in top of the list. Normally the top web sites are full of garbage.

  6. I can’t believe how amazing this article is! The author has done a tremendous job of presenting the information in an captivating and educational manner. I can’t thank her enough for offering such valuable insights that have certainly enriched my awareness in this subject area. Bravo to her for creating such a gem!

  7. In these days of austerity in addition to relative anxiousness about getting debt, most people balk about the idea of employing a credit card in order to make purchase of merchandise as well as pay for a vacation, preferring, instead just to rely on the actual tried as well as trusted way of making repayment – cash. However, if you possess cash on hand to make the purchase entirely, then, paradoxically, that is the best time to use the cards for several causes.

  8. phonyx disse:

    The gaming experience is top notch. I had a few questions and the customer support answered me right away. Really impressive service! phonyx

  9. phjili588 disse:

    I’ve tried a few sites lately but this one is really smooth. The games load fast and the payouts are fair. Definitely my new favorite spot! phjili588

  10. Another issue is that video games are normally serious in nature with the principal focus on understanding rather than amusement. Although, there is an entertainment feature to keep your children engaged, each and every game is normally designed to improve a specific experience or area, such as math concepts or scientific disciplines. Thanks for your publication.

  11. hello!,I love your writing very much! percentage we be in contact extra approximately your post on AOL? I require an expert in this house to solve my problem. May be that is you! Having a look ahead to see you.

  12. Hi, Neat post. There is a problem along with your site in web explorer, would check this? IE nonetheless is the market leader and a big part of people will pass over your excellent writing because of this problem.

  13. I believe this is among the such a lot vital information for me. And i am satisfied reading your article. But want to commentary on some general things, The website taste is great, the articles is truly great : D. Excellent task, cheers

  14. Hiya very nice site!! Guy .. Excellent .. Amazing .. I’ll bookmark your web site and take the feeds also?I’m glad to seek out a lot of helpful information right here within the submit, we want work out extra strategies on this regard, thank you for sharing. . . . . .

  15. trx vanity disse:

    This is very interesting, You are an excessively skilled blogger. I have joined your feed and sit up for in search of extra of your fantastic post. Also, I have shared your site in my social networks!

  16. It?s really a nice and helpful piece of information. I?m glad that you shared this useful info with us. Please keep us up to date like this. Thanks for sharing.

  17. I have recently started a site, the info you offer on this site has helped me tremendously. Thanks for all of your time & work.

  18. satta Matka disse:

    Hello there, I discovered your blog via Google at the same time as searching for a comparable topic, your site got here up, it looks good. I’ve bookmarked it in my google bookmarks.

  19. khabar disse:

    Thanks , I have just been searching for info about this subject for ages and yours is the best I’ve discovered till now. But, what about the bottom line? Are you sure about the source?

  20. Hello there, just became aware of your blog through Google, and found that it is truly informative. I am going to watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!

  21. I have taken notice that in digital camera models, special devices help to {focus|concentrate|maintain focus|target|a**** automatically. These sensors involving some video cameras change in in the area of contrast, while others start using a beam involving infra-red (IR) light, specifically in low lumination. Higher spec cameras often use a blend of both systems and could have Face Priority AF where the photographic camera can ‘See’ some sort of face while keeping focused only on that. Many thanks for sharing your thinking on this blog.

  22. I mastered more interesting things on this fat reduction issue. One particular issue is a good nutrition is very vital when dieting. A massive reduction in junk food, sugary ingredients, fried foods, sugary foods, beef, and white flour products could possibly be necessary. Retaining wastes bloodsuckers, and toxic compounds may prevent objectives for fat loss. While particular drugs temporarily solve the situation, the unpleasant side effects will not be worth it, plus they never supply more than a short lived solution. It’s a known undeniable fact that 95 of fad diets fail. Thanks for sharing your ideas on this web site.

  23. hey there and thank you in your info ? I have certainly picked up something new from proper here. I did then again expertise some technical issues the use of this website, as I skilled to reload the web site many instances previous to I could get it to load correctly. I have been brooding about if your web hosting is OK? Not that I am complaining, but sluggish loading circumstances times will often impact your placement in google and can injury your high-quality rating if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I?m adding this RSS to my email and can look out for a lot extra of your respective exciting content. Ensure that you replace this once more soon..

  24. klive disse:

    I love your wp web template, where do you download it from?

  25. Great blog here! Also your web site loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  26. Thanks for your publication. I also think that laptop computers have grown to be more and more popular today, and now in many cases are the only sort of computer found in a household. The reason being at the same time actually becoming more and more reasonably priced, their processing power keeps growing to the point where they are as highly effective as pc’s out of just a few in years past.

  27. playzonegame disse:

    The UI flow for a diverse gaming hub like this needs surgical precision; otherwise, feature overload hits hard. Love the concept, but keep the navigation snappy! Check out playzone game affiliate for some structure insights.

  28. usdt vanity disse:

    I know this if off topic but I’m looking into starting my own blog and was curious what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 certain. Any tips or advice would be greatly appreciated. Thank you

  29. Hey There. I discovered your blog the use of msn. This is a very well written article. I?ll be sure to bookmark it and come back to learn extra of your helpful info. Thanks for the post. I will certainly comeback.

  30. tpower disse:

    Excellent post however , I was wondering if you could write a litte more on this topic? I’d be very grateful if you could elaborate a little bit further. Bless you!

  31. tpower disse:

    Hi! I’m at work surfing around your blog from my new iphone 4! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the superb work!

  32. Dildo sleeve disse:

    Hey! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  33. Cock sleeve disse:

    Audio started playing when I opened up this web page, so frustrating!

  34. Nice post. I learn one thing more difficult on different blogs everyday. It is going to all the time be stimulating to learn content material from other writers and follow a bit of one thing from their store. I?d favor to make use of some with the content on my weblog whether or not you don?t mind. Natually I?ll provide you with a hyperlink in your web blog. Thanks for sharing.

  35. of course like your website but you need to check the spelling on several of your posts. Several of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I?ll definitely come back again.

  36. klive disse:

    This will be a fantastic blog, would you be interested in doing an interview about just how you created it? If so e-mail me!

  37. Wow, superb blog structure! How long have you ever been running a blog for? you made blogging look easy. The full glance of your site is fantastic, as neatly as the content material!

  38. I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Outstanding work!

  39. I cherished up to you’ll obtain performed proper here. The cartoon is tasteful, your authored subject matter stylish. nonetheless, you command get got an nervousness over that you want be turning in the following. ill no doubt come more beforehand once more since exactly the same just about very incessantly inside case you defend this hike.

  40. Thanks for your fascinating article. One other problem is that mesothelioma cancer is generally due to the breathing of dust from mesothelioma, which is a extremely dangerous material. It can be commonly noticed among staff in the engineering industry who may have long exposure to asbestos. It’s also caused by living in asbestos covered buildings for a long time of time, Inherited genes plays a huge role, and some people are more vulnerable on the risk when compared with others.

  41. agen king88 disse:

    I can’t express how much I value the effort the author has put into producing this exceptional piece of content. The clarity of the writing, the depth of analysis, and the plethora of information provided are simply impressive. Her passion for the subject is evident, and it has certainly resonated with me. Thank you, author, for sharing your wisdom and enlightening our lives with this incredible article!

  42. I do not even know how I ended up right here, however I assumed this put up used to be great. I don’t recognize who you’re but certainly you are going to a famous blogger when you aren’t already 😉 Cheers!

  43. agen king88 disse:

    Thanks for the post. My partner and i have often observed that a majority of people are desirous to lose weight as they wish to appear slim plus attractive. Even so, they do not usually realize that there are other benefits just for losing weight additionally. Doctors assert that fat people have problems with a variety of ailments that can be directly attributed to their own excess weight. The good news is that people that are overweight in addition to suffering from numerous diseases can reduce the severity of their illnesses by way of losing weight. You’ll be able to see a continuous but noted improvement with health while even a minor amount of losing weight is attained.

  44. king88 disse:

    Thanks, I’ve been seeking for details about this topic for ages and yours is the best I have discovered so far.

  45. ufabet disse:

    You could definitely see your enthusiasm in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always follow your heart.

  46. ufabet disse:

    Hello very nice web site!! Man .. Excellent .. Superb .. I’ll bookmark your blog and take the feeds additionally?I’m satisfied to seek out a lot of helpful information here within the submit, we need develop extra techniques on this regard, thank you for sharing. . . . . .

  47. I have realized some new points from your website about computers. Another thing I’ve always assumed is that laptop computers have become something that each residence must have for some reasons. They supply you with convenient ways in which to organize homes, pay bills, go shopping, study, focus on music and in some cases watch tv programs. An innovative way to complete every one of these tasks is a laptop computer. These computers are mobile ones, small, robust and easily transportable.

  48. Hi! I’ve been reading your site for a long time now and finally got the courage to go ahead and give you a shout out from Lubbock Texas! Just wanted to say keep up the fantastic work!

  49. I think that a property foreclosures can have a important effect on the client’s life. Foreclosures can have a 8 to decade negative effect on a client’s credit report. The borrower who have applied for a home loan or almost any loans for instance, knows that a worse credit rating is, the more tough it is for any decent financial loan. In addition, it can affect a borrower’s capacity to find a good place to let or hire, if that turns into the alternative houses solution. Great blog post.

  50. It?s actually a nice and helpful piece of information. I?m glad that you shared this useful info with us. Please keep us up to date like this. Thanks for sharing.

  51. rp8888casino disse:

    The live dealer tables feel so authentic and the slot variety keeps me entertained for hours on end. I really respect how smoothly the deposit and withdrawal process works, everything goes through securely and quickly. It is refreshing to play on a site that actually prioritizes player safety and fair play. Explore the games at rp8888casino

  52. ck445 disse:

    Honestly, setting up accounts sounds complicated! I just need something straightforward for my 10-minute break. Checking out ck445 ডাউনলোড seems like the easiest first step to see what’s actually fun there.

  53. I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back later on. Many thanks

  54. It is really a nice and helpful piece of information. I?m glad that you shared this useful info with us. Please keep us up to date like this. Thank you for sharing.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Close Search Window
↑