目录
一、准备工作
准备工作参考:
【大模型应用开发-实战】(四)手把手入门智普清言官方API调用-准备工作(一)-优快云博客
使用curl、openAI、zhipuai依赖库调用,参考
【大模型应用开发-实战】(五)手把手入门智普清言官方API调用-使用openai、zhipu sdk和requests调用(二)-优快云博客
使用langchain方式调用,参考
https://forestlong.blog.youkuaiyun.com/article/details/148980146?spm=1011.2415.3001.5331
二、完整代码
1、依赖安装
requirements.txt
langchain==0.3.26
langchain-community==0.3.26
langchain_openai==0.3.27
langchainhub==0.1.21
httpx_sse==0.4.1
requests==2.32.4
python-dotenv==1.1.1
pip install -r requirements.txt
2、新建.env文件
ZHIPUAI_API_KEY = "zhipuai_api_key"
LANGCHAIN_API_KEY = "zhipuai_api_key"
3、核心调用代码
chagtlm_langchain_with_agent.py
# 完整解决方案:LangChain Agent + 智谱清言童话创作系统
from dotenv import load_dotenv
import os
from langchain.agents import AgentExecutor, Tool, create_react_agent
from langchain_community.chat_models import ChatZhipuAI
from langchain import hub
# 1. 环境配置(API密钥存储在.env文件)
load_dotenv()
ZHIPU_API_KEY = os.getenv("ZHIPUAI_API_KEY")
# 2. 初始化智谱GLM-4模型(创造性参数优化)
zhipu_llm = ChatZhipuAI(
model_name="glm-4",
temperature=0.9, # 提高创造性
max_tokens=2500, # 保证长故事完整
api_key=ZHIPU_API_KEY
)
# 3. 定义故事评估工具(确保教育价值)
def story_evaluator(story: str) -> str:
"""评估故事的教育元素和趣味性"""
kindness_count = story.count("善良") + story.count("爱心")
magic_elements = sum(1 for word in ["魔法", "精灵", "会说话的"] if word in story)
return f"""评估通过!故事包含:
- 善良主题出现次数:{kindness_count}
- 奇幻元素数量:{magic_elements}
- 互动句式:{"有" if "你猜怎么着" in story else "需增加"}"""
def langchain_call_with_agent():
# 4. 构建工具集(可扩展添加更多工具)
tools = [
Tool(
name="StoryEvaluator",
func=story_evaluator,
description="用于检测故事的教育价值和儿童吸引力"
)
]
# 5. 创建防错提示模板(自动处理变量依赖)
prompt = hub.pull("hwchase17/react-chat") # 使用LangChain官方预置模板
prompt = prompt.partial(
tools="\n".join([f"{tool.name}: {tool.description}" for tool in tools]),
tool_names=", ".join([tool.name for tool in tools]),
chat_history="" # 显式提供空聊天历史避免缺失变量[2,4](@ref)
)
# 6. 构建童话创作Agent
story_agent = create_react_agent(
llm=zhipu_llm,
tools=tools,
prompt=prompt
)
# 7. 配置执行器(带错误处理)
agent_executor = AgentExecutor(
agent=story_agent,
tools=tools,
verbose=True,
max_iterations=3,
handle_parsing_errors=True # 防止解析错误中断[3](@ref)
)
# 8. 执行故事生成(提供完整输入变量)
try:
print("🧙 童话魔法师开始创作...")
result = agent_executor.invoke({
"input": """作为童话大王,请创作800字左右的奇幻故事,要求:
1. 主角:拥有魔法画笔的小女孩
2. 反派:偷走颜色的灰影怪
3. 核心寓意:善良能创造奇迹
4. 必须包含3次互动问题如'你猜怎么着?'
5. 分5个章节:相遇-危机-选择-奇迹-领悟
6. 故事长度约200字""",
"chat_history": [] # 确保提供所有必需变量[2](@ref)
})
print("\n✨ 原创童话故事 ✨")
print(result["output"])
except Exception as e:
print(f"魔法失效了!错误信息: {str(e)}")
if __name__ == '__main__':
langchain_call_with_agent()