import tiktoken import openai import os import gradio as gr openai.api_key = os.environ.get("OPENAI_API_KEY") encoding = tiktoken.get_encoding("cl100k_base") def generate_prompt(prompt: str, style: str) -> str: if len(prompt) == 0: return "请输入您的提示语" generated_prompt = '以“' + prompt + '”为主题,撰写一段' + style + ',字数在100字左右' print('功能:' + style + ',generated_prompt:' + generated_prompt) return generated_prompt def text_generation(original_prompt: str, generated_prompt: str, style: str) -> str: if not len(generated_prompt) == 0: prompt = generated_prompt elif not len(original_prompt) == 0: prompt = original_prompt else: return "请输入您的提示语" print('功能:' + style + ',提示语:' + prompt) if len(encoding.encode(prompt)) > 512: return "您的提示语过长,请精简后再试" response = openai.ChatCompletion.create( model="gpt-3.5-turbo", #gpt-4, gpt-3.5-turbo, text-embedding-ada-002 messages=[{"role": "user", "content": prompt}], temperature=0.5, max_tokens=3580, top_p=1) result = '按照您的提示语:' + prompt + ',生成的文案如下:\n\n' + response["choices"][0]["message"]["content"] print(result) return result css_style = "#fixed_size_img {height: 240px;} " title = "文案创作 by宁侠" description = ''' 本服务的主要应用场景涵盖多种文案输入生成和续写,例如用户可以自行输入各种内容,之后服务将会对其进行回答、续写或者按照指令进行回复。 ''' with gr.Blocks(title=title, css=css_style) as demo: gr.HTML('''