1 Star 0 Fork 1

python/ai-agent-imooc925

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
5.6 FewShot的使用.py 1.17 KB
一键复制 编辑 原始数据 按行查看 历史
码农的世界 提交于 2025-04-18 15:15 +08:00 . Initial commit: Add project files
# zeroshot会导致低质量回答
from langchain_openai import ChatOpenAI
model = ChatOpenAI(
model="gpt-4o-mini",
temperature=0.0,
openai_api_base = os.getenv("OPENAI_API_BASE"),
openai_api_key = os.getenv("OPENAI_API_KEY")
)
res = model.invoke("What is 2 🦜 9?")
print(res)
#增加示例
#使用FewShotChatMessagePromptTemplate
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate
#增加示例组
examples = [
{"input": "2 🦜 2", "output": "4"},
{"input": "2 🦜 3", "output": "5"},
]
#构造提示词模板
example_prompt = ChatPromptTemplate.from_messages(
[
("human", "{input}"),
("ai", "{output}"),
]
)
#组合示例与提示词
few_shot_prompt = FewShotChatMessagePromptTemplate(
example_prompt=example_prompt,
examples=examples,
)
#打印提示词模板
print(few_shot_prompt.invoke({}).to_messages())
## 最终提示词
final_prompt = ChatPromptTemplate.from_messages(
[
("system", "你是一位神奇的数学奇才"),
few_shot_prompt,
("human", "{input}"),
]
)
##重新提问
chain = final_prompt | model
result = chain.invoke({"input": "What is 2 🦜 9?"})
print(result)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/python_76/ai-agent-imooc925.git
git@gitee.com:python_76/ai-agent-imooc925.git
python_76
ai-agent-imooc925
ai-agent-imooc925
main

搜索帮助