diff --git a/week1/community-contributions/Week_1-Day 5-Article_Title_Generator-V3_Firecrawl.ipynb b/week1/community-contributions/Week_1-Day 5-Article_Title_Generator-V3_Firecrawl.ipynb
new file mode 100644
index 0000000..05ba0a7
--- /dev/null
+++ b/week1/community-contributions/Week_1-Day 5-Article_Title_Generator-V3_Firecrawl.ipynb
@@ -0,0 +1,532 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "603cd418-504a-4b4d-b1c3-be04febf3e79",
+ "metadata": {},
+ "source": [
+ "# Article Title Generator (V3 - using Firecrawl) \n",
+ "\n",
+ "Summarization use-case in which the user provides an article, which the LLM will analyze to suggest an SEO-optimized title.\n",
+ "\n",
+ "**NOTES**:\n",
+ "\n",
+ "1. This version supports website scrapping using [Firecrawl](https://www.firecrawl.dev/).
\n",
+ " 1. **Note:** There is a Free tier that provides 500 one-time credits (good for scraping 500 pages).\n",
+ " 2. Upon registration, get and add your Firecrawl API Key to the .env file as: **`FIRECRAWL_API_KEY`**.
\n",
+ "2. Leverage streaming (OpenAI only).
\n",
+ "3. The following models were configured:
\n",
+ " 1. OpenAI gpt-4o-mini\n",
+ " 2. Llama llama3.2\n",
+ " 3. Deepseek deepseek-r1:1.5b\n",
+ " 4. Firecrawl LLM Extract feature
\n",
+ " \n",
+ " It is possible to configure additional models by adding the new model to the MODELS dictionary and its\n",
+ " initialization to the CLIENTS dictionary. Then, call the model with --> **`answer =\n",
+ " get_answer('NEW_MODEL')`**.
\n",
+ "4. Users are encouraged to assess and rank the suggested titles using any headline analyzer tool online.\n",
+ " Example: [ISITWP Headline Analyzer](https://www.isitwp.com/headline-analyzer/). "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "115004a8-747a-4954-9580-1ed548f80336",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# install required libraries if they were not part of the requirements.txt\n",
+ "!pip install firecrawl-py"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e773daa6-d05e-49bf-ad8e-a8ed4882b77e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# confirming Llama is loaded\n",
+ "!ollama pull llama3.2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "279b0c00-9bb0-4c7f-9c6d-aa0b108274b9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "import os\n",
+ "from dotenv import load_dotenv\n",
+ "from IPython.display import Markdown, display, update_display\n",
+ "from openai import OpenAI\n",
+ "from firecrawl import FirecrawlApp"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d4730d8d-3e20-4f3c-a4ff-ed2ac0a8aa27",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# set environment variables for OpenAi\n",
+ "load_dotenv(override=True)\n",
+ "api_key = os.getenv('OPENAI_API_KEY')\n",
+ "\n",
+ "# validate API Key\n",
+ "if not api_key:\n",
+ " raise ValueError(\"No OPENAI API Key was found! Please check the .env file.\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b2a78101-d866-400f-a482-1d8fda8e0df9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# set environment variable for Firecrawl\n",
+ "firecrawl_api_key = os.getenv('FIRECRAWL_API_KEY')\n",
+ "\n",
+ "# validate API Key\n",
+ "if not firecrawl_api_key:\n",
+ " raise ValueError(\"No FIRECRAWL API Key was found! Please check the .env file.\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1abbb826-de66-498c-94d8-33369ad01885",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# constants\n",
+ "MODELS = { 'GPT': 'gpt-4o-mini', \n",
+ " 'LLAMA': 'llama3.2', \n",
+ " 'DEEPSEEK': 'deepseek-r1:1.5b'\n",
+ " }\n",
+ "\n",
+ "CLIENTS = { 'GPT': OpenAI(), \n",
+ " 'LLAMA': OpenAI(base_url='http://localhost:11434/v1', api_key='ollama'),\n",
+ " 'DEEPSEEK': OpenAI(base_url='http://localhost:11434/v1', api_key='ollama') \n",
+ " }\n",
+ "\n",
+ "# path to Chrome\n",
+ "# CHROME_PATH = \"C:/Program Files/Google/Chrome/Application/chrome.exe\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6f490fe4-32d5-41f3-890d-ecf4e5e01dd4",
+ "metadata": {},
+ "source": [
+ "**Webcrawler** (based on the code from Firecrawl [documentation](https://docs.firecrawl.dev/introduction))."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2852700e-33ed-4be5-bd31-8aa05036aaf2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class WebsiteCrawler:\n",
+ " def __init__(self, url, wait_time=20, format='markdown'):\n",
+ " \"\"\"\n",
+ " Initialize the WebsiteCrawler using Firecrawl to scrape JavaScript-rendered content.\n",
+ " \"\"\"\n",
+ " self.url = url\n",
+ " self.wait_time = wait_time\n",
+ " self.format = format\n",
+ "\n",
+ " try:\n",
+ "\n",
+ " # initialize Firecrawl\n",
+ " screate_app = FirecrawlApp(api_key=firecrawl_api_key)\n",
+ "\n",
+ " # Scrape a website:\n",
+ " scrape_result = screate_app.scrape_url(self.url,\n",
+ " params=self.getParams())\n",
+ " \n",
+ "\n",
+ " # parse data\n",
+ " self.title = scrape_result['metadata']['ogTitle']\n",
+ "\n",
+ " # get the content using the appropriate key\n",
+ " if format == 'markdown':\n",
+ " # OpenAI, Llama, Deepseek\n",
+ " self.text = scrape_result['markdown'] \n",
+ " elif format == 'json':\n",
+ " # Firecrawl LLM Extract\n",
+ " self.text = scrape_result['json']\n",
+ "\n",
+ " except Exception as e:\n",
+ " print(f\"Error occurred: {e}\")\n",
+ " self.title = \"Error occurred\"\n",
+ " self.text = \"\"\n",
+ "\n",
+ " # set appropriate parameters for scraping\n",
+ " def getParams(self):\n",
+ "\n",
+ " # For OpenAi, Llama or Deepseek\n",
+ " params={'formats': [self.format], \n",
+ " 'actions': [{\"type\": \"wait\", \"milliseconds\": self.wait_time}], \n",
+ " 'includeTags': [\"main\"], }\n",
+ "\n",
+ " # For Firecrawl LLM extract\n",
+ " if self.format == 'json':\n",
+ " params={'formats': [self.format], \n",
+ " 'actions': [{\"type\": \"wait\", \"milliseconds\": self.wait_time}], \n",
+ " 'jsonOptions': {'systemPrompt': system_prompt, 'prompt': user_prompt, }}\n",
+ " \n",
+ " return params\n",
+ "\n",
+ " # Get Firecrawl LLM extract result\n",
+ " def getResult(self):\n",
+ "\n",
+ " formated_result = f\"\"\"\n",
+ " **Optimized Title:** {self.text['Optimized Title']} \n",
+ "
**Justification:** {self.text['Justification']}\n",
+ " \"\"\"\n",
+ "\n",
+ " # Remove leading and trailing spaces \n",
+ " return formated_result.strip()\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "592d8f86-fbf7-4b16-a69d-468030d72dc4",
+ "metadata": {},
+ "source": [
+ "### Prompts"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1914afad-dbd8-4c1f-8e68-80b0e5d743a9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# system prompt\n",
+ "system_prompt = \"\"\"\n",
+ " You are an experienced SEO-focused copywriter. The user will provide an article, and your task is to analyze its content and generate a single, most effective, keyword-optimized title to maximize SEO performance.\n",
+ "\n",
+ "Instructions:\n",
+ "Ignore irrelevant content, such as the current title (if any), navigation menus, advertisements, or unrelated text.\n",
+ "Prioritize SEO best practices, considering:\n",
+ "Keyword relevance and search intent (informational, transactional, etc.).\n",
+ "Readability and engagement.\n",
+ "Avoiding keyword stuffing.\n",
+ "Ensure conciseness and clarity, keeping the title under 60 characters when possible for optimal SERP display.\n",
+ "Use a compelling structure that balances informativeness and engagement, leveraging formats like:\n",
+ "Listicles (\"10 Best Strategies for…\")\n",
+ "How-to guides (\"How to Boost…\")\n",
+ "Questions (\"What Is the Best Way to…\")\n",
+ "Power words to enhance click-through rates (e.g., \"Proven,\" \"Ultimate,\" \"Essential\").\n",
+ "Provide only one single, best title—do not suggest multiple options.\n",
+ "Limit the answer to the following Response Format (Markdown):\n",
+ "Optimized Title: [Provide only one title here]\n",
+ "Justification: [Explain why this title is effective for SEO]\n",
+ "\n",
+ " \"\"\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b0486867-6d38-4cb5-91d4-fb60952c3a9b",
+ "metadata": {},
+ "source": [
+ "**Provide the article URL and get its content for analysis**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "ddd76319-13ce-480b-baa7-cab6a5c88168",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# article url - change to any other article URL\n",
+ "article_url = \"https://searchengineland.com/seo-trends-2025-447745\"\n",
+ "\n",
+ "# get article content\n",
+ "article = WebsiteCrawler(url=article_url)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "176cfac7-5e6d-4d4a-a1c4-1b63b60de1f7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# user prompt\n",
+ "user_prompt = \"\"\"\n",
+ "Following the article to be analyzed to suggest a title. Limit the answer to the following Response Format (Markdown): \n",
+ "Optimized Title: [Provide only one title here]\n",
+ "Justification: [Explain why this title is effective for SEO].\n",
+ "\"\"\"\n",
+ "\n",
+ "user_prompt = f\"{user_prompt} {article}\"\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c45fc7d7-08c9-4e34-b427-b928a219bb94",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# message list\n",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
+ " {\"role\": \"user\", \"content\": user_prompt}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f67b881f-1040-4cf7-82c5-e85f4c0bd252",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# get suggested title\n",
+ "def get_title(model, **kwargs):\n",
+ " # stream if GPT\n",
+ " if 'stream' in kwargs:\n",
+ " response = CLIENTS[model].chat.completions.create(\n",
+ " model=MODELS[model],\n",
+ " messages=messages,\n",
+ " stream=kwargs['stream']\n",
+ " )\n",
+ " else:\n",
+ " response = CLIENTS[model].chat.completions.create(\n",
+ " model=MODELS[model],\n",
+ " messages=messages,\n",
+ " )\n",
+ "\n",
+ " return response\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "8988d6ff-076a-4eae-baf4-26a8d6a2bc44",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# filter response from model verbose - like Deepseek reasoning/thinking verbose\n",
+ "def filter_response(response):\n",
+ " filtered_response = response\n",
+ " # Find last occurrence of 'Optimized Title:' to avoid displaying reasoning verbose\n",
+ " substring = 'Optimized Title:'\n",
+ " start = response.rfind(substring)\n",
+ " if start > -1:\n",
+ " filtered_response = response[start:]\n",
+ "\n",
+ " # Find if the title has quotation (or other) marks and remove it - this should be improved\n",
+ " filtered_response = (\n",
+ " filtered_response.replace('\"', '', 2)\n",
+ " .replace('[', '', 1)\n",
+ " .replace(']', '', 1)\n",
+ " .replace('**', '', 2)\n",
+ " )\n",
+ " \n",
+ " return filtered_response"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0e9e99cf-5e25-4a1f-ab11-a2255e318671",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# display suggested title\n",
+ "def display_title(model):\n",
+ " # get model-suggested title\n",
+ " title = get_title(model)\n",
+ " \n",
+ " display(Markdown(f\"### {model} (___{MODELS[model]}___) Answer\\n\\n_______\")) \n",
+ "\n",
+ " response = \"\"\n",
+ "\n",
+ " if model == 'GPT':\n",
+ " display_handle = display(Markdown(\"\"), display_id=True)\n",
+ " # for chunk in stream:\n",
+ " for chunk in get_title(model=model, stream=True):\n",
+ " response += chunk.choices[0].delta.content or ''\n",
+ " response = (\n",
+ " response.replace(\"```\",\"\")\n",
+ " .replace(\"markdown\", \"\")\n",
+ " .replace(\"Optimized Title:\", \"**Optimized Title:**\")\n",
+ " .replace(\"Justification:\", \"**Justification:**\")\n",
+ " )\n",
+ " update_display(Markdown(response), display_id=display_handle.display_id)\n",
+ " else:\n",
+ " response = get_title(model=model)\n",
+ " response = response.choices[0].message.content\n",
+ " response = filter_response(response)\n",
+ "\n",
+ " # insert line break to preserve format - only LLAMA\n",
+ " line_break = \"
\"\n",
+ " if model == \"DEEPSEEK\":\n",
+ " line_break = \"\"\n",
+ " \n",
+ " response = (\n",
+ " response.replace(\"Optimized Title:\", \"**Optimized Title:**\")\n",
+ " .replace(\"Justification:\", f\"{line_break}**Justification:**\") \n",
+ " )\n",
+ " display(Markdown(response))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "947b42ed-5b43-486d-8af3-e5b671c1fd0e",
+ "metadata": {},
+ "source": [
+ "### Get OpenAI Suggested Title"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "eb6f66e3-ab99-4f76-9358-896cb43c1fa1",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# get and display openAi suggested title\n",
+ "display_title(model='GPT')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "70073ebf-a00a-416b-854d-642d450cd99b",
+ "metadata": {},
+ "source": [
+ "### Get Llama Suggested Title"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "caa190bb-de5f-45cc-b671-5d62688f7b25",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# get and display Llama suggested title\n",
+ "display_title(model='LLAMA')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "811edc4f-20e2-482d-ac89-fae9d1b70bed",
+ "metadata": {},
+ "source": [
+ "### Get Deepseek Suggested Title"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "082628e4-ff4c-46dd-ae5f-76578eb017ad",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# get and display Deepseek title\n",
+ "display_title(model='DEEPSEEK')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f2d401ed-734d-4e96-be30-09b49d516f38",
+ "metadata": {},
+ "source": [
+ "### Using Firecrawl LLM Extract (to replace LLMs above - OpenAI, Llama & Deepseek)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3e6495a2-df0b-4a7b-a376-692456be633d",
+ "metadata": {},
+ "source": [
+ "### Get Firecrawl Suggested Title"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c8763b0a-54ef-409f-8dd6-13231b6f7774",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "fc_title = WebsiteCrawler(url=article_url, format='json')\n",
+ "\n",
+ "display(Markdown(fc_title.getResult()))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7fc404a6-3a91-4c09-89de-867d3d69b4b2",
+ "metadata": {},
+ "source": [
+ "### Observations\n",
+ "\n",
+ "1. **Firecrawl** is a great alternative to replace both Selenium and BeautifulSoup. However, it is not free.\n",
+ "2. **Firecrawl LLM Extract** feature may replace the calls to other LLMs for analysis and title generation. Note that the result provided seems to be cached upon its first generation. Therefore, the suggested title and its justification will always be the same. \n",
+ "3. **Deepseek challenges:**\\\n",
+ " a.It always returns its thinking/reasoning verbose, which, while helpful to understand how it works, is not always\n",
+ " required, such as in this example code. A new function (**filter_response**) was created to remove the additional verbose.\\\n",
+ " b. It is unreliable with the response, sometimes returning the required format for the response instead of the\n",
+ " actual response. For example, for the title, it may sometimes return:\n",
+ " \n",
+ " **Optimized Title:** \\[The user wants the suggested title here]\n",
+ " \n",
+ "### Suggested future improvements\n",
+ "\n",
+ "1. Add the logic that would allow each model to assess the recommendations from the different models and \n",
+ " select the best among these.\n",
+ "2. Add the logic to leverage an API (if available) that automatically assesses the suggested titles."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1af8260b-5ba1-4eeb-acd0-02de537b1bf4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ }
+ ],
+ "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
+}
diff --git a/week2/community-contributions/oob-Week_2-Day_3-Gradio_issue_with_Claude.ipynb b/week2/community-contributions/oob-Week_2-Day_3-Gradio_issue_with_Claude.ipynb
new file mode 100644
index 0000000..f6a8bb9
--- /dev/null
+++ b/week2/community-contributions/oob-Week_2-Day_3-Gradio_issue_with_Claude.ipynb
@@ -0,0 +1,395 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "7df20212-bfa8-4b2b-aec5-7b562dd15ee8",
+ "metadata": {},
+ "source": [
+ "### Issue with Gradio when using Claude for Conversational AI (chatbots)\n",
+ "\n",
+ "As explained in Day 3 (notebook), Gradio has been upgraded to pass in history in a format OpenAI accepts.\n",
+ "\n",
+ "This update simplifies the development work as Gradio manages the history in the background and provides a history structure that matches OpenAi. Fortunately, this works with other models that leverage the client libraries for OpenAI, such as Llama and Gemini. \n",
+ "\n",
+ "However, leveraging Gradio's ChatInterface while using Claude models generates a BadRequest error. \n",
+ "\n",
+ "In analyzing the history list from Gradio, it has the following format:\n",
+ "\n",
+ "`{'role': 'assistant', 'metadata': None, 'content': '[assistant message here]', 'options': None}`\n",
+ "\n",
+ "OpenAi accepts this format without issues, as do other models such as Llama and Gemini - at least while leveraging the client libraries for OpenAI. They accept both formats. \n",
+ "\n",
+ "However, Claude's API requires the following format:\n",
+ "\n",
+ "`{'role': 'user', 'content': '[user message here]'}`\n",
+ "\n",
+ "Claude rejects anything different from this format.\n",
+ "\n",
+ "Run the code below to get the details! "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b5398289-f4d0-4317-b9c2-fff06c4bbfec",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import os\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import google.generativeai\n",
+ "import anthropic\n",
+ "import gradio as gr\n",
+ "from pprint import pprint # for a nicely formatted printout of a list"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "76df1fb5-76f8-4b52-afbb-12b892208b50",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# set environment variables for OpenAi\n",
+ "load_dotenv(override=True)\n",
+ "openai_api_key = os.getenv('OPENAI_API_KEY')\n",
+ "anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
+ "google_api_key = os.getenv('GOOGLE_API_KEY')\n",
+ "\n",
+ "# validate API Key\n",
+ "if not openai_api_key:\n",
+ " raise ValueError(\"No OpenAI API key was found! Please check the .env file.\")\n",
+ "else:\n",
+ " print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n",
+ "\n",
+ "if not anthropic_api_key:\n",
+ " raise ValueError(\"No Anthropic API key was found! Please check the .env file.\")\n",
+ "else:\n",
+ " print(f\"Anthropic API Key exists and begins {anthropic_api_key[:7]}\")\n",
+ "\n",
+ "if not google_api_key:\n",
+ " raise ValueError(\"No Gemini API key was found! Please check the .env file.\")\n",
+ "else:\n",
+ " print(f\"Gemini API Key exists and begins {google_api_key[:8]}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f2429366-a9ab-4e72-a651-56f17b779cf4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# constants\n",
+ "MODELS = { 'GPT': 'gpt-4o-mini', \n",
+ " 'LLAMA': 'llama3.2', \n",
+ " # 'DEEPSEEK': 'deepseek-r1:1.5b',\n",
+ " 'CLAUDE': 'claude-3-haiku-20240307',\n",
+ " 'GEMINI': 'gemini-2.0-flash-exp'\n",
+ " }\n",
+ "\n",
+ "CLIENTS = { 'GPT': OpenAI(), \n",
+ " 'LLAMA': OpenAI(base_url='http://localhost:11434/v1', api_key='ollama'),\n",
+ " # 'DEEPSEEK': OpenAI(base_url='http://localhost:11434/v1', api_key='ollama'),\n",
+ " 'CLAUDE': anthropic.Anthropic(),\n",
+ " 'GEMINI': OpenAI(base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\", api_key=google_api_key)\n",
+ " }\n",
+ "\n",
+ "# system prompt\n",
+ "system_message = \"You are a nice assistant that like to chat with users\"\n",
+ "\n",
+ "# to save/print the history structure\n",
+ "console = []"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bb34616a-2304-4a56-af3a-8d353629722b",
+ "metadata": {},
+ "source": [
+ "#### Testing GPT\n",
+ "\n",
+ "This runs without issues. You may change the model to Llama or Gemini for further testing."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "9e69eb7a-50cf-478c-83f6-4ce923a9c53a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def gpt_chat(message, history):\n",
+ " # change to Llama or Gemini for test\n",
+ " model = 'GPT'\n",
+ "\n",
+ " # add system message to history\n",
+ " if not history:\n",
+ " history.append({\"role\": \"system\", \"content\": system_message})\n",
+ "\n",
+ " # conversation including new user message\n",
+ " messages = history + [{\"role\": \"user\", \"content\": message}]\n",
+ "\n",
+ " # send request to OpenAi\n",
+ " response = CLIENTS[model].chat.completions.create(\n",
+ " model = MODELS[model],\n",
+ " max_tokens = 200,\n",
+ " messages = messages,\n",
+ " )\n",
+ "\n",
+ " # save history structure\n",
+ " global console\n",
+ " console = history[:]\n",
+ " \n",
+ " # post in Gradio's chat interface\n",
+ " return response.choices[0].message.content"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "20444651-440c-4b6d-996d-87a21c28f28e",
+ "metadata": {},
+ "source": [
+ "##### Have a conversation of several messages (3 or more)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "90dac8e6-e1ef-455a-94e9-06735e6c17fb",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Gradio with GPT\n",
+ "gr.ChatInterface(fn=gpt_chat, type=\"messages\", examples=[\"How are you today?\", \"Please, tell me a joke.\"]).launch()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b4048069-b712-491a-96d5-f8fd9f0fe533",
+ "metadata": {},
+ "source": [
+ "##### Notice how the history structure includes both formats, and this is okay with OpenAi"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2f8acbde-f5c3-4890-af5b-69a24ded9b45",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# audit console\n",
+ "pprint(console)\n",
+ "\n",
+ "# empty list\n",
+ "console.clear()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "deaeb8a0-266a-4b5d-8536-e5c59391baa5",
+ "metadata": {},
+ "source": [
+ "#### Testing with Claude\n",
+ "\n",
+ "This first test will generate a BadRequest error on the second message from the user. The first message sent follows the required format preventing errors."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "268e662d-84f5-4b09-8472-c3545a04f2a4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Chat using Gradio's history - generates error after the second message from user\n",
+ "def claude_chat(message, history): # Gradio requires the history parameter, but it goes unused. \n",
+ " \n",
+ " # save history structure\n",
+ " global console\n",
+ " console = history[:]\n",
+ " \n",
+ " model = 'CLAUDE'\n",
+ "\n",
+ " # conversation including new user message - this is why the first message does not generate an error\n",
+ " messages = history + [{\"role\": \"user\", \"content\": message}]\n",
+ "\n",
+ " # send the request to Claude\n",
+ " response = CLIENTS[model].messages.create(\n",
+ " model = MODELS[model],\n",
+ " max_tokens = 200,\n",
+ " system = system_message,\n",
+ " messages = messages,\n",
+ " )\n",
+ " \n",
+ " # post in Gradio's chat interface\n",
+ " return response.content[0].text"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5fd5e221-ab81-4567-a14d-5638d9919a40",
+ "metadata": {},
+ "source": [
+ "##### Have a conversation of several messages (3 or more)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "fbd1a4b2-afcf-4345-bf1a-283c16076e07",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Gradio with Claude\n",
+ "gr.ChatInterface(fn=claude_chat, type=\"messages\", examples=[\"How are you today?\", \"Please, tell me a joke.\"]).launch()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "834bf737-b3d3-4225-be12-f493f3490f16",
+ "metadata": {},
+ "source": [
+ "##### Notice how the history structure changes for the second message. This cause a BadRequest error with Claude."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c6cfa123-83d5-46d8-ac33-74fd9cae0ab3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# audit console\n",
+ "pprint(console)\n",
+ "\n",
+ "# empty list\n",
+ "console.clear()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c0b5c4e0-7544-4279-8006-fde4be9c656f",
+ "metadata": {},
+ "source": [
+ "##### Have a new conversation of several messages (3 or more), but this time leveraging a local history repository instead of Gradio's. \n",
+ "\n",
+ "The code leverages the list `console` as the local repository. Note that Gradio still requires the second parameter (history) is required even though it is not used. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "8c50326e-8496-499a-81d9-28b883ac9b6b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def claude_chat(message, history): # Gradio requires the history parameter, but it goes unused. \n",
+ " # local history repository instead of Gradio's \n",
+ " global console\n",
+ " model = 'CLAUDE'\n",
+ "\n",
+ " # append new user message to history - using Claude's required format\n",
+ " console.append({\"role\": \"user\", \"content\": message})\n",
+ "\n",
+ " # send the request to Claude\n",
+ " response = CLIENTS[model].messages.create(\n",
+ " model = MODELS[model],\n",
+ " max_tokens = 200,\n",
+ " system = system_message,\n",
+ " messages = console, # use local history repository\n",
+ " )\n",
+ "\n",
+ " # append the assistant response to history - using Claude's required format\n",
+ " console.append({\"role\": \"assistant\", \"content\": response.content[0].text})\n",
+ "\n",
+ " # post in Gradio's chat interface\n",
+ " return response.content[0].text"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f19621f5-8dd6-4a88-9a21-9aab04a9dd90",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Gradio with Claude\n",
+ "gr.ChatInterface(fn=claude_chat, type=\"messages\", examples=[\"How are you today?\", \"Please, tell me a joke.\"]).launch()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d6c33236-0d2f-4341-b9ec-e3d7b3eeaec6",
+ "metadata": {},
+ "source": [
+ "##### Notice that the history structure follows the required format."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bd5dd244-abc7-4654-97d2-c140b2a934d2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# audit console\n",
+ "pprint(console)\n",
+ "\n",
+ "# empty list\n",
+ "console.clear()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "48fc0b5f-09de-413f-a809-7bbba5a1ae3e",
+ "metadata": {},
+ "source": [
+ "### Conclusion\n",
+ "\n",
+ "1. OpenAi (and models that leverage the client libraries for OpenAI) supports both formats for the conversation history.\n",
+ "\n",
+ " (Gradio's) `{'role': 'assistant', 'metadata': None, 'content': '[assistant message here]', 'options': None}`\n",
+ "\n",
+ " (Claude's) `{'role': 'user', 'content': '[user message here]'}`\n",
+ " \n",
+ "2. Claude only supports the following format for the conversation history:\n",
+ "\n",
+ " (Claude's) `{'role': 'user', 'content': '[user message here]'}`"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "913b171a-8b3e-43e4-ac38-cedf2c4cdedf",
+ "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
+}