,," /> " />

目 录CONTENT

文章目录

创建文本生成应用

Administrator
2024-05-22 / 0 评论 / 0 点赞 / 10 阅读 / 14685 字

目标

  • 解释什么是文本生成应用程序。

  • 使用 openai 构建文本生成应用程序。

  • 配置应用程序以使用更多或更少的 tokens,并更改 temperature,以获得不同的输出。

什么是文本生成应用

构建应用程序时,它具有某种界面

  • 基于命令。 控制台应用程序是典型的应用程序,您可以在其中键入命令并执行任务。 例如,“git”是一个基于命令的应用程序。

  • 用户界面(UI)。 某些应用程序具有图形用户界面 (GUI),您可以在其中单击按钮、输入文本、选择选项等

传统控制台和UI应用程序的局限性

  • 存在局限性。 您不能输入任意命令,只能键入该应用程序支持的命令。

  • 特定于某种语言。 某些应用程序支持多种语言,但默认情况下,即使可以添加更多语言支持,该应用程序也是针对有限的语言构建的。

文本生成应用程序的优势

文本生成应用程序有何不同呢?

在文本生成应用程序中,您拥有更大的灵活性,不再局限于一组特定的命令或特定的输入语言。 相反,您可以使用自然语言与应用程序交互。 另一个好处是,因为您已经在与经过大量信息库训练的数据源进行交互,而传统应用程序可能仅限于在数据库中存储的有限内容。

使用文本生成应用程序构建什么

比如:

  • 聊天机器人 回答有关您的公司及其产品等主题的问题的聊天机器人可能是一个不错的选择。

  • 协同助手 LLMs 擅长总结文本、从文本中获取见解、生成简历等文本等。

  • 代码助手 根据您使用的编程语言模型,您可以构建一个代码助手来帮助您编写代码。 例如,您可以使用 GitHub Copilot 和 ChatGPT 等产品来帮助您编写代码。

怎么使用LLMs

  • 使用API,将根据提示构建 Web 请求并返回生成的文本。

  • 使用库,库有助于封装 API 调用,使其更易于使用

安装 openai

有许多库可用于与 OpenAI 或 Azure OpenAI 交互。 还可以使用不同的编程语言,如 C#、Python、JavaScript、Java 等。 我们选择使用 openai Python 库,通过 pip 来安装它。

pip install openai

创建资源

需要执行以下步骤:

添加 API key and endpoint

需要告诉“openai”库要使用什么 API key。 要查找 API key ,请转到创建好的 Azure Open AI Service 中的 "Keys and Endpoint"部分并复制 "Key 1" 值。

实战

文字生成

生成文本的方法是使用“Completion”类。 这是一个例子:

prompt = "Complete the following: Once upon a time there was a"

completion = openai.Completion.create(model="davinci-002", prompt=prompt)
print(completion.choices[0].text)

在上面的代码中,我们创建一个 completion 对象并传入我们要使用的模型和提示。 然后我们输出生成的文本。

import openai

openai.api_key = "sk-..."

completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}])
print(completion.choices[0].message.content)

下一章将详细介绍此功能。

文本生成应用

import openai

openai.api_key = "您的 openai key 或 Azure OpenAI key"

openai.api_type = 'azure'
openai.api_version = '2023-05-15'
openai.api_base = "您的 Azure OpenAI Endpoint"
deployment_name = "部署模型的名字"

# add your completion code
prompt = "Complete the following: Once upon a time there was a"

# make completion
completion = openai.Completion.create(engine= deployment_name, model="davinci-002", prompt=prompt)

# print response
print(completion.choices[0].text)

不同类型的提示,针对不同的事情

提示可用于各种任务。 例如:

  • 生成一种类型的文本。 例如,生成一首诗、测验题目等。

  • 查找信息。 您可以使用提示来查找信息,例如以下示例'What does CORS mean in web development?'。

  • 生成代码

示例:打造菜谱生成器

  1. 使用现有的 app.py 文件作为起点

  2. 找到 prompt 变量并将其代码更改为以下内容:

    prompt = "Show me 5 recipes for a dish with the following ingredients: chicken, potatoes, and carrots. Per recipe, list all the ingredients used"

    运行代码,您应该会看到类似以下内容的输出:

    -Chicken Stew with Potatoes and Carrots: 3 tablespoons oil, 1 onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 1/2 cups chicken broth, 1/2 cup dry white wine, 2 tablespoons chopped fresh parsley, 2 tablespoons unsalted butter, 1 1/2 pounds boneless, skinless chicken thighs, cut into 1-inch pieces
    -Oven-Roasted Chicken with Potatoes and Carrots: 3 tablespoons extra-virgin olive oil, 1 tablespoon Dijon mustard, 1 tablespoon chopped fresh rosemary, 1 tablespoon chopped fresh thyme, 4 cloves garlic, minced, 1 1/2 pounds small red potatoes, quartered, 1 1/2 pounds carrots, quartered lengthwise, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 (4-pound) whole chicken
    -Chicken, Potato, and Carrot Casserole: cooking spray, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and shredded, 1 potato, peeled and shredded, 1/2 teaspoon dried thyme leaves, 1/4 teaspoon salt, 1/4 teaspoon black pepper, 2 cups fat-free, low-sodium chicken broth, 1 cup frozen peas, 1/4 cup all-purpose flour, 1 cup 2% reduced-fat milk, 1/4 cup grated Parmesan cheese
    
    -One Pot Chicken and Potato Dinner: 2 tablespoons olive oil, 1 pound boneless, skinless chicken thighs, cut into 1-inch pieces, 1 large onion, chopped, 3 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 2 cups chicken broth, 1/2 cup dry white wine
    
    -Chicken, Potato, and Carrot Curry: 1 tablespoon vegetable oil, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 teaspoon ground coriander, 1 teaspoon ground cumin, 1/2 teaspoon ground turmeric, 1/2 teaspoon ground ginger, 1/4 teaspoon cayenne pepper, 2 cups chicken broth, 1/2 cup dry white wine, 1 (15-ounce) can chickpeas, drained and rinsed, 1/2 cup raisins, 1/2 cup chopped fresh cilantro

    NOTE, your LLM is nondeterministic, so you might get different results every time you run the program.

  3. 优化并更改代码

no_recipes = input("No of recipes (for example, 5: ")

ingredients = input("List of ingredients (for example, chicken, potatoes, and carrots: ")

# interpolate the number of recipes into the prompt an ingredients
prompt = f"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used"
Taking the code for a test run, could look like this:

No of recipes (for example, 5: 3
List of ingredients (for example, chicken, potatoes, and carrots: milk,strawberries

-Strawberry milk shake: milk, strawberries, sugar, vanilla extract, ice cubes
-Strawberry shortcake: milk, flour, baking powder, sugar, salt, unsalted butter, strawberries, whipped cream
-Strawberry milk: milk, strawberries, sugar, vanilla extract

针对清单增加过滤器

过滤掉成分。 我们希望能够过滤掉我们不喜欢或过敏的成分。 要完成此更改,我们可以编辑现有提示并在其末尾添加过滤条件,如下所示:

filter = input("Filter (for example, vegetarian, vegan, or gluten-free: ")

prompt = f"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used, no {filter}"

上面代码中,我们在提示语末尾添加了 {filter},并让用户输入过滤值。

现在运行程序的输入示例如下

No of recipes (for example, 5: 3
List of ingredients (for example, chicken, potatoes, and carrots: onion,milk
Filter (for example, vegetarian, vegan, or gluten-free: no milk

1. French Onion Soup

Ingredients:

-1 large onion, sliced
-3 cups beef broth
-1 cup milk
-6 slices french bread
-1/4 cup shredded Parmesan cheese
-1 tablespoon butter
-1 teaspoon dried thyme
-1/4 teaspoon salt
-1/4 teaspoon black pepper

Instructions:

2. In a large pot, sauté onions in butter until golden brown.
3. Add beef broth, milk, thyme, salt, and pepper. Bring to a boil.
4. Reduce heat and simmer for 10 minutes.
5. Place french bread slices on soup bowls.
6. Ladle soup over bread.
7. Sprinkle with Parmesan cheese.

8. Onion and Potato Soup

Ingredients:

-1 large onion, chopped
-2 cups potatoes, diced
-3 cups vegetable broth
-1 cup milk
-1/4 teaspoon black pepper

Instructions:

9. In a large pot, sauté onions in butter until golden brown.
10. Add potatoes, vegetable broth, milk, and pepper. Bring to a boil.
11. Reduce heat and simmer for 10 minutes.
12. Serve hot.

13. Creamy Onion Soup

Ingredients:

-1 large onion, chopped
-3 cups vegetable broth
-1 cup milk
-1/4 teaspoon black pepper
-1/4 cup all-purpose flour
-1/2 cup shredded Parmesan cheese

Instructions:

14. In a large pot, sauté onions in butter until golden brown.
15. Add vegetable broth, milk, and pepper. Bring to a boil.
16. Reduce heat and simmer for 10 minutes.
17. In a small bowl, whisk together flour and Parmesan cheese until smooth.
18. Add to soup and simmer for an additional 5 minutes, or until soup has thickened.

减少token和代码安全

安全性

将 Key 与代码分开,例如 API Key。Key 不属于代码,应存储在安全的位置。 为了将 Key 与代码分开,我们可以使用环境变量和像python-dotenv 这样的库去从文件中加载它们。 代码如下:

创建一个包含以下内容的 .env 文件:

OPENAI_API_KEY=sk-...

token数量

我们应该考虑需要多少 token 来生成我们想要的文本。 token 需要花钱,因此在可能的情况下,我们应该尽量节约使用 token 的数量。 例如,我们可以对提示进行调整,以便我们可以使用更少的 token

要更改使用的 token,您可以使用 max_tokens 参数。 例如,如果您想使用 100 个 token,您可以这样做:

completion = openai.Completion.create(model="davinci-002", prompt=prompt, max_tokens=100)

结果随机性

temperature 是我们到目前为止还没有提到的东西,但它是我们的程序如何执行的重要元素。 temperature 值越高,输出就越随机。 相反, temperature 值越低,输出就越可预测。 考虑一下您是否希望输出有所变化。

要改变 temperature ,您可以使用 `temperature` 参数。 例如,如果您想使用 0.5 的 temperature ,您可以这样做:

```python
completion = openai.Completion.create(model="davinci-002", prompt=prompt, temperature=0.5)
```

作业

https://microsoft.github.io/generative-ai-for-beginners/#/06-text-generation-apps/translations/cn/README?wt.mc_id=academic-105485-koreyst

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区