<div class="flex flex-col h-screen">
  <!-- Reply Section -->
  <div class="flex-1 overflow-y-auto p-4 space-y-4">
    <!-- Sample messages -->
  
    <pre class="bg-blue-100 text-blue-900 max-w-lg p-3 rounded-lg overflow-x-auto break-words whitespace-pre-wrap" id="response">Ask Something 🤖</pre>
      <div class="animate-pulse hidden bg-blue-100 text-blue-900 max-w-lg" id="loader">thinking...</div>
    <!-- Add more messages here -->
  </div>

  <!-- Chat Input -->
  <div class="border-t-2 border-gray-200 p-4 flex gap-2">
    <input type="text" id="prompt" placeholder="Type your message here..." class="w-96 rounded-full border-gray-300 p-2 shadow-sm focus:outline-none focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"/>
    <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onclick="callOllama()">
  Click me
</button>
  </div>
</div>
window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 10000;

const callOllama = async () => {
  const responseElement = document.querySelector("#response");
  const loader = document.querySelector("#loader");
  loader.classList.remove("hidden")
  responseElement.textContent = ""
  
  try {
    const response = await fetch("http://localhost:11434/api/generate", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        model: "llama2",
        prompt: document.querySelector("input").value,
        stream: true,
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    loader.classList.add("hidden")
   
    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;

      const decodedChunk = decoder.decode(value, { stream: true });
      try {
        const formattedChunk = JSON.parse(decodedChunk);
        const responseText = formattedChunk.response || "";
        responseElement.textContent += responseText;
      } catch (error) {
        console.error("Error parsing chunk", error);
        // Handle parsing error or show a message to the user
      }
    }
  } catch (error) {
    console.error("Fetch error:", error);
    // Handle fetch error or show a message to the user
  }
};

External CSS

  1. https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css

External JavaScript

This Pen doesn't use any external JavaScript resources.