19 changed files with 1127 additions and 186 deletions
Binary file not shown.
Binary file not shown.
After Width: | Height: | Size: 432 KiB |
@ -0,0 +1,332 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "fe12c203-e6a6-452c-a655-afb8a03a4ff5", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# **End of week 1 exercise**\n", |
||||
"\n", |
||||
"To demonstrate your familiarity with OpenAI API, and also Ollama, build a tool that takes a technical question, \n", |
||||
"and responds with an explanation. This is a tool that you will be able to use yourself during the course!" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "c70e5ab1", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## **1. Get a response from your favorite AI Tutor** " |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 1, |
||||
"id": "c1070317-3ed9-4659-abe3-828943230e03", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"import os\n", |
||||
"from openai import OpenAI\n", |
||||
"import json\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"from IPython.display import Markdown, display, update_display" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "65dace69", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"load_dotenv()\n", |
||||
"api_key = os.getenv('OPENAI_API_KEY')\n", |
||||
"\n", |
||||
"if api_key and api_key.startswith('sk-proj-') and len(api_key) > 10:\n", |
||||
" print(\"API key looks good so far\")\n", |
||||
"else:\n", |
||||
" print(\"There might be a problem with your API key? Please visit the troubleshooting notebook!\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 3, |
||||
"id": "4a456906-915a-4bfd-bb9d-57e505c5093f", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# constants\n", |
||||
"\n", |
||||
"MODEL_GPT = 'gpt-4o-mini'\n", |
||||
"MODEL_LLAMA = 'llama3.2'\n", |
||||
"\n", |
||||
"openai = OpenAI()\n", |
||||
"\n", |
||||
"ollama_via_openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 38, |
||||
"id": "3673d863", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"system_prompt = \"\"\"You are the software engnieer, phd in mathematics, machine learning engnieer, and other topics\"\"\"\n", |
||||
"system_prompt += \"\"\"\n", |
||||
"When responding, always use Markdown for formatting. For any code, use well-structured code blocks with syntax highlighting,\n", |
||||
"For instance:\n", |
||||
"```python\n", |
||||
"\n", |
||||
"sample_list = [for i in range(10)]\n", |
||||
"```\n", |
||||
"Another example\n", |
||||
"```javascript\n", |
||||
" function displayMessage() {\n", |
||||
" alert(\"Hello, welcome to JavaScript!\");\n", |
||||
" }\n", |
||||
"\n", |
||||
"```\n", |
||||
"\n", |
||||
"Break down explanations into clear, numbered steps for better understanding. \n", |
||||
"Highlight important terms using inline code formatting (e.g., `function_name`, `variable`).\n", |
||||
"Provide examples for any concepts and ensure all examples are concise, clear, and relevant.\n", |
||||
"Your goal is to create visually appealing, easy-to-read, and informative responses.\n", |
||||
"\n", |
||||
"\"\"\"\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 39, |
||||
"id": "1df78d41", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def tutor_user_prompt(question):\n", |
||||
" # Ensure the question is properly appended to the user prompt.\n", |
||||
" user_prompt = (\n", |
||||
" \"Please carefully explain the following question in a step-by-step manner for clarity:\\n\\n\"\n", |
||||
" )\n", |
||||
" user_prompt += question\n", |
||||
" return user_prompt" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 43, |
||||
"id": "6dccbccb", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"\n", |
||||
"\n", |
||||
"def askTutor(question, MODEL):\n", |
||||
" # Generate the user prompt dynamically.\n", |
||||
" user_prompt = tutor_user_prompt(question)\n", |
||||
" \n", |
||||
" # OpenAI API call to generate response.\n", |
||||
" if MODEL == 'gpt-4o-mini':\n", |
||||
" print(f'You are getting response from {MODEL}')\n", |
||||
" stream = openai.chat.completions.create(\n", |
||||
" model=MODEL,\n", |
||||
" messages=[\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": user_prompt}\n", |
||||
" ],\n", |
||||
" stream=True\n", |
||||
" )\n", |
||||
" else:\n", |
||||
" MODEL == 'llama3.2'\n", |
||||
" print(f'You are getting response from {MODEL}')\n", |
||||
" stream = ollama_via_openai.chat.completions.create(\n", |
||||
" model=MODEL,\n", |
||||
" messages=[\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": user_prompt}\n", |
||||
" ],\n", |
||||
" stream=True\n", |
||||
" )\n", |
||||
"\n", |
||||
" # Initialize variables for response processing.\n", |
||||
" response = \"\"\n", |
||||
" display_handle = display(Markdown(\"\"), display_id=True)\n", |
||||
" \n", |
||||
" # Process the response stream and update display dynamically.\n", |
||||
" for chunk in stream:\n", |
||||
" # Safely access the content attribute.\n", |
||||
" response_chunk = getattr(chunk.choices[0].delta, \"content\", \"\")\n", |
||||
" if response_chunk: # Check if response_chunk is not None or empty\n", |
||||
" response += response_chunk\n", |
||||
" # No replacement of Markdown formatting here!\n", |
||||
" update_display(Markdown(response), display_id=display_handle.display_id)\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 44, |
||||
"id": "a8d7923c-5f28-4c30-8556-342d7c8497c1", |
||||
"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", |
||||
"\"\"\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "3f0d0137-52b0-47a8-81a8-11a90a010798", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"askTutor(question=question, MODEL=MODEL_GPT)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "b79f9479", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## **2. Using both LLMs collaboratively approach**" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "80e3c8f5", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"- I thought about like similar the idea of a RAG (Retrieval-Augmented Generation) approach, is an excellent idea to improve responses by refining the user query and producing a polished, detailed final answer. Two LLM talking each other its cool!!! Here's how we can implement this:\n", |
||||
"\n", |
||||
"**Updated Concept:**\n", |
||||
"1. Refine Query with Ollama:\n", |
||||
" - Use Ollama to refine the raw user query into a well-structured prompt.\n", |
||||
" - This is especially helpful when users input vague or poorly structured queries.\n", |
||||
"2. Generate Final Response with GPT:\n", |
||||
" - Pass the refined prompt from Ollama to GPT to generate the final, detailed, and polished response.\n", |
||||
"3. Return the Combined Output:\n", |
||||
" - Combine the input, refined query, and the final response into a single display to ensure clarity." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 59, |
||||
"id": "60f5ac2d", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def refine_with_ollama(raw_question):\n", |
||||
" \"\"\"\n", |
||||
" Use Ollama to refine the user's raw question into a well-structured prompt.\n", |
||||
" \"\"\"\n", |
||||
" print(\"Refining the query using Ollama...\")\n", |
||||
" messages = [\n", |
||||
" {\"role\": \"system\", \"content\": \"You are a helpful assistant. Refine and structure the following user input.\"},\n", |
||||
"\n", |
||||
" {\"role\": \"user\", \"content\": raw_question},\n", |
||||
" ]\n", |
||||
" response = ollama_via_openai.chat.completions.create(\n", |
||||
" model=MODEL_LLAMA,\n", |
||||
" messages=messages,\n", |
||||
" stream=False # Non-streamed refinement\n", |
||||
" )\n", |
||||
" refined_query = response.choices[0].message.content\n", |
||||
" return refined_query" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 60, |
||||
"id": "2aa4c9f6", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def ask_with_ollama_and_gpt(raw_question):\n", |
||||
" \"\"\"\n", |
||||
" Use Ollama to refine the user query and GPT to generate the final response.\n", |
||||
" \"\"\"\n", |
||||
" # Step 1: Refine the query using Ollama\n", |
||||
" refined_query = refine_with_ollama(raw_question)\n", |
||||
" \n", |
||||
" # Step 2: Generate final response with GPT\n", |
||||
" print(\"Generating the final response using GPT...\")\n", |
||||
" messages = [\n", |
||||
" {\"role\": \"system\", \"content\": system_prompt},\n", |
||||
" {\"role\": \"user\", \"content\": refined_query},\n", |
||||
" ]\n", |
||||
" stream = openai.chat.completions.create(\n", |
||||
" model=MODEL_GPT,\n", |
||||
" messages=messages,\n", |
||||
" stream=True # Stream response for dynamic display\n", |
||||
" )\n", |
||||
"\n", |
||||
" # Step 3: Combine responses\n", |
||||
" response = \"\"\n", |
||||
" display_handle = display(Markdown(f\"### Refined Query:\\n\\n{refined_query}\\n\\n---\\n\\n### Final Response:\"), display_id=True)\n", |
||||
" for chunk in stream:\n", |
||||
" response_chunk = getattr(chunk.choices[0].delta, \"content\", \"\")\n", |
||||
" if response_chunk:\n", |
||||
" response += response_chunk\n", |
||||
" update_display(Markdown(f\"### Refined Query:\\n\\n{refined_query}\\n\\n---\\n\\n### Final Response:\\n\\n{response}\"), display_id=display_handle.display_id)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 61, |
||||
"id": "4150e857", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Example Usage\n", |
||||
"question = \"\"\"\n", |
||||
"Please explain what this code does:\n", |
||||
"yield from {book.get(\"author\") for book in books if book.get(\"author\")}\n", |
||||
"\"\"\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "f2b8935f", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"ask_with_ollama_and_gpt(raw_question=question)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "086a5294", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [] |
||||
} |
||||
], |
||||
"metadata": { |
||||
"kernelspec": { |
||||
"display_name": "llm_env", |
||||
"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.11.9" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,342 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "06cf3063-9f3e-4551-a0d5-f08d9cabb927", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Welcome to Week 2!\n", |
||||
"\n", |
||||
"## Frontier Model APIs\n", |
||||
"\n", |
||||
"In Week 1, we used multiple Frontier LLMs through their Chat UI, and we connected with the OpenAI's API.\n", |
||||
"\n", |
||||
"Today we'll connect with the APIs for Anthropic and Google, as well as OpenAI." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "85cfe275-4705-4d30-abea-643fbddf1db0", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Setting up your keys\n", |
||||
"\n", |
||||
"If you haven't done so already, you could now create API keys for Anthropic and Google in addition to OpenAI.\n", |
||||
"\n", |
||||
"**Please note:** if you'd prefer to avoid extra API costs, feel free to skip setting up Anthopic and Google! You can see me do it, and focus on OpenAI for the course. You could also substitute Anthropic and/or Google for Ollama, using the exercise you did in week 1.\n", |
||||
"\n", |
||||
"For OpenAI, visit https://openai.com/api/ \n", |
||||
"For Anthropic, visit https://console.anthropic.com/ \n", |
||||
"For Google, visit https://ai.google.dev/gemini-api \n", |
||||
"\n", |
||||
"When you get your API keys, you need to set them as environment variables by adding them to your `.env` file.\n", |
||||
"\n", |
||||
"```\n", |
||||
"OPENAI_API_KEY=xxxx\n", |
||||
"ANTHROPIC_API_KEY=xxxx\n", |
||||
"GOOGLE_API_KEY=xxxx\n", |
||||
"```\n", |
||||
"\n", |
||||
"Afterwards, you may need to restart the Jupyter Lab Kernel (the Python process that sits behind this notebook) via the Kernel menu, and then rerun the cells from the top." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 12, |
||||
"id": "de23bb9e-37c5-4377-9a82-d7b6c648eeb6", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# imports\n", |
||||
"\n", |
||||
"import os\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"from openai import OpenAI\n", |
||||
"import anthropic\n", |
||||
"from IPython.display import Markdown, display, update_display\n", |
||||
"import google.generativeai # For gemini" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "1179b4c5-cd1f-4131-a876-4c9f3f38d2ba", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Load environment variables in a file called .env\n", |
||||
"# Print the key prefixes to help with any debugging\n", |
||||
"load_dotenv\n", |
||||
"\n", |
||||
"openai_api_key = os.getenv('OPENAI_API_KEY')\n", |
||||
"google_api_key = os.getenv('GOOGLE_API_KEY')\n", |
||||
"\n", |
||||
"if openai_api_key:\n", |
||||
" print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n", |
||||
"\n", |
||||
"else:\n", |
||||
" print(f\"OpenAI API Key not set\")\n", |
||||
"\n", |
||||
"if google_api_key:\n", |
||||
" print(f\"Google API Key exists and begins {google_api_key[:8]}\")\n", |
||||
"\n", |
||||
"else:\n", |
||||
" print(f\"Google API key not set\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 14, |
||||
"id": "1da06c1b", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# This for GPT model\n", |
||||
"openai = OpenAI()\n", |
||||
"\n", |
||||
"# This is for Gemini Google\n", |
||||
"gemini_via_openai = OpenAI(base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\", api_key=google_api_key)\n", |
||||
"\n", |
||||
"# This is for local Llama\n", |
||||
"\n", |
||||
"llama_via_openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n", |
||||
"\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 30, |
||||
"id": "f8aeb22f", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Model Name:\n", |
||||
"GPT_MODEL = 'gpt-4o-mini'\n", |
||||
"GEMINI_MODEL = 'gemini-1.5-flash'\n", |
||||
"LLAMA_MODEL = 'llama3.2'" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 51, |
||||
"id": "4e3007e9", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"gpt_system = \"You are a chatbot who is very argumentative; \\\n", |
||||
"you disagree with anything in the conversation and you challenge everything, in a snarky way.\"\n", |
||||
"\n", |
||||
"gemini_system = \"You are a logical and factual chatbot. Your role is to evaluate statements made in \\\n", |
||||
" the conversation and provide evidence or reasoning. You avoid emotional responses and aim to bring clarity and resolve conflicts. \\\n", |
||||
" When the conversation becomes heated or illogical, you steer it back to a constructive and fact-based discussion.\"\n", |
||||
"\n", |
||||
"\n", |
||||
"llama_system = \"You are a very polite, courteous chatbot. However, You try to disagree with your supportive\\\n", |
||||
"arguments. If the other person is argumentative, you try to calm them down, counter them, and keep chatting.\"\n", |
||||
"\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 44, |
||||
"id": "14d9b74e", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"\n", |
||||
"gpt_messages = [\"Hi there\"]\n", |
||||
"gemini_messages = [\"Hello\"]\n", |
||||
"llama_messages = [\"Hi\"]\n", |
||||
"\n", |
||||
"# gpt_messages = [\"I think cats are better than dogs.\"]\n", |
||||
"# gemini_messages = [\"Can you provide evidence for why cats are better than dogs?\"]\n", |
||||
"# llama_messages = [\"I agree, but I also think dogs have their own charm!\"]\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 53, |
||||
"id": "6c7e7250", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def call_gpt():\n", |
||||
" messages = [{\"role\": \"system\", \"content\": gpt_system}]\n", |
||||
" for gpt, gemini, llama in zip(gpt_messages, gemini_messages, llama_messages):\n", |
||||
" # Add GPT's response\n", |
||||
" messages.append({\"role\": \"assistant\", \"content\": gpt})\n", |
||||
" # Add Gemini's response\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gemini})\n", |
||||
" # Add Llama's response\n", |
||||
" messages.append({\"role\": \"user\", \"content\": llama})\n", |
||||
"\n", |
||||
" completion = openai.chat.completions.create(\n", |
||||
" model=GPT_MODEL,\n", |
||||
" messages=messages\n", |
||||
" )\n", |
||||
"\n", |
||||
" return completion.choices[0].message.content\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "2e0b601f", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"```python\n", |
||||
"messages:\n", |
||||
"[\n", |
||||
" {\"role\": \"system\", \"content\": \"You are a chatbot who is very argumentative; you disagree...\"},\n", |
||||
" {\"role\": \"assistant\", \"content\": \"I think cats are better than dogs.\"},\n", |
||||
" {\"role\": \"user\", \"content\": \"Can you provide evidence for why cats are better than dogs?\"},\n", |
||||
" {\"role\": \"user\", \"content\": \"I agree, but I also think dogs have their own charm!\"}\n", |
||||
"]\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "6c031314", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"call_gpt()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 55, |
||||
"id": "c2cb3905", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def call_gemini():\n", |
||||
" messages = [{\"role\": \"system\", \"content\": gemini_system}]\n", |
||||
" for gpt, gemini, llama in zip(gpt_messages, gemini_messages, llama_messages):\n", |
||||
" # Add GPT's response\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gpt})\n", |
||||
" # Add Gemini's response\n", |
||||
" messages.append({\"role\": \"assistant\", \"content\": gemini})\n", |
||||
" # Add Llama's response\n", |
||||
" messages.append({\"role\": \"user\", \"content\": llama})\n", |
||||
" \n", |
||||
" # print(messages)\n", |
||||
"\n", |
||||
" try:\n", |
||||
" # Use gemini_via_openai instead of openai\n", |
||||
" completion = gemini_via_openai.chat.completions.create(\n", |
||||
" model=GEMINI_MODEL,\n", |
||||
" messages=messages\n", |
||||
" )\n", |
||||
" return completion.choices[0].message.content\n", |
||||
" except Exception as e:\n", |
||||
" print(f\"Error in Gemini call: {e}\")\n", |
||||
" return \"An error occurred in Gemini.\"\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "5c9d4803", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"call_gemini()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": 56, |
||||
"id": "109e63e4", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def call_llama():\n", |
||||
" messages = [{\"role\": \"system\", \"content\": llama_system}]\n", |
||||
" for gpt, gemini, llama in zip(gpt_messages, gemini_messages, llama_messages):\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gpt})\n", |
||||
" messages.append({\"role\": \"user\", \"content\": gemini})\n", |
||||
" messages.append({\"role\": \"assistant\", \"content\": llama})\n", |
||||
"\n", |
||||
" # print(messages)\n", |
||||
"\n", |
||||
" try:\n", |
||||
" response = llama_via_openai.chat.completions.create(\n", |
||||
" model=LLAMA_MODEL,\n", |
||||
" messages=messages\n", |
||||
" )\n", |
||||
" return response.choices[0].message.content\n", |
||||
" except Exception as e:\n", |
||||
" print(f\"Error in Llama call: {e}\")\n", |
||||
" return \"An error occurred in Llama.\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "6e24eb6d", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"call_llama()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "f76f5b2a", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"gpt_messages = [\"I think cats are better than dogs.\"]\n", |
||||
"gemini_messages = [\"Can you provide evidence for why cats are better than dogs?\"]\n", |
||||
"llama_messages = [\"I agree, but I also think dogs have their own charm!\"]\n", |
||||
"\n", |
||||
"print(f\"GPT:\\n{gpt_messages[0]}\\n\")\n", |
||||
"print(f\"Llama:\\n{llama_messages[0]}\\n\")\n", |
||||
"\n", |
||||
"for i in range(5):\n", |
||||
" gpt_next = call_gpt()\n", |
||||
" print(f\"GPT:\\n{gpt_next}\\n\")\n", |
||||
" gpt_messages.append(gpt_next)\n", |
||||
" \n", |
||||
" llama_next = call_llama()\n", |
||||
" print(f\"Llama:\\n{llama_next}\\n\")\n", |
||||
" llama_messages.append(llama_next)\n", |
||||
"\n", |
||||
" gemini_next = call_llama()\n", |
||||
" print(f\"Gemini:\\n{gemini_next}\\n\")\n", |
||||
" llama_messages.append(gemini_next)" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "80f0e498", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [] |
||||
} |
||||
], |
||||
"metadata": { |
||||
"kernelspec": { |
||||
"display_name": "llm_env", |
||||
"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.11.9" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
@ -0,0 +1,264 @@
|
||||
{ |
||||
"cells": [ |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "ddfa9ae6-69fe-444a-b994-8c4c5970a7ec", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"# Project - Airline AI Assistant\n", |
||||
"\n", |
||||
"We'll now bring together what we've learned to make an AI Customer Support assistant for an Airline" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "8b50bbe2-c0b1-49c3-9a5c-1ba7efa2bcb4", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# imports\n", |
||||
"\n", |
||||
"import os\n", |
||||
"import json\n", |
||||
"from dotenv import load_dotenv\n", |
||||
"from openai import OpenAI\n", |
||||
"import gradio as gr" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "747e8786-9da8-4342-b6c9-f5f69c2e22ae", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Initialization\n", |
||||
"\n", |
||||
"load_dotenv()\n", |
||||
"\n", |
||||
"openai_api_key = os.getenv('OPENAI_API_KEY')\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\")\n", |
||||
" \n", |
||||
"MODEL = \"gpt-4o-mini\"\n", |
||||
"openai = OpenAI()\n", |
||||
"\n", |
||||
"# As an alternative, if you'd like to use Ollama instead of OpenAI\n", |
||||
"# Check that Ollama is running for you locally (see week1/day2 exercise) then uncomment these next 2 lines\n", |
||||
"# MODEL = \"llama3.2\"\n", |
||||
"# openai = OpenAI(base_url='http://localhost:11434/v1', api_key='ollama')\n" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "0a521d84-d07c-49ab-a0df-d6451499ed97", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"system_message = \"You are a helpful assistant for an Airline called FlightAI. \"\n", |
||||
"system_message += \"Give short, courteous answers, no more than 1 sentence. \"\n", |
||||
"system_message += \"Always be accurate. If you don't know the answer, say so.\"" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "61a2a15d-b559-4844-b377-6bd5cb4949f6", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# This function looks rather simpler than the one from my video, because we're taking advantage of the latest Gradio updates\n", |
||||
"\n", |
||||
"def chat(message, history):\n", |
||||
" messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n", |
||||
" response = openai.chat.completions.create(model=MODEL, messages=messages)\n", |
||||
" return response.choices[0].message.content\n", |
||||
"\n", |
||||
"gr.ChatInterface(fn=chat, type=\"messages\").launch()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "36bedabf-a0a7-4985-ad8e-07ed6a55a3a4", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Tools\n", |
||||
"\n", |
||||
"Tools are an incredibly powerful feature provided by the frontier LLMs.\n", |
||||
"\n", |
||||
"With tools, you can write a function, and have the LLM call that function as part of its response.\n", |
||||
"\n", |
||||
"Sounds almost spooky.. we're giving it the power to run code on our machine?\n", |
||||
"\n", |
||||
"Well, kinda." |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "0696acb1-0b05-4dc2-80d5-771be04f1fb2", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# Let's start by making a useful function\n", |
||||
"\n", |
||||
"ticket_prices = {\"london\": \"$799\", \"paris\": \"$899\", \"tokyo\": \"$1400\", \"berlin\": \"$499\"}\n", |
||||
"\n", |
||||
"def get_ticket_price(destination_city):\n", |
||||
" print(f\"Tool get_ticket_price called for {destination_city}\")\n", |
||||
" city = destination_city.lower()\n", |
||||
" return ticket_prices.get(city, \"Unknown\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "80ca4e09-6287-4d3f-997d-fa6afbcf6c85", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"get_ticket_price(\"Berlin\")" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "4afceded-7178-4c05-8fa6-9f2085e6a344", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# There's a particular dictionary structure that's required to describe our function:\n", |
||||
"\n", |
||||
"price_function = {\n", |
||||
" \"name\": \"get_ticket_price\",\n", |
||||
" \"description\": \"Get the price of a return ticket to the destination city. Call this whenever you need to know the ticket price, for example when a customer asks 'How much is a ticket to this city'\",\n", |
||||
" \"parameters\": {\n", |
||||
" \"type\": \"object\",\n", |
||||
" \"properties\": {\n", |
||||
" \"destination_city\": {\n", |
||||
" \"type\": \"string\",\n", |
||||
" \"description\": \"The city that the customer wants to travel to\",\n", |
||||
" },\n", |
||||
" },\n", |
||||
" \"required\": [\"destination_city\"],\n", |
||||
" \"additionalProperties\": False\n", |
||||
" }\n", |
||||
"}" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "bdca8679-935f-4e7f-97e6-e71a4d4f228c", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# And this is included in a list of tools:\n", |
||||
"\n", |
||||
"tools = [{\"type\": \"function\", \"function\": price_function}]" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "markdown", |
||||
"id": "c3d3554f-b4e3-4ce7-af6f-68faa6dd2340", |
||||
"metadata": {}, |
||||
"source": [ |
||||
"## Getting OpenAI to use our Tool\n", |
||||
"\n", |
||||
"There's some fiddly stuff to allow OpenAI \"to call our tool\"\n", |
||||
"\n", |
||||
"What we actually do is give the LLM the opportunity to inform us that it wants us to run the tool.\n", |
||||
"\n", |
||||
"Here's how the new chat function looks:" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "ce9b0744-9c78-408d-b9df-9f6fd9ed78cf", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"def chat(message, history):\n", |
||||
" messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n", |
||||
" response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)\n", |
||||
"\n", |
||||
" if response.choices[0].finish_reason==\"tool_calls\":\n", |
||||
" message = response.choices[0].message\n", |
||||
" responses = handle_tool_call(message)\n", |
||||
" messages.append(message)\n", |
||||
" for response in responses:\n", |
||||
" messages.append(response)\n", |
||||
" response = openai.chat.completions.create(model=MODEL, messages=messages)\n", |
||||
" \n", |
||||
" return response.choices[0].message.content" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "b0992986-ea09-4912-a076-8e5603ee631f", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"# We have to write that function handle_tool_call:\n", |
||||
"\n", |
||||
"def handle_tool_call(message):\n", |
||||
" responses = []\n", |
||||
" for tool_call in message.tool_calls:\n", |
||||
" arguments = json.loads(tool_call.function.arguments)\n", |
||||
" city = arguments.get('destination_city')\n", |
||||
" price = get_ticket_price(city)\n", |
||||
" responses.append({\n", |
||||
" \"role\": \"tool\",\n", |
||||
" \"content\": json.dumps({\"destination_city\": city,\"price\": price}),\n", |
||||
" \"tool_call_id\": tool_call.id\n", |
||||
" })\n", |
||||
" return responses" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "f4be8a71-b19e-4c2f-80df-f59ff2661f14", |
||||
"metadata": {}, |
||||
"outputs": [], |
||||
"source": [ |
||||
"gr.ChatInterface(fn=chat, type=\"messages\").launch()" |
||||
] |
||||
}, |
||||
{ |
||||
"cell_type": "code", |
||||
"execution_count": null, |
||||
"id": "11c9da69-d0cf-4cf2-a49e-e5669deec47b", |
||||
"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.11.11" |
||||
} |
||||
}, |
||||
"nbformat": 4, |
||||
"nbformat_minor": 5 |
||||
} |
Loading…
Reference in new issue