如何使用ChatGPT在PYTHON中编码产品推荐引擎?

351 阅读6分钟

Cover image for How to code a product recommendation engine in PYTHON using ChatGPT?

在当今竞争激烈的电子商务领域,个性化的产品推荐对企业吸引和保留客户至关重要。机器学习算法可以通过分析客户数据并根据他们的喜好和行为提供建议来帮助实现这一目标。在这篇文章中,我将探讨如何使用Python和ChatGPT语言模型编码一个产品推荐系统。我们将利用它的功能来创建一个推荐系统,该系统可以根据客户以前的购买和浏览历史向他们推荐产品。

视频解释我们要编码的内容

虽然视频演示了ChatGPT在Tcardi平台上的执行,但我们不会复制这个过程。相反,我们将研究该插件的编码,以学习所采用的方法,我们可以将其应用于我们自己的项目。

如果你有兴趣在你的项目中使用Tcardi或者为它的发展做出贡献,你可以在GitHub上访问它的存储库。Tracardi是一个开源项目,允许开发人员创建高度可定制的自动化工作流程和客户旅程图。

我鼓励你至少给他们一颗github星,分享如何在产品推荐中使用ChatGPT。

开始使用

要开始使用ChatGPT API,你需要在OpenAI创建一个账户并获得一个API密钥。API密钥将使您能够访问GPT-4语言模型,然后您可以在各种情况下使用它来生成文本。

有多种定价模式可供选择,每种模式都有不同的功能和价位。定价是基于你使用的代币数量,1,000个代币大约相当于750个单词。

你不需要担心ChatGPT的价格,因为对于程序员来说,定价是相当合理的,我个人使用了一段时间,没有支付超过一美元。

库的安装

OpenAI的API可以通过HTTP请求从任何编程语言中使用官方的Python绑定来访问。要安装官方的Python绑定,使用命令:

pip install openai

进入全屏模式 退出全屏模式

正如我提到的,API使用API密钥进行认证,可以从API密钥页面获得。记住要保证你的API密钥的安全,不要把它暴露在任何客户端的代码中。

所有的API请求都应该在授权HTTP头中包含你的API密钥,如下所示:

Authorization: Bearer OPENAI_API_KEY

进入全屏模式 退出全屏模式

请求组织

对于属于多个组织的用户,你可以通过一个头来指定API请求使用哪个组织。这些API请求的用量将计入指定组织的订阅配额。

curl命令示例:

curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Organization: YOUR_ORG_ID"

进入全屏模式 退出全屏模式

使用openai Python包的例子:

import os
import openai
openai.organization = "YOUR_ORG_ID"
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Model.list()

进入全屏模式 退出全屏模式

提出请求

要提出你的第一个API请求,只需将下面的命令复制并粘贴到你的终端。请确保将"$OPENAI_API_KEY "替换为你自己的秘密API密钥。

Tracardi利用asyncio的异步API调用,所以它不使用openai库。因此,我将采用同样的方法,使用原始的REST API调用而不是库。这种方法将使代码更加有效和灵活。

为了进行API调用,你可以使用任何你熟悉的现有库。为了简单起见,我将使用request库。

我们将使用"https://api.openai.com/v1/completions "POST端点。

该插件向该API发送以下有效载荷,其中prompt是实际提示:

prompt_length = len(prompt.split())
max_tokens = 1024 - prompt_length

payload = {
    "model": "text-davinci-003",
    "prompt": prompt,
    "max_tokens": max_tokens,
    "temperature": 0.5,
    "top_p": 1,
    "n": 1
}

进入全屏模式 退出全屏模式

记得设置头信息:

headers = {
    "Authorization": f"Bearer {OPENAI_API_KEY}",
    "Content-Type": "application/json"
}

进入全屏模式 退出全屏模式

把这一切放在一起,下面是使用 requests 库在 Python 中的实际请求:

import requests

# set the OpenAI API endpoint
url = "https://api.openai.com/v1/completions"

# set the prompt and other parameters for the request
prompt = "Hello, how are you?"
prompt_length = len(prompt.split())
max_tokens = 1024 - prompt_length
payload = {
    "model": "text-davinci-003",
    "prompt": prompt,
    "max_tokens": max_tokens,
    "temperature": 0.5,
    "top_p": 1,
    "n": 1
}
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

# send the request to the OpenAI API endpoinsk-Nnndgp2NfhIVwXNcPC6kT3BlbkFJUJmZOlWuYImxSGaGdB4Gt
response = requests.post(url, headers=headers, json=payload)

# print the response content
print(response.json())

进入全屏模式 退出全屏模式

将ChatGPT响应与你的代码结合起来

Tracardi实施了一个巧妙的技巧,将ChatGPT响应与他们的代码结合起来。他们要求聊天以JSON格式进行响应,然后将其解析为一个字典,可以在代码中使用。

为了从ChatGPT生成所需的响应,你需要提供正确的提示。Tracardi在他们的用例中使用了以下提示:

Customer bought HERE_LIST_OF_PRODUCTS. What other products would you suggest to this customer? Please provide at least 3 suggestions as a pair of product name and category. Respond with a JSON list of objects. 

进入全屏模式 退出全屏模式

确保将HERE_LIST_OF_PRODUCTS替换为客户购买的实际产品列表。

所以我们的代码可以是这样的:

import requests

# set the OpenAI API endpoint
url = "https://api.openai.com/v1/completions"

# Add your api key
YOUR_API_KEY = ""

list_of_products = ["Adidas sneakers", "t-shirt"]
list_of_products = ",".join(list_of_products)

# set the prompt and other parameters for the request
prompt = f"Customer bought {list_of_products}. What other products would you suggest to this customer? Please provide at least 3 suggestions as a pair of product name and category. Respond with a JSON list of objects. "
prompt_length = len(prompt.split())
max_tokens = 1024 - prompt_length
payload = {
    "model": "text-davinci-003",
    "prompt": prompt,
    "max_tokens": max_tokens,
    "temperature": 0.5,
    "top_p": 1,
    "n": 1
}
headers = {
    "Authorization": f"Bearer {YOUR_API_KEY}",
    "Content-Type": "application/json"
}

# send the request to the OpenAI API endpoint
response = requests.post(url, headers=headers, json=payload)

# print the response content
print(response.json())

进入全屏模式 退出全屏模式

当我运行这段代码时,我得到了这样的响应:

{
  "id": "cmpl-7d9JftFrUQy30f0amNadsryzd6V",
  "object": "text_completion", 
  "created": 1682415119,
  "model": "text-davinci-003", 
  "choices": [
    {"text": "\n\n[\n  {\n    "Product Name": "Adidas Track Pants",\n    "Category": "Clothing"\n  },\n  {\n    "Product Name": "Adidas Backpack",\n    "Category": "Bags"\n  },\n  {\n    "Product Name": "Adidas Sunglasses",\n    "Category": "Accessories"\n  }\n]", "index": 0, "logprobs": None, "finish_reason": "stop"}
  ], 
  "usage": {
    "prompt_tokens": 43, 
    "completion_tokens": 86, 
    "total_tokens": 129
  }
}

进入全屏模式 退出全屏模式

我们需要把 "choice "解析成dict,然后我们就可以在python代码中使用这个响应。

下面是这样做的代码:

result = response.json()
choices = json.loads(result["choices"][0]["text"])
print(choices)

进入全屏模式 退出全屏模式

我们当然可以通过加入更多关于我们产品的具体信息来提高提示的准确性。例如:

Customer bought {list_of_products}. What other products would you suggest to this customer, knowing that we sell {list_of_our_product_categories}. Please provide at least 3 suggestions as a pair of product name and category. Respond with a JSON list of objects in "choices" key. 

进入全屏模式 退出全屏模式

在固定的提示下,我得到了以下结果:

{
"choices": [
  {"product": "Energy Drinks", "category": "Beverages"}, 
  {"product": "Gym Bag", "category": "Training Equipment"},
  {"product": "Running Shorts", "category": "Sport Apparel"}
]
}

进入全屏模式 退出全屏模式

复制过去的代码

import json
import requests

# set the OpenAI API endpoint
url = "https://api.openai.com/v1/completions"

# Add your api key
YOUR_API_KEY = ""

list_of_products = ["Adidas sneakers", "t-shirt"]
list_of_products = ",".join(list_of_products)
list_of_our_product_categories = "Sport apparel, energy drinks, training equipment, etc."

# set the prompt and other parameters for the request
prompt = f"Customer bought {list_of_products}. What other products would you suggest to this customer, " \
         f"knowing that we sell {list_of_our_product_categories}. Please provide at least 3 suggestions as " \
         f"a pair of product name and category. Respond with a JSON list of objects in \"choices\" key. "
prompt_length = len(prompt.split())
max_tokens = 1024 - prompt_length
payload = {
    "model": "text-davinci-003",
    "prompt": prompt,
    "max_tokens": max_tokens,
    "temperature": 0.5,
    "top_p": 1,
    "n": 1
}
headers = {
    "Authorization": f"Bearer {YOUR_API_KEY}",
    "Content-Type": "application/json"
}

# send the request to the OpenAI API endpoint
response = requests.post(url, headers=headers, json=payload)

# print the response content
result = response.json()
choices = json.loads(result["choices"][0]["text"])
print(choices)

进入全屏模式 退出全屏模式

这个简单的技巧可以使你与chatGPT的整合非常容易。如果你想在客户旅程中使用这种方法--你可以随时安装Tcardi在其中添加你的自定义python插件