{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "# 第7章：构建聊天应用\n",
    "## Azure OpenAI API 快速入门\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "## 概述\n",
    "本笔记本改编自包含同时访问 [OpenAI](notebook-openai.ipynb) 服务的笔记本的 [Azure OpenAI 示例仓库](https://github.com/Azure/azure-openai-samples?WT.mc_id=academic-105485-koreyst)。\n",
    "\n",
    "Python OpenAI API 也适用于 Azure OpenAI，需做一些小修改。了解更多差异，请参阅：[如何使用 Python 在 OpenAI 和 Azure OpenAI 端点之间切换](https://learn.microsoft.com/azure/ai-services/openai/how-to/switching-endpoints?WT.mc_id=academic-109527-jasmineg)\n",
    "\n",
    "欲获取更多快速入门示例，请参考官方 [Azure OpenAI 快速入门文档](https://learn.microsoft.com/azure/cognitive-services/openai/quickstart?pivots=programming-language-studio&WT.mc_id=academic-105485-koreyst)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "## 目录  \n",
    "\n",
    "[概述](#overview)  \n",
    "[开始使用 Azure OpenAI 服务](#getting-started-with-azure-openai-service)  \n",
    "[构建你的第一个提示](#build-your-first-prompt)  \n",
    "\n",
    "[用例](#use-cases)    \n",
    "[1. 文本摘要](#summarize-text)  \n",
    "[2. 文本分类](#classify-text)  \n",
    "[3. 生成新产品名称](#generate-new-product-names)  \n",
    "[4. 微调分类器](#fine-tune-a-classifier)  \n",
    "[5. 嵌入](#embeddings)\n",
    "\n",
    "[参考资料](#references)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "### Azure OpenAI 服务入门\n",
    "\n",
    "新客户需要[申请访问权限](https://aka.ms/oai/access?WT.mc_id=academic-105485-koreyst)Azure OpenAI 服务。  \n",
    "审批完成后，客户可以登录 Azure 门户，创建 Azure OpenAI 服务资源，并通过工作室开始试验模型  \n",
    "\n",
    "[快速入门的绝佳资源](https://techcommunity.microsoft.com/blog/educatordeveloperblog/azure-openai-service-is-now-generally-available/3719177?WT.mc_id=academic-105485-koreyst)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "### 构建您的第一个提示  \n",
    "这个简短的练习将为向 OpenAI 模型提交提示以完成一个简单任务“摘要”提供基本介绍。\n",
    "\n",
    "\n",
    "<strong>步骤</strong>:  \n",
    "1. 在您的 Python 环境中安装 OpenAI 库  \n",
    "2. 加载标准辅助库并设置您为所创建的 OpenAI 服务的典型 OpenAI 安全凭据  \n",
    "3. 为您的任务选择一个模型  \n",
    "4. 为模型创建一个简单的提示  \n",
    "5. 向模型 API 提交您的请求！\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "### 1. 安装 OpenAI\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "  > [!NOTE] 如果在 Codespaces 或 Devcontainer 内运行此笔记本，则此步骤不是必需的\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674254990318
    },
    "jupyter": {
     "outputs_hidden": true,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "%pip install openai python-dotenv"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "### 2. 导入辅助库并实例化凭据\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674829434433
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from openai import OpenAI\n",
    "import numpy as np\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv()\n",
    "\n",
    "#validate data inside .env file\n",
    "\n",
    "# The Responses API is served from the Azure OpenAI (Microsoft Foundry) v1 endpoint,\n",
    "# so we point the OpenAI client at <your-endpoint>/openai/v1/ (no api_version needed).\n",
    "endpoint = os.environ['AZURE_OPENAI_ENDPOINT']\n",
    "client = OpenAI(\n",
    "  api_key=os.environ['AZURE_OPENAI_API_KEY'],\n",
    "  base_url=f\"{endpoint.rstrip('/')}/openai/v1/\",\n",
    "  )\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "### 3. 寻找合适的模型  \n",
    "像 GPT-4o 和 GPT-4o mini 这样的模型能够理解和生成自然语言。Microsoft Foundry 中的 Azure OpenAI 提供了一系列模型能力，每种模型在不同的任务中具有不同的性能和速度水平。 \n",
    "\n",
    "[Microsoft Foundry 的 Azure OpenAI 模型](https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure?WT.mc_id=academic-105485-koreyst)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674742720788
    },
    "jupyter": {
     "outputs_hidden": true,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "# Select the deployment name configured in your .env file\n",
    "model = os.environ['AZURE_OPENAI_DEPLOYMENT']\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "## 4. 提示设计  \n",
    "\n",
    "“大型语言模型的魔力在于，通过在大量文本上训练以最小化预测误差，模型最终学会了对这些预测有用的概念。例如，它们学会了像”(1):\n",
    "\n",
    "* 如何拼写\n",
    "* 语法如何运作\n",
    "* 如何改写\n",
    "* 如何回答问题\n",
    "* 如何进行对话\n",
    "* 如何用多种语言写作\n",
    "* 如何编程\n",
    "* 等等。\n",
    "\n",
    "#### 如何控制大型语言模型  \n",
    "“在所有输入给大型语言模型的内容中，最有影响力的远远是文本提示(1)。\n",
    "\n",
    "大型语言模型可以通过几种方式被提示生成输出：\n",
    "\n",
    "- 指令：告诉模型你想要什么\n",
    "- 填写：引导模型完成你想要的开头部分\n",
    "- 演示：通过以下方式向模型展示你想要的内容：\n",
    "- 提示中包含几个示例\n",
    "- 在微调训练数据集中包含数百或数千个示例\n",
    "\n",
    "\n",
    "\n",
    "#### 创建提示的三条基本指导原则：\n",
    "\n",
    "<strong>展示与说明</strong>。通过指令、示例或两者结合，明确告诉模型你想要什么。如果你想让模型将一列项目按字母顺序排列，或者按情感对一段话分类，就给它展示这是你想要的。\n",
    "\n",
    "<strong>提供高质量数据</strong>。如果你想构建一个分类器或让模型遵循某种模式，确保有足够的示例。务必校对你的示例——模型通常足够聪明能够识别基础拼写错误并给出回应，但它也可能认为这是故意的，这会影响回复结果。\n",
    "\n",
    "**检查你的设置。** temperature 和 top_p 设置控制模型生成响应时的确定性。如果你要求模型给出的回答只有唯一正确答案，那么你应将这些参数设置较低。如果你希望获得更多样化的回答，可以设置得更高。人们对这些设置最大的误解是认为它们是“聪明度”或“创造力”的控制开关。\n",
    "\n",
    "\n",
    "来源：https://learn.microsoft.com/azure/ai-services/openai/overview\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "image 正在创建你的第一个文本提示！\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "### 5. 提交！\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674494935186
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "# Create your first prompt\n",
    "text_prompt = \"Should oxford commas always be used?\"\n",
    "\n",
    "response = client.responses.create(\n",
    "  model=model,\n",
    "  input = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
    "               {\"role\":\"user\",\"content\":text_prompt},],\n",
    "  store=False,)\n",
    "\n",
    "response.output_text\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "### 重复相同的调用，结果如何比较？ \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674494940872
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "\n",
    "response = client.responses.create(\n",
    "  model=model,\n",
    "  input = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
    "               {\"role\":\"user\",\"content\":text_prompt},],\n",
    "  store=False,)\n",
    "\n",
    "response.output_text\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "## 总结文本  \n",
    "#### 挑战  \n",
    "通过在文本段落末尾添加“tl;dr:”来总结文本。注意模型如何在没有额外指令的情况下理解执行多项任务。你可以尝试比tl;dr更具描述性的提示，以修改模型的行为并自定义你获得的摘要(3)。  \n",
    "\n",
    "近期的工作表明，通过在大规模文本语料库上进行预训练，然后在特定任务上进行微调，在许多NLP任务和基准测试上获得了显著提升。虽然这种方法在架构上通常与任务无关，但仍需要成千上万的任务特定微调数据集。相比之下，人类通常只需少量示例或简单指令即可执行新的语言任务——这是现有NLP系统仍然很难做到的。这里我们展示了扩大语言模型规模显著提升了任务无关的少样本性能，有时甚至可以达到与此前最先进微调方法竞争的水平。  \n",
    "\n",
    "\n",
    "\n",
    "摘要  \n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "# 多种使用场景的练习  \n",
    "1. 概括文本  \n",
    "2. 分类文本  \n",
    "3. 生成新产品名称\n",
    "4. 嵌入\n",
    "5. 微调分类器\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674495198534
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "prompt = \"Recent work has demonstrated substantial gains on many NLP tasks and benchmarks by pre-training on a large corpus of text followed by fine-tuning on a specific task. While typically task-agnostic in architecture, this method still requires task-specific fine-tuning datasets of thousands or tens of thousands of examples. By contrast, humans can generally perform a new language task from only a few examples or from simple instructions - something that current NLP systems still largely struggle to do. Here we show that scaling up language models greatly improves task-agnostic, few-shot performance, sometimes even reaching competitiveness with prior state-of-the-art fine-tuning approaches.\\n\\ntl;dr\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674495201868
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "#Setting a few additional, typical parameters during API Call\n",
    "\n",
    "response = client.responses.create(\n",
    "  model=model,\n",
    "  input = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
    "               {\"role\":\"user\",\"content\":prompt},],\n",
    "  store=False,)\n",
    "\n",
    "response.output_text\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "## 文本分类  \n",
    "#### 挑战  \n",
    "在推理时将项目分类到提供的类别中。以下示例中，我们在提示中同时提供了类别和要分类的文本(*playground_reference)。 \n",
    "\n",
    "客户咨询：您好，我笔记本键盘上的一个键最近坏了，需要更换：\n",
    "\n",
    "分类类别：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674499424645
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "prompt = \"Classify the following inquiry into one of the following: categories: [Pricing, Hardware Support, Software Support]\\n\\ninquiry: Hello, one of the keys on my laptop keyboard broke recently and I'll need a replacement:\\n\\nClassified category:\"\n",
    "print(prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674499378518
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "#Setting a few additional, typical parameters during API Call\n",
    "\n",
    "response = client.responses.create(\n",
    "  model=model,\n",
    "  input = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
    "               {\"role\":\"user\",\"content\":prompt},],\n",
    "  store=False,)\n",
    "\n",
    "response.output_text\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "## 生成新产品名称\n",
    "#### 挑战\n",
    "从示例词中创建产品名称。这里我们在提示中包含我们将要为其生成名称的产品信息。我们还提供了一个类似的示例来展示我们希望收到的模式。我们还将温度值设置得较高，以增加随机性和更具创新性的响应。\n",
    "\n",
    "产品描述：家用奶昔机\n",
    "种子词：快速，健康，紧凑。\n",
    "产品名称：HomeShaker，Fit Shaker，QuickShake，Shake Maker\n",
    "\n",
    "产品描述：一双适合任何脚尺寸的鞋子。\n",
    "种子词：适应性，合脚，全尺寸适配。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674257087279
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "prompt = \"Product description: A home milkshake maker\\nSeed words: fast, healthy, compact.\\nProduct names: HomeShaker, Fit Shaker, QuickShake, Shake Maker\\n\\nProduct description: A pair of shoes that can fit any foot size.\\nSeed words: adaptable, fit, omni-fit.\"\n",
    "\n",
    "print(prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "#Setting a few additional, typical parameters during API Call\n",
    "\n",
    "response = client.responses.create(\n",
    "  model=model,\n",
    "  input = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
    "               {\"role\":\"user\",\"content\":prompt}],\n",
    "  store=False,)\n",
    "\n",
    "response.output_text\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "## 嵌入\n",
    "本节将展示如何检索嵌入，以及如何查找单词、句子和文档之间的相似性。为了运行以下笔记本，您需要部署一个使用 `text-embedding-ada-002` 作为基础模型的模型，并在 .env 文件中使用 `AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT` 变量设置其部署名称。\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "### 模型分类 - 选择嵌入模型\n",
    "\n",
    "<strong>模型分类</strong>: {family} - {capability} - {input-type} - {identifier}  \n",
    "\n",
    "{family}     --> text-embedding  (嵌入模型家族)  \n",
    "{capability} --> ada             (所有其他嵌入模型将在2024年退役)  \n",
    "{input-type} --> n/a             (仅对搜索模型指定)  \n",
    "{identifier} --> 002             (版本002)  \n",
    "\n",
    "model = 'text-embedding-ada-002'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "  > [!NOTE] 如果在 Codespaces 或 Devcontainer 中运行此笔记本，则以下步骤不是必需的\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dependencies for embeddings_utils\n",
    "%pip install matplotlib plotly scikit-learn pandas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674829364153
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "def cosine_similarity(a, b):\n",
    "    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674829424097
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "text = 'the quick brown fox jumped over the lazy dog'\n",
    "model= os.environ['AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT']\n",
    "client.embeddings.create(input='[text]', model=model).data[0].embedding"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674829555255
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "\n",
    "# compare several words\n",
    "automobile_embedding  = client.embeddings.create(input='automobile', model=model).data[0].embedding\n",
    "vehicle_embedding     = client.embeddings.create(input='vehicle', model=model).data[0].embedding\n",
    "dinosaur_embedding    = client.embeddings.create(input='dinosaur', model=model).data[0].embedding\n",
    "stick_embedding       = client.embeddings.create(input='stick', model=model).data[0].embedding\n",
    "\n",
    "print(cosine_similarity(automobile_embedding, vehicle_embedding))\n",
    "print(cosine_similarity(automobile_embedding, dinosaur_embedding))\n",
    "print(cosine_similarity(automobile_embedding, stick_embedding))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "## 来自cnn每日新闻数据集的比较文章\n",
    "来源：https://huggingface.co/datasets/cnn_dailymail\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674831122093
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "cnn_daily_articles = ['BREMEN, Germany -- Carlos Alberto, who scored in FC Porto\\'s Champions League final victory against Monaco in 2004, has joined Bundesliga club Werder Bremen for a club record fee of 7.8 million euros ($10.7 million). Carlos Alberto enjoyed success at FC Porto under Jose Mourinho. \"I\\'m here to win titles with Werder,\" the 22-year-old said after his first training session with his new club. \"I like Bremen and would only have wanted to come here.\" Carlos Alberto started his career with Fluminense, and helped them to lift the Campeonato Carioca in 2002. In January 2004 he moved on to FC Porto, who were coached by José Mourinho, and the club won the Portuguese title as well as the Champions League. Early in 2005, he moved to Corinthians, where he impressed as they won the Brasileirão,but in 2006 Corinthians had a poor season and Carlos Alberto found himself at odds with manager, Emerson Leão. Their poor relationship came to a climax at a Copa Sul-Americana game against Club Atlético Lanús, and Carlos Alberto declared that he would not play for Corinthians again while Leão remained as manager. Since January this year he has been on loan with his first club Fluminense. Bundesliga champions VfB Stuttgart said on Sunday that they would sign a loan agreement with Real Zaragoza on Monday for Ewerthon, the third top Brazilian player to join the German league in three days. A VfB spokesman said Ewerthon, who played in the Bundesliga for Borussia Dortmund from 2001 to 2005, was expected to join the club for their pre-season training in Austria on Monday. On Friday, Ailton returned to Germany where he was the league\\'s top scorer in 2004, signing a one-year deal with Duisburg on a transfer from Red Star Belgrade. E-mail to a friend .',\n",
    "                        '(CNN) -- Football superstar, celebrity, fashion icon, multimillion-dollar heartthrob. Now, David Beckham is headed for the Hollywood Hills as he takes his game to U.S. Major League Soccer. CNN looks at how Bekham fulfilled his dream of playing for Manchester United, and his time playing for England. The world\\'s famous footballer has begun a five-year contract with the Los Angeles Galaxy team, and on Friday Beckham will meet the press and reveal his new shirt number. This week, we take an in depth look at the life and times of Beckham, as CNN\\'s very own \"Becks,\" Becky Anderson, sets out to examine what makes the man tick -- as footballer, fashion icon and global phenomenon. It\\'s a long way from the streets of east London to the Hollywood Hills and Becky charts Beckham\\'s incredible rise to football stardom, a journey that has seen his skills grace the greatest stages in world soccer. She goes in pursuit of the current hottest property on the sports/celebrity circuit in the U.S. and along the way explores exactly what\\'s behind the man with the golden boot. CNN will look back at the life of Beckham, the wonderfully talented youngster who fulfilled his dream of playing for Manchester United, his marriage to pop star Victoria, and the trials and tribulations of playing for England. We\\'ll look at the highs (scoring against Greece), the lows (being sent off during the World Cup), the Man. U departure for the Galacticos of Madrid -- and now the Home Depot stadium in L.A. We\\'ll ask how Beckham and his family will adapt to life in Los Angeles -- the people, the places to see and be seen and the celebrity endorsement. Beckham is no stranger to exposure. He has teamed with Reggie Bush in an Adidas commercial, is the face of Motorola, is the face on a PlayStation game and doesn\\'t need fashion tips as he has his own international clothing line. But what does the star couple need to do to become an accepted part of Tinseltown\\'s glitterati? The road to major league football in the U.S.A. is a well-worn route for some of the world\\'s greatest players. We talk to some of the former greats who came before him and examine what impact these overseas stars had on U.S. soccer and look at what is different now. We also get a rare glimpse inside the David Beckham academy in L.A, find out what drives the kids and who are their heroes. The perception that in the U.S.A. soccer is a \"game for girls\" after the teenage years is changing. More and more young kids are choosing the European game over the traditional U.S. sports. E-mail to a friend .',\n",
    "                        'LOS ANGELES, California (CNN) -- Youssif, the 5-year-old burned Iraqi boy, rounded the corner at Universal Studios when suddenly the little boy hero met his favorite superhero. Youssif has always been a huge Spider-Man fan. Meeting him was \"my favorite thing,\" he said. Spider-Man was right smack dab in front of him, riding a four-wheeler amid a convoy of other superheroes. The legendary climber of buildings and fighter of evil dismounted, walked over to Youssif and introduced himself. Spidey then gave the boy from a far-away land a gentle hug, embracing him in his iconic blue and red tights. He showed Youssif a few tricks, like how to shoot a web from his wrist. Only this time, no web was spun. \"All right Youssif!\" Spider-Man said after the boy mimicked his wrist movement. Other superheroes crowded around to get a closer look. Even the Green Goblin stopped his villainous ways to tell the boy hi. Youssif remained unfazed. He didn\\'t take a liking to Spider-Man\\'s nemesis. Spidey was just too cool. \"It was my favorite thing,\" the boy said later. \"I want to see him again.\" He then felt compelled to add: \"I know it\\'s not the real Spider-Man.\" This was the day of dreams when the boy\\'s nightmares were, at least temporarily, forgotten. He met SpongeBob, Lassie and a 3-year-old orangutan named Archie. The hairy, brownish-red primate took to the boy, grabbing his hand and holding it. Even when Youssif pulled away, Archie would inch his hand back toward the boy\\'s and then snatch it. See Youssif enjoy being a boy again » . The boy giggled inside a play area where sponge-like balls shot out of toy guns. It was a far different artillery than what he was used to seeing in central Baghdad, as recently as a week ago. He squealed with delight and raced around the room collecting as many balls as he could. He rode a tram through the back stages at Universal Studios. At one point, the car shook. Fire and smoke filled the air, debris cascaded down and a big rig skidded toward the vehicle. The boy and his family survived the pretend earthquake unscathed. \"Even I was scared,\" the dad said. \"Well, I wasn\\'t,\" Youssif replied. The father and mother grinned from ear to ear throughout the day. Youssif pushed his 14-month-old sister, Ayaa, in a stroller. \"Did you even need to ask us if we were interested in coming here?\" Youssif\\'s father said in amazement. \"Other than my wedding day, this is the happiest day of my life,\" he said. Just a day earlier, the mother and father talked about their journey out of Iraq and to the United States. They also discussed that day nine months ago when masked men grabbed their son outside the family home, doused him in gas and set him on fire. His mother heard her boy screaming from inside. The father sought help for his boy across Baghdad, but no one listened. He remembers his son\\'s two months of hospitalization. The doctors didn\\'t use anesthetics. He could hear his boy\\'s piercing screams from the other side of the hospital. Watch Youssif meet his doctor and play with his little sister » . The father knew that speaking to CNN would put his family\\'s lives in jeopardy. The possibility of being killed was better than seeing his son suffer, he said. \"Anything for Youssif,\" he said. \"We had to do it.\" They described a life of utter chaos in Baghdad. Neighbors had recently given birth to a baby girl. Shortly afterward, the father was kidnapped and killed. Then, there was the time when some girls wore tanktops and jeans. They were snatched off the street by gunmen. The stories can be even more gruesome. The couple said they had heard reports that a young girl was kidnapped and beheaded --and her killers sewed a dog\\'s head on the corpse and delivered it to her family\\'s doorstep. \"These are just some of the stories,\" said Youssif\\'s mother, Zainab. Under Saddam Hussein, there was more security and stability, they said. There was running water and electricity most of the time. But still life was tough under the dictator, like the time when Zainab\\'s uncle disappeared and was never heard from again after he read a \"religious book,\" she said. Sitting in the parking lot of a Target in suburban Los Angeles, Youssif\\'s father watched as husbands and wives, boyfriends and girlfriends, parents and their children, came and went. Some held hands. Others smiled and laughed. \"Iraq finished,\" he said in what few English words he knows. He elaborated in Arabic: His homeland won\\'t be enjoying such freedoms anytime soon. It\\'s just not possible. Too much violence. Too many killings. His two children have only seen war. But this week, the family has seen a much different side of America -- an outpouring of generosity and a peaceful nation at home. \"It\\'s been a dream,\" the father said. He used to do a lot of volunteer work back in Baghdad. \"Maybe that\\'s why I\\'m being helped now,\" the father said. At Universal Studios, he looked out across the valley below. The sun glistened off treetops and buildings. It was a picturesque sight fit for a Hollywood movie. \"Good America, good America,\" he said in English. E-mail to a friend . CNN\\'s Arwa Damon contributed to this report.'\n",
    "]\n",
    "\n",
    "cnn_daily_article_highlights = ['Werder Bremen pay a club record $10.7 million for Carlos Alberto .\\nThe Brazilian midfielder won the Champions League with FC Porto in 2004 .\\nSince January he has been on loan with his first club, Fluminense .',\n",
    "                                'Beckham has agreed to a five-year contract with Los Angeles Galaxy .\\nNew contract took effect July 1, 2007 .\\nFormer English captain to meet press, unveil new shirt number Friday .\\nCNN to look at Beckham as footballer, fashion icon and global phenomenon .',\n",
    "                                'Boy on meeting Spider-Man: \"It was my favorite thing\"\\nYoussif also met SpongeBob, Lassie and an orangutan at Universal Studios .\\nDad: \"Other than my wedding day, this is the happiest day of my life\"'\n",
    "]\n",
    "\n",
    "cnn_df = pd.DataFrame({\"articles\":cnn_daily_articles, \"highligths\":cnn_daily_article_highlights})\n",
    "\n",
    "cnn_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "gather": {
     "logged": 1674831294043
    },
    "jupyter": {
     "outputs_hidden": false,
     "source_hidden": false
    },
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "outputs": [],
   "source": [
    "article1_embedding    = client.embeddings.create(input=cnn_df.articles.iloc[0], model=model).data[0].embedding\n",
    "article2_embedding    = client.embeddings.create(input=cnn_df.articles.iloc[1], model=model).data[0].embedding\n",
    "article3_embedding    = client.embeddings.create(input=cnn_df.articles.iloc[2], model=model).data[0].embedding\n",
    "\n",
    "print(cosine_similarity(article1_embedding, article2_embedding))\n",
    "print(cosine_similarity(article1_embedding, article3_embedding))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "# 参考资料  \n",
    "- [Microsoft Foundry - Azure OpenAI 模型](https://learn.microsoft.com/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure?WT.mc_id=academic-105485-koreyst)  \n",
    "- [Microsoft Foundry 门户](https://ai.azure.com?WT.mc_id=academic-105485-koreyst)  \n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "# 获取更多帮助  \n",
    "[OpenAI 商业化团队](AzureOpenAITeam@microsoft.com)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "nteract": {
     "transient": {
      "deleting": false
     }
    }
   },
   "source": [
    "# 贡献者\n",
    "* Louis Li  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n\n<!-- CO-OP TRANSLATOR DISCLAIMER START -->\n**免责声明**：\n本文件由 AI 翻译服务 [Co-op Translator](https://github.com/Azure/co-op-translator) 翻译完成。尽管我们力求准确，但请注意，自动翻译可能包含错误或不准确之处。原始语言版文件应视为权威来源。对于重要信息，建议使用专业人工翻译。我们对因使用本翻译而产生的任何误解或误释不承担责任。\n<!-- CO-OP TRANSLATOR DISCLAIMER END -->\n"
   ]
  }
 ],
 "metadata": {
  "kernel_info": {
   "name": "python310-sdkv2"
  },
  "kernelspec": {
   "display_name": "base",
   "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.10.13"
  },
  "microsoft": {
   "host": {
    "AzureML": {
     "notebookHasBeenCompleted": true
    }
   }
  },
  "nteract": {
   "version": "nteract-front-end@1.0.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}