{ "cells": [ { "cell_type": "markdown", "id": "135ee16c-2741-4ebf-aca9-1d263083b3ce", "metadata": {}, "source": [ "# End of week 1 exercise\n", "\n", "Build a tutor tool by using Ollama." ] }, { "cell_type": "code", "execution_count": null, "id": "c1070317-3ed9-4659-abe3-828943230e03", "metadata": {}, "outputs": [], "source": [ "# imports\n", "import ollama\n", "from IPython.display import Markdown, display, clear_output" ] }, { "cell_type": "code", "execution_count": null, "id": "4a456906-915a-4bfd-bb9d-57e505c5093f", "metadata": {}, "outputs": [], "source": [ "# constants\n", "MODEL_LLAMA = 'llama3.2'" ] }, { "cell_type": "code", "execution_count": null, "id": "3f0d0137-52b0-47a8-81a8-11a90a010798", "metadata": {}, "outputs": [], "source": [ "# here is the question; type over this to ask something new\n", "\n", "question = \"\"\"\n", "Please explain what this code does and why:\n", "yield from {book.get(\"author\") for book in books if book.get(\"author\")}\n", "\"\"\"\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "8f7c8ea8-4082-4ad0-8751-3301adcf6538", "metadata": {}, "outputs": [], "source": [ "# Get Llama 3.2 to answer, with streaming\n", "\n", "\n", "messages=[{\"role\":\"user\",\"content\":question}]\n", "\n", "for chunk in ollama.chat(model=MODEL_LLAMA, messages=messages, stream=True):\n", " print(chunk['message']['content'], end='', flush=True)\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d1f71014-e780-4d3f-a227-1a7c18158a4c", "metadata": {}, "outputs": [], "source": [ "#Alternative answer with streaming in Markdown!\n", "\n", "def stream_response():\n", " messages = [{\"role\": \"user\", \"content\": question}]\n", " \n", " display_markdown = display(Markdown(\"\"), display_id=True)\n", "\n", " response_text = \"\"\n", " for chunk in ollama.chat(model=MODEL_LLAMA, messages=messages, stream=True):\n", " \n", " response_text += chunk['message']['content']\n", " clear_output(wait=True) # Clears previous output\n", " display_markdown.update(Markdown(response_text)) # Updates Markdown dynamically\n", "\n", "# Run the function\n", "stream_response()" ] }, { "cell_type": "code", "execution_count": null, "id": "c38fdd2a-4b09-402c-ba46-999b22b0cb15", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 5 }