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
- Ela pode inventar. Isso se chama alucinação). Sempre confira datas, números e nomes.
- Privacidade: não envie dados pessoais (seus ou de outras pessoas) para a API.
- Humano no comando: use a IA para rascunhar; quem decide e assina é você.
- 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
- Documentação da API da OpenAI — geração de texto
- Lista oficial de modelos da OpenAI
- Biblioteca oficial openai-python (GitHub)
- Termos de Uso da OpenAI
- ChatGPT — Wikipédia
- Code.org: IA para estudantes (em português)
- Elements of AI — curso gratuito sobre IA
📝 Publicado originalmente em 29 de novembro de 2023. Revisado, reescrito e com fontes conferidas em outubro de 2026.
Last modified: 29 de novembro de 2023
A clear and useful article. It helped me understand the subject from a different angle.
🎯 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! 🏴☠️
🔐 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!
An attention-grabbing dialogue is value comment. I feel that it is best to write extra on this matter, it may not be a taboo topic however typically persons are not enough to talk on such topics. To the next. Cheers
One important issue is that if you find yourself searching for a education loan you may find that you will need a co-signer. There are many circumstances where this is correct because you might discover that you do not employ a past credit ranking so the lender will require you have someone cosign the loan for you. Thanks for your post.
I truly appreciate this post. I?ve been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thanks again
I’m impressed by the quality of this content! The author has obviously put a great amount of effort into investigating and arranging the information. It’s exciting to come across an article that not only gives valuable information but also keeps the readers engaged from start to finish. Great job to her for creating such a brilliant work!
Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why waste your intelligence on just posting videos to your site when you could be giving us something informative to read?
I have observed that car insurance businesses know the autos which are prone to accidents and various risks. In addition they know what types of cars are inclined to higher risk and also the higher risk they may have the higher the particular premium rate. Understanding the simple basics connected with car insurance will assist you to choose the right form of insurance policy that may take care of your preferences in case you happen to be involved in an accident. Many thanks sharing the particular ideas for your blog.
Thanks for sharing this perspective on this topic. The explanation is clear, and the practical details make the main idea easy to understand. A related resource I came across is just my sock.
Practical advice on sell house fast options can help homeowners avoid rushing into unclear agreements. https://sellwithdealmate.com/
Reading about we buy houses for cash can help sellers recognize questions to ask before accepting an offer. https://sellwithdealmate.com/
Feeling really lucky today! This site has a great atmosphere and the games are super addictive in a good way. Five stars. pkluckyi8game
Finally found a platform that actually delivers on its promises. The game variety is top notch and it feels very secure. Highly recommend phjilipark22 for anyone looking for some real action.
This whole platform feels solid; the blend of tradition and tech is smart. Checking out mm88a casino gave me a good feel for the depth, even beyond the slot focus. Gotta check the live casino next!
Normally I don’t read article on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been surprised me. Thanks, quite nice post.
Hello there, I discovered your site by means of Google even as looking for a related subject, your website got here up, it looks good. I have bookmarked it in my google bookmarks.
I’ve been looking for a reliable platform for a while and this one really delivers. The interface is smooth and the payouts are fast. Definitely check out asia128login for a great experience.
Hiya! I know this is kinda off topic nevertheless I’d figured I’d ask. Would you be interested in trading links or maybe guest writing a blog post or vice-versa? My site discusses a lot of the same subjects as yours and I think we could greatly benefit from each other. If you’re interested feel free to send me an e-mail. I look forward to hearing from you! Superb blog by the way!
Thanks for this wonderful article. Yet another thing to mention is that most digital cameras can come equipped with a zoom lens that enables more or less of any scene to become included through ‘zooming’ in and out. These types of changes in {focus|focusing|concentration|target|the a**** length tend to be reflected in the viewfinder and on large display screen on the back of the actual camera.