Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

下面的代码有很多冗余的操作,比如pd的处理,streamlit的处理,返回的01的处理,现在有人帮我做这些了,只给我一个函数,入参是正文内容,出参是大模型生成的结果,帮我重构一下…

  1. User

    下面的代码有很多冗余的操作,比如pd的处理,streamlit的处理,返回的01的处理,现在有人帮我做这些了,只给我一个函数,入参是正文内容,出参是大模型生成的结果,帮我重构一下这个函数:def update_keywords(df, st_flag=False, idx=0): import streamlit as st if (pd.isnull(df.at[idx, '关键词']) or df.at[idx, '关键词'] == '' or df.at[idx, '关键词'] == '空') and df.at[ idx, '关键词'] != "坏": payload = { "prompt": """根据以上文章,生成五个关于文章内容的关键词,请使用json格式输出。 要求: 1. 不能生成一个长的事件,必须要生成关键词 2. 关键词不要超过4个字 3. 关键词要易于检索 4. 关键词要多样性,不要都以同样的字开头 5. 不要关注文章开头结尾的作者、版权要求等文章内容以外的信息 json的格式为{"keyword":["关键词1","关键词2","关键词3","关键词4","关键词5"]"},请在此确认关键词的数量为五个,并且严格按照所给的json格式输出:""", "article": df.at[idx, '正文内容'] .replace(' ', '') .replace('\n', '') .replace("\u3000", "") # 有的文章空格符号用的这个,会导致json结果生成不出来 [:2000] }

        retry_count = 0  # 初始化重试计数器
        max_retries = 15  # 设置最大重试次数
        new_prompt_flag = False
        output_strs = []
        output_strs_len = []
    
        while retry_count < max_retries:
            if retry_count > 13:
                target_number = 30
                closest_idx = find_closest_index(output_strs_len, target_number)
                # 第一个prompt一次都生成不成功的换prompt方法
                if not closest_idx and not new_prompt_flag:
    
                    print('新prompt尝试')
                    payload['prompt'] = """根据以上文章,生成五个关于文章内容的关键词,请使用json格式输出。
            要求:
            1. 不要关注文章开头结尾的作者、版权要求等文章内容以外的信息
            2. 关键词不要超过4个字
            3. 关键词要易于检索
            4. 关键词要多样性,不要都以同样的字开头
            5. 不能生成一个长的事件,必须要生成关键词
            json的格式为{"keyword":["关键词1","关键词2","关键词3","关键词4","关键词5"]},请在此确认关键词的数量为五个,按照所给的json格式输出,慢慢来,不着急,注意不要关注文章开头结尾的作者、版权要求等文章内容以外的信息,注意不要生成错的json格式哦:"""
                    retry_count = 0
                    new_prompt_flag = True
                    continue
                elif closest_idx or closest_idx == 0:
                    df.at[idx, '关键词'] = output_strs[closest_idx]
                    return 1
                else:
                    df.at[idx, '关键词'] = "坏"
                    break
            try:
                text_input = (payload["article"] + payload["prompt"]).replace("\xa0", '').replace(' ', '').replace('\n',
                                                                                                                   '').replace(
                    "\u3000", "")
    
                res = test_api_server(text_input)
                result = res['text'][0].replace(text_input, '')
    
                parsed_dict = json.loads(result)
                keyword_list = parsed_dict.get("keyword", [])
                output_str = str(keyword_list)
    
                # 初始化总长度为0
                total_length = 0
                balance_length = 0
                # 遍历列表并累加字符串长度
                for item in keyword_list:
                    if isinstance(item, str):  # 确保元素是字符串类型
                        total_length += len(item)
                        balance_length += count_letter_digit(item)
                total_length -= balance_length / 1.25
                output_strs.append(output_str)
                output_strs_len.append(total_length)
    
                if output_str.count("关键词") < 3 and total_length < 40 and len(keyword_list) == 5:
                    df.at[idx, '关键词'] = output_str
                    display_message('成功生成关键词: %s' % output_str, st=st, st_flag=st_flag, mode='success')
                    return 1
                else:
                    display_message('失败生成关键词: %s' % output_str, st=st, st_flag=st_flag, mode='warning')
                    retry_count += 1
            except requests.RequestException:
                display_message('API请求失败', st=st, st_flag=st_flag, mode='warning')
                retry_count += 1
            except Exception as e:
                display_message('异常: %s' % e, st=st, st_flag=st_flag, mode='warning')
                display_message('响应结果: %s' % res, st=st, st_flag=st_flag, mode='warning')
                retry_count += 1
        df.at[idx, '关键词'] = "坏"
    return 0
    
  2. Assistant

    def update_keywords(text_content): payload = { "prompt": """根据以上文章,生成五个关于文章内容的关键词,请使用json格式输出。 要求: 1. 不能生成一个长的事件,必须要生成关键词 2. 关键词不要超过4个字 3. 关键词要易于检索 4. 关键词要多样性,不要都以同样的字开头 5. 不要关注文章开头结尾的作者、版权要求等文章内容以外的信息 json的格式为{"keyword":["关键词1","关键词2","关键词3","关键词4","关键词5"]"},请在此确认关键词的数量为五个,并且严格按照所给的json格式输出:""", "article": text_content.replace(' ', '').replace('\n', '').replace("\u3000", "")[:2000] }

    retry_count = 0
    max_retries = 15
    new_prompt_flag = False
    output_strs = []
    output_strs_len = []
    
    while retry_count < max_retries:
        if retry_count > 13:
            target_number = 30
            closest_idx = find_closest_index(output_strs_len, target_number)
            if not closest_idx and not new_prompt_flag:
                print('新prompt尝试')
                payload['prompt'] = """根据以上文章,生成五个关于文章内容的关键词,请使用json格式输出。
        要求:
        1. 不要关注文章开头结尾的作者、版权要求等文章内容以外的信息
        2. 关键词不要超过4个字
        3. 关键词要易于检索
        4. 关键词要多样性,不要都以同样的字开头
        5. 不能生成一个长的事件,必须要生成关键词
        json的格式为{"keyword":["关键词1","关键词2","关键词3","关键词4","关键词5"]},请在此确认关键词的数量为五个,按照所给的json格式输出,慢慢来,不着急,注意不要关注文章开头结尾的作者、版权要求等文章内容以外的信息,注意不要生成错的json格式哦:"""
                retry_count = 0
                new_prompt_flag = True
                continue
            elif closest_idx or closest_idx == 0:
                return output_strs[closest_idx]
            else:
                return "坏"
        
        try:
            text_input = (payload["article"] + payload["prompt"]).replace("\xa0", '').replace(' ', '').replace('\n',
                                                                                                                   '').replace(
                "\u3000", "")
    
            res = test_api_server(text_input)
            result = res['text'][0].replace(text_input, '')
    
            parsed_dict = json.loads(result)
            keyword_list = parsed_dict.get("keyword", [])
            output_str = str(keyword_list)
    
            total_length = 0
            balance_length = 0
            for item in keyword_list:
                if isinstance(item, str):
                    total_length += len(item)
                    balance_length += count_letter_digit(item)
            total_length -= balance_length / 1.25
            output_strs.append(output_str)
            output_strs_len.append(total_length)
    
            if output_str.count("关键词") < 3 and total_length < 40 and len(keyword_list) == 5:
                return output_str
            else:
                retry_count += 1
        except requests.RequestException as e:
            print('API请求失败')
            retry_count += 1
        except Exception as e:
            print('异常: %s' % e)
            print('响应结果: %s' % res)
            retry_count += 1
    
    return "坏"