最佳实践
中文exp-2806未验证
系统提示词优化 文档内容复用 对话历史管理 使用稳定的系统提示词 # 推荐:使用稳定的系统提示词 system_prompt = """ 你是一个专业的技术顾问,具有以下特点: - 深厚的技术背景和丰富的项目经验 - 能够提供准确、实用的技术建议 - 善于用简洁明了的语言解释复杂概念 请根据用户问题提供专业的技术指导。 """ 将长文档作为系统消息 # 推荐:将长文档作为系统消息 def create_document_based_chat ( document_content , user_question ): return client.chat.completions.create( model = "glm-5.3" , messages = [ { "role" : "system" , "content" : f "请基于以下文档内容回答用户问题: \n\n { document_content } " }, { "role" : "user" , "content" : user_question } ] ) # 多次调用相同文档,系统提示词会被缓存 questions = [ "文档的主要内容是什么?" , "有哪些关键要点?" , "如何实施这些建议?" ] for question in questions: response = create_document_based_chat(document_content, question) # 第二次及以后的调用会命中缓存 管理对话历史以提高缓存效率 class ConversationManager : def __init__ ( self , client , system_prompt ): self .client = client self .system_prompt = system_prompt self .history = [{ "role" : "system" , "content" : system_prompt}] def add_message ( self , role , content ): self .history.append({ "role" : role, "content" : content}) def get_response ( self , user_message ): # 添加用户消息 self .add_message( "user" , user_message) # 获取回复(历史对话会被缓存) response = self .client.chat.completions.create( model = "glm-5.3" , messages = self .history ) # 添加助手回复到历史 assistant_message = response.choices[ 0 ].message.content self .add_message( "assistant" , assistant_message) return response def get_cache_stats ( self , response ): """获取缓存统计""" if hasattr (response.usage, 'prompt_tokens_details' ): cached = response.usage.prompt_tokens_details.cached_tokens or 0 total = response.usage.prompt_tokens return f "缓存命中: { cached } / { total } ( { cached / total * 100 :.1f} %)" return "无缓存信息" # 使用示例 manager = ConversationManager(client, "你是一个编程助手..." ) response1 = manager.get_response( "如何学习 Python?" ) response2 = manager.get_response( "推荐一些学习资源" ) # 会复用之前的对话缓存
复制后粘贴到 AI 对话框发送,本次对话全程生效
出处:智谱 GLM 官方提示词教程 · docs.bigmodel.cn/cn/guide/capabilities/cache · 可信度 S · 标签:中文 / 提示词工程 / 长上下文 / 少样本 怎么用(对话型)复制后粘贴到对话框发送,本次对话全程生效。想长期用:支持自定义指令的产品(设置→个性化)可设为默认。