如何编程生成GPT提示词?批量调用OpenAI API的优雅实现
优化OpenAI API提示词循环实现的方案
问题背景
我有如下模板提示词:
prompt = f""" Write a poem about the topic delimited by triple backticks if it starts with a consonant, otherwise say "foo". Topic: ```{topic}``` """
以及主题列表:
topics = ['cuddly pandas', 'ugly bears', 'sketchy Elons']
需要针对topics中的每个主题,使用相同的基础提示词调用OpenAI API。当前循环实现需在每次迭代时重新定义f-string,不够优雅,求优化方案。
优化方案
方法1:预定义模板字符串,使用str.format()生成提示词
将基础模板定义为普通字符串,仅保留占位符,循环时通过format()方法传入主题参数,避免重复构建f-string:
# 预定义基础模板(仅定义一次) base_prompt = """ Write a poem about the topic delimited by triple backticks if it starts with a consonant, otherwise say "foo". Topic: ```{topic}``` """ topics = ['cuddly pandas', 'ugly bears', 'sketchy Elons'] # 循环生成提示词并调用API for topic in topics: current_prompt = base_prompt.format(topic=topic) # 此处替换为OpenAI API调用逻辑,例如: # response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": current_prompt}]) print(current_prompt)
方法2:使用string.Template类(适合复杂场景的安全替换)
如果需要更严格的模板替换规则(避免占位符冲突),可以用Python标准库的string.Template:
from string import Template # 定义Template模板(仅定义一次) prompt_template = Template(""" Write a poem about the topic delimited by triple backticks if it starts with a consonant, otherwise say "foo". Topic: ```$topic``` """) topics = ['cuddly pandas', 'ugly bears', 'sketchy Elons'] for topic in topics: current_prompt = prompt_template.substitute(topic=topic) # 调用OpenAI API print(current_prompt)
方法3:封装为函数,复用构建逻辑
如果后续需要扩展提示词构建规则(比如添加额外判断),封装成函数会让代码更易维护:
def build_prompt(topic): """根据主题生成符合要求的提示词""" base_prompt = """ Write a poem about the topic delimited by triple backticks if it starts with a consonant, otherwise say "foo". Topic: ```{topic}``` """ return base_prompt.format(topic=topic) topics = ['cuddly pandas', 'ugly bears', 'sketchy Elons'] for topic in topics: current_prompt = build_prompt(topic) # 调用OpenAI API print(current_prompt)
以上方案均实现了仅定义一次基础模板,循环时仅传入主题参数生成具体提示词,避免了重复定义f-string的冗余操作,代码更简洁优雅且易于维护。
内容的提问来源于stack exchange,提问作者DeltaIV
相关产品推荐
相关产品推荐

