怎么用python调用chatgtp给每个链接生成好评

import os
import openai
import sys
import ast
import os
import openai
import time

import pandas as pd

openai.api_type = ""
openai.api_base = ""
openai.api_version = ""
openai.api_key = '你的密钥'

message_text = [{"role":"system","content":"You are an AI assistant that helps people find information."},{"role":"user","content":"你好"},{"role":"assistant","content":"你好!有什么我可以帮助你找到的信息吗?"}]

completion = openai.ChatCompletion.create(
  engine="automate_api",
  messages = message_text,
  temperature=0.7,
  max_tokens=800,
  top_p=0.95,
  frequency_penalty=0,
  presence_penalty=0,
  stop=None
)

class SequenceChat:
    def __init__(self, api_key, organization=None, azure=True):
        self.azure = azure  # 是否使用Azure api
        if azure:
            openai.api_type = "azure"
            openai.api_base = "https://suncent.openai.azure.com/"
            openai.api_version = "2023-07-01-preview"

        if organization:
            openai.organization = organization
        openai.api_key = api_key
        dic = openai.Model.list()
        if dic:
            models = []

            for model in dic['data']:
                models.append(model['id'])

            gpt = [i for i in models if i.startswith('gpt')]
            print(f'连结成功, 可用gpt模型:\n' + '\n'.join(gpt))
        else:
            print('openai连接失败')

        self.openai = openai
        self.msg_history = []
        self.msg_system = []
        self.fails = []

    def set_system(self, msg_system):
        self.msg_system = [
            {"role": "system", "content": msg_system}
        ]

    def ask(self, user_msg, msg_system=None, records=0, fail_limit=3, sleep_limit=18, model='gpt-4'):
        """

        :param msg_system: system消息
        :param model: 使用的模型
        :param sleep_limit: 失败后的睡眠时间
        :param user_msg: 传入的1条user消息
        :param records: 使用前n次历史对话
        :param fail_limit: 允许的最大失败重试次数
        :return: answer, response, 回答及响应
        """
        openai = self.openai

        if msg_system:
            self.set_system(msg_system)

        # 添加系统、历史问答及当前问题
        records = self.msg_history[-records * 2:] if records else []
        messages = self.msg_system + records + [{"role": "user", "content": user_msg}]
        while fail_limit > 0:
            try:
                if self.azure:
                    response = openai.ChatCompletion.create(
                        engine='automate_api',
                        model=model,
                        messages=messages
                    )
                else:
                    response = openai.ChatCompletion.create(
                        model=model,
                        messages=messages
                    )

                answer = response.choices[0].message.content
                # 添加问题回复到历史中
                self.msg_history.append({"role": "user", "content": user_msg})
                self.msg_history.append({"role": "assistant", "content": answer})
                return answer, response
            except Exception as e:
                print(e)
            print(f'chatgpt回复失败,重试第 {4 - fail_limit} 次')
            time.sleep(sleep_limit)
            fail_limit -= 1

        # 超出失败次数
        self.fails.append([messages, str(e)])
        return None, None

    def clear(self):
        self.msg_history = []
        self.msg_system = []
        self.fails = []


if __name__ == '__main__':
    chat = SequenceChat(api_key = '896697e1b90a49678cc3dda58051dbd9')
    system_msg = """
    You are an American who owns a used car. 
    You have already purchased a product on Amazon. 
    You love this product and think it's great.
    You need to write 3 unrepeated comments  and 3 corresponding comment titles according to the title and featurebullets of this link to welcome more people like you to buy, each with no less than 15 words and no more than 20 words.
    Comments cannot contain characters other than commas.
    """ # 你是一个美国二手车车主在亚马逊购物,根据一个链接的标题和五点写3条互不重复的15词好评

    df = pd.read_excel("D:\\PC-backups\\浏览器下载\\批量生成-ASIN维度上3个通用直评.xlsx",usecols=['asin','title','featurebullets'])
    chat.set_system(system_msg)
    a = 0
    reviews = []
    opps = []
    for index, row in df.iterrows():
        # print(f"ASIN: {row['asin']}")
        # print(f"Title: {row['title']}")
        # print(f"Feature Bullets: {row['featurebullets']}")
        asin = row['asin']
        title = row['title']
        featurebullets = row['featurebullets']
        msg = f"""
            asin:{asin}
            title:{title}
            featurebullets"{featurebullets}
            Output a list, put the asin number and three comments as strings in a list of python, [asin, the title of the first comment,first comment, the title of the second comment,second comment, the title of the third comment,third comment]
            The generated list must be able to become a list in python using the ast.literal_eval () statement
            """
        ans, response = chat.ask(msg)

        try:
            ans = ast.literal_eval(ans)
            # 在文件中增加一行:
            reviews.append(ans)
            # # 将新的review数据转换为DataFrame
            # new_df = pd.DataFrame([ans],
            #                       columns=['asin', 'title1', 'review1', 'title2', 'review2', 'title3', 'review3'])
        except:
            print(print(a),ans)
            opps.append(ans)
        chat.clear()
        a = a + 1
        # if a > 10:  # 每生成十条语句就存下来
        #    break

    # 定义文件名
    file_name = 'D:\\PC-backups\\浏览器下载\\Try-生成结果-ASIN维度上3个通用直评_output.xlsx.txt'

    # 打开文件用于写入,指定使用utf-8编码
    with open(file_name, 'w', encoding='utf-8') as file:
        # 遍历列表中的每个元素
        for item in opps:
            # 将每个元素写入文件,并在每个元素后添加换行符
            file.write(item + '\n')

    print(f'List has been successfully written to {file_name}')

    print(reviews)
    reviews_df = pd.DataFrame(reviews)
    # 将新的DataFrame 导出为 Excel 文件
    reviews_df.to_excel("D:\\PC-backups\\浏览器下载\\Try-生成结果-ASIN维度上3个通用直评_output.xlsx", index=False)
    # df = pd.read_excel("D:\\PC-backups\\浏览器下载\\批量生成-ASIN维度上3个通用直评.xlsx")
    # df = pd.merge(df,reviews_df,on='asin',how = 'left')

    # 合并某个路径下的所有excel表格
    df.to_excel("D:\\PC-backups\\浏览器下载\\try-Fianl-批量生成-ASIN维度上3个通用直评.xlsx",index=False)
    sys.exit(7)


    asin = 'B0BW4SW'
    title = 'Front Struts Shock Absorber Assembly Fits Corolla 2003 2004 2005 2006 2007 2008, Complete Suspension 172114 172115, Struts with Coil Spring Assemblies SAA689 2 PACKS'
    featurebullets = """
    ☑️【FITMENT】Cold Air Intake Kit Fit for 3" Universal Engine (Fits Manual and Auto Transmission)(Please MATCH your vehicle on the left top before purchasing)
☑️【STURDY MATERIAL】 Sturdy aluminum cold air intake kit with filter tubes and custom heat shields, mandrel-bent and powder-coated aluminum intake tubes help increase the amount of air flowing to your engine, while heat shields help protect the intake air from the high temperatures in the engine compartment.
☑️【REUSABLE DESIGN】 The reusable cold air intake filter with combines 2 layers of pleated, breathable cotton with filter oil to absorb dirt and dust particles, allows clean air to continue to flow into your engine, requiring cleaning only once every 100,000 miles under normal highway driving conditions.
☑️【HIGH PERFORMANCE】 High performance air filter intake kit Increase acceleration and engine growl, provides a less restrictive path for airflow, increasing the amount of cold, oxygen-rich air entering the engine by up to an estimated 14 horsepower and 13 foot-pounds of torque. Your engine will growl during acceleration and return to silence once you hit highway speeds.
☑️【INSTALL & MAINTENANCE】 Easy to maintain: No filter cleaning required over up to 100,000 miles. Easy to install: Bolts on in less than an hour with basic hand tools. The Cold Air Intake is one of the easiest ways to increase horse power and torque.
"""
    msg = f"""
            asin:{asin}
            title:{title}
            featurebullets"{featurebullets}
            Output a list, put the asin number and three comments as strings in a list of python, [asin, the title of the first comment,first comment, the title of the second comment,second comment, the title of the third comment,third comment]
            The generated list must be able to become a list in pthon using the ast.literal_eval () statement
    """

    chat.set_system(system_msg)

    ans, response = chat.ask(msg)

    print(ans)



怎么用python调用chatgtp给每个链接生成好评?

已知链接的标题和描述信息,现在利用chatgtp给每个链接生成3条互不重复的15字以内的的评论。

下面是代码的逐步解释和一些特殊用法的讲解:

1. **导入模块**:
   - `os`:用于与操作系统交互的功能,如文件路径操作。
   - `openai`:OpenAI的官方Python库,用于与OpenAI的API进行交互。
   - `sys`:提供了访问由C语言编写的Python解释器的函数和变量。
   - `ast`:用于将字符串形式的Python表达式转换为Python数据结构。
   - `time`:提供了各种与时间相关的函数。
   - `pandas`:一个数据分析库,用于处理和分析数据。

2. **设置OpenAI API**:
   - 设置API类型为Azure,API的基础URL,版本和API密钥。

3. **定义`SequenceChat`类**:
   - 这个类用于封装与OpenAI API的交互。
   - `__init__`方法初始化API设置,并列出可用的GPT模型。
   - `set_system`方法设置系统消息。
   - `ask`方法发送用户消息到OpenAI API,并处理响应。
   - `clear`方法清除历史消息。

4. **主程序**:
   - 创建`SequenceChat`实例。
   - 读取Excel文件,包含产品信息。
   - 对于每个产品,构造一个消息并发送给OpenAI API,生成评论。
   - 将生成的评论存储在列表中,并尝试将它们写入文件。

5. **特殊用法讲解**:
   - `openai.ChatCompletion.create`:这是OpenAI库中的一个方法,用于发送消息到API并获取生成的文本。
   - `ast.literal_eval`:安全地将字符串形式的Python表达式转换为Python对象。在这个脚本中,它用于验证生成的评论是否符合预期的格式。
   - `pd.read_excel`:pandas库中的一个函数,用于读取Excel文件。
   - `time.sleep`:暂停程序执行指定的时间(以秒为单位),用于在API请求失败时重试。

6. **文件操作**:
   - 使用`with open`语句打开文件进行写入,这是一种上下文管理器,可以确保文件在操作完成后正确关闭。

7. **错误处理**:
   - 在`ask`方法中,使用`try-except`块来捕获API调用过程中可能出现的异常,并在失败时进行重试。

8. **退出程序**:
   - 使用`sys.exit`来退出程序,可以传递一个状态码,表示程序的退出状态。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐木叶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值