{ "cells": [ { "cell_type": "markdown", "id": "cde48e67-b51e-4c47-80ae-37dd00aa0c1d", "metadata": {}, "source": [ "### An AI Chatbot that teaches students the programming language Kotlin using Anthropic API" ] }, { "cell_type": "code", "execution_count": 5, "id": "c658ac85-6087-4a2c-b23f-1b92c17f0db3", "metadata": {}, "outputs": [], "source": [ "# imports\n", "\n", "import os\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "import gradio as gr\n", "import anthropic" ] }, { "cell_type": "code", "execution_count": 13, "id": "46df0488-f874-41e0-a6a4-9a64aa7be53c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "OpenAI API Key exists and begins sk-proj-\n" ] } ], "source": [ "# Load environment variables \n", "\n", "load_dotenv(override=True)\n", "openai_api_key = os.getenv('OPENAI_API_KEY')\n", " \n", "if openai_api_key:\n", " print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n", "else:\n", " print(\"OpenAI API Key not set\")" ] }, { "cell_type": "code", "execution_count": 14, "id": "7eadc218-5b10-4174-bf26-575361640524", "metadata": {}, "outputs": [], "source": [ "openai = OpenAI()" ] }, { "cell_type": "code", "execution_count": 7, "id": "e7484731-ac84-405a-a688-6e81d139c5ce", "metadata": {}, "outputs": [], "source": [ "system_message = \"You are a helpful programming study assistant\"" ] }, { "cell_type": "code", "execution_count": 17, "id": "54e82f5a-993f-4a95-9d9d-caf35dbc4e76", "metadata": {}, "outputs": [], "source": [ "def chat(message, history):\n", " messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n", "\n", " print(\"History is:\")\n", " print(history)\n", " print(\"And messages is:\")\n", " print(messages)\n", "\n", " stream = openai.chat.completions.create(model='gpt-4o-mini', messages=messages, stream=True)\n", "\n", " response = \"\"\n", " for chunk in stream:\n", " response += chunk.choices[0].delta.content or ''\n", " yield response" ] }, { "cell_type": "code", "execution_count": 20, "id": "5941ed67-e2a7-41bc-a8a3-079e9f1fdb64", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7864\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "