🤖 Como Criar um Chatbot com Ollama usando Python

Neste tutorial, você aprenderá a integrar a API do Ollama em um sistema de chatbot com exemplos em Python, destacando como a IA pode transformar a interação com usuários.

Requisitos:

📌 Passo 1: Instalar as dependências do Python

Para rodar o chatbot com a API do Ollama, instale as bibliotecas necessárias via pip.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install flask requests
pip install flask requests
pip install flask requests
  • Flask: Para criar o servidor web do chatbot.
  • Requests: Para fazer requisições HTTP à API do Ollama.

📌 Passo 2: Criar o Backend (Python)

Crie um arquivo chamado app.py com o seguinte conteúdo:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
@app.route("/api/chat", methods=["POST"])
def chat():
user_message = request.json.get("prompt")
model = "llama3" # Substitua pelo modelo desejado (ex: "mistral", "llama2")
# Requisição para o Ollama
response = requests.post(
"http://localhost:1143/api/generate",
json={
"model": model,
"prompt": user_message,
"stream": False
}
)
# Formatar a resposta
data = response.json()
return jsonify({"response": data["response"]})
if __name__ == "__main__":
app.run(debug=True)
from flask import Flask, request, jsonify import requests app = Flask(__name__) @app.route("/api/chat", methods=["POST"]) def chat(): user_message = request.json.get("prompt") model = "llama3" # Substitua pelo modelo desejado (ex: "mistral", "llama2") # Requisição para o Ollama response = requests.post( "http://localhost:1143/api/generate", json={ "model": model, "prompt": user_message, "stream": False } ) # Formatar a resposta data = response.json() return jsonify({"response": data["response"]}) if __name__ == "__main__": app.run(debug=True)
from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

@app.route("/api/chat", methods=["POST"])
def chat():
    user_message = request.json.get("prompt")
    model = "llama3"  # Substitua pelo modelo desejado (ex: "mistral", "llama2")

    # Requisição para o Ollama
    response = requests.post(
        "http://localhost:1143/api/generate",
        json={
            "model": model,
            "prompt": user_message,
            "stream": False
        }
    )

    # Formatar a resposta
    data = response.json()
    return jsonify({"response": data["response"]})

if __name__ == "__main__":
    app.run(debug=True)

📌 Passo 3: Criar a Interface do Chatbot (HTML + JavaScript)

Crie um arquivo index.html para a interface do usuário:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<title>Chatbot com IA</title>
<style>
body { font-family: Arial, sans-serif; background: #f0f0f0; padding: 20px; }
#chat { background: #fff; border: 1px solid #ccc; padding: 15px; margin-bottom: 10px; }
.user { color: #007bff; }
.ai { color: #28a745; }
</style>
</head>
<body>
<h1>Chatbot com IA</h1>
<div id="chat"></div>
<input type="text" id="userInput" placeholder="Digite sua mensagem..." />
<button onclick="sendMessage()">Enviar</button>
<script>
async function sendMessage() {
const input = document.getElementById("userInput").value;
const chat = document.getElementById("chat");
chat.innerHTML += `<div><strong>Você:</strong> ${input}</div>`;
document.getElementById("userInput").value = "";
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: input })
});
const data = await response.json();
chat.innerHTML += `<div><strong>IA:</strong> ${data.response}</div>`;
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>Chatbot com IA</title> <style> body { font-family: Arial, sans-serif; background: #f0f0f0; padding: 20px; } #chat { background: #fff; border: 1px solid #ccc; padding: 15px; margin-bottom: 10px; } .user { color: #007bff; } .ai { color: #28a745; } </style> </head> <body> <h1>Chatbot com IA</h1> <div id="chat"></div> <input type="text" id="userInput" placeholder="Digite sua mensagem..." /> <button onclick="sendMessage()">Enviar</button> <script> async function sendMessage() { const input = document.getElementById("userInput").value; const chat = document.getElementById("chat"); chat.innerHTML += `<div><strong>Você:</strong> ${input}</div>`; document.getElementById("userInput").value = ""; const response = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: input }) }); const data = await response.json(); chat.innerHTML += `<div><strong>IA:</strong> ${data.response}</div>`; } </script> </body> </html>
<!DOCTYPE html>
<html>
<head>
    <title>Chatbot com IA</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f0f0f0; padding: 20px; }
        #chat { background: #fff; border: 1px solid #ccc; padding: 15px; margin-bottom: 10px; }
        .user { color: #007bff; }
        .ai { color: #28a745; }
    </style>
</head>
<body>
    <h1>Chatbot com IA</h1>
    <div id="chat"></div>
    <input type="text" id="userInput" placeholder="Digite sua mensagem..." />
    <button onclick="sendMessage()">Enviar</button>

    <script>
        async function sendMessage() {
            const input = document.getElementById("userInput").value;
            const chat = document.getElementById("chat");
            chat.innerHTML += `<div><strong>Você:</strong> ${input}</div>`;
            document.getElementById("userInput").value = "";

            const response = await fetch("/api/chat", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ prompt: input })
            });

            const data = await response.json();
            chat.innerHTML += `<div><strong>IA:</strong> ${data.response}</div>`;
        }
    </script>
</body>
</html>

📌 Passo 4: Rodar o Chatbot

  • Execute o servidor Python:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
python app.py
python app.py
python app.py
  • Acesse o chatbot no navegador:

Abra http://localhost:5000 (ou a porta configurada) e interaja com o chatbot.

📌 Dicas Adicionais

  • Modelos disponíveis: Substitua "llama3" pelo modelo desejado (ex: "mistral", "llama2").
  • Personalização: Adicione estilos, memória de conversa ou integração com APIs externas.
  • Segurança: Para produção, valide entradas e use HTTPS.

Pronto! Seu chatbot com IA está funcionando! 🤖✨