环境说明:代码内的common.get_model()方法为提取到公共类里面的方法
一、 深入核心:调校你的AI引擎
掌握init_chat_model的关键参数,进准控制模型行为
1. temperature
控制输出的随机性与创造性,控制模型的活跃度,越高则模型就更有创意,越低则模型越保守
2. max_tokens
控制生成内容的最大长度,建议设置高点 但是不能超过大模型最大的maxtoken限制
3. timeout
设置API请求的超时时间,如果超时会触发重试
4. max_retries
定义请求失败后的自动重试次数
二、平衡创造与精准
1. Temperature - 随机性控制器
0.0 - 0.3 精确任务,如:数学计算,代码生成,翻译等
0.4 - 0.7 平衡输出,如:客服对话,知识问答
0.8 - 1.2 创意写作,如:文案创作,头脑风暴
2. MaxToekns - 成本与长度控制器
估算规则
- 英文:1 token ≈ 4 字符 ≈ 0.75 单词
- 中文:1 token ≈ 1-2汉字
三、指令的艺术:v1.0提示词工程
1. 核心变化
从Message对象到更直接的字符串/字典,API调用更简洁
Legacy:[HumanMessage,AIMessage]
v1.0:[('human','.....'),('ai','.....')]
2. 系统提示词(System Prompt)
为AI设定校色、行为便捷和输出规则,是高质量输入的第一步。
3. 设计技巧
- 明确角色:告诉AI它是谁(e.g.,'你是一个资深的Python程序员')
- 定义风格:沟通的语调(e.g.,‘风格轻松幽默’)
- 设定边界:什么不能做(e.g.,‘不要回答与编程无关的问题’)
- 输出格式:明确指定(e.g.,‘必须以JSON格式输出’)
system_prompt = """你是一个专业的Python编程助手
你的特点:
- 擅长解释复杂的概念
- 代码示例清晰易懂
- 注重最佳实践
- 不使用已废弃的语法
回答要求:
- 先解释原理,再给代码
- 代码要有详细的注释
- 如果有多种方案,说明优劣
"""
messages = [
{"role":"system","content":system_prompt},
{"role":"user","content":"什么是装饰器?"}
]
response = model.invoke(messages)
print(response.content)
4. 用示例引导AI:Few-Shot学习的力量
当指令不够清晰时,提供几个范例是最好的方法。
# 错误示例
# Prompt
"将句子分类为'积极或'消极':'今天天气不错!'"
# AI Response
"这是一个积极的陈述"
# 格式不统一
# 提供示例后的正确示例
# Prompt with examples
'[{"input":"这部电影太棒了","output":"积极"},{"input":"我不太喜欢这个","output":"消极"},]'
"将句子分类为'积极或'消极':'今天天气不错!'"
# AI Response
"积极"
# (格式完全符合预期)
few_shot_prompt = """你是一个情感分析助手,根据文本判断情感倾向。
示例1:
输入:今天天气真好,心情很愉快!
输出:正面 | 置信度:0.95
示例2:
输入:产品质量太差了,非常失望。
输出:负面 | 置信度:0.90
示例3:
输入:今天去了超市买东西。
输出:中性 | 置信度:0.87
现在分析下面的文本:
"""
from common import Common
common = Common()
model = common.get_model()
# user_input = "这个课程内容很实用,学到了很多知识!"
user_input = "什么垃圾玩意儿,再也不买了!"
messages = [
{"role":"system","content":few_shot_prompt},
{"role":"user","content":user_input}
]
response = model.invoke(messages)
print(response.content)
5. 常见提示词方式
# 方式一:纯字符串(简单场景)
response = model.invoke("翻译成英文:你好世界")
# 方式二:消息列表(多轮对话)
messages = [
{"role":"system","content":"你是一个专业的翻译助手"},
{"role":"user","content":"翻译:Hello world"}
]
response = model.invoke(messages)
# 方式三:使用Message对象(兼容旧代码)
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
messages = [
SystemMessage(content="你是一个专业的翻译助手"),
HumanMessage(content="翻译:Hello world")
]
response = model.invoke(messages)
6. 提示词模板
"""
提示词模板示例
"""
from common import Common
class PromptTemplate:
"""简单的提示词模板类"""
def __init__(self, template: str):
self.template = template
def format(self, **kwargs):
return self.template.format(**kwargs)
# 定义模板
translation_template = PromptTemplate("""你是一个专业的翻译助手,
任务:将{source_lang} 翻译成 {target_lang}
风格:{style}
原文:
{text}
翻译:"""
)
# 使用模板
prompt = translation_template.format(
source_lang="中文",
target_lang="英文",
style="正式",
text="有句古话说得好:识时务者为俊杰!"
)
common = Common()
model = common.get_model()
response = model.invoke(prompt)
print(response.content)
四、效率革命:批量、异步与流式输出
1. 批量调用(Batch)
描述:一次API调用处理多个独立输入。
适用场景 :数据清晰、批量评估、离线任务。显著优于循环调用
from common import Common
common = Common()
model = common.get_model()
# 准备多个输入
inputs = [
"翻译成英文:春天来了",
"翻译成英文:你好,世界",
"翻译成英文:你好,世界,中国",
"翻译成日文:冬天下雪",
"翻译成韩文: 夏天很热"
]
# 批量调用
import time
start = time.time()
response = model.batch(inputs)
batch_time = time.time() - start
for i, output in enumerate(response):
print(f"输入:{inputs[i]}")
print(f"输出:{output.content}")
print("-" * 20)
print(f"批量调用耗时:{batch_time:.2f}秒")
# 循环调用(低效,仅用于对比)
start = time.time()
loop_responses = []
for input in inputs:
loop_responses.append(model.invoke(input).content)
loop_time = time.time() - start
print(f"循环调用耗时:{loop_time:.2f}秒")
print(f"批量调用节省的时间:{((loop_time - batch_time)/loop_time * 100):.2f}%")
# 输出结果:
# 输入:翻译成英文:春天来了
# 输出:Spring has come.
# --------------------
# 输入:翻译成英文:你好,世界
# 输出:Hello, world
# --------------------
# 输入:翻译成英文:你好,世界,中国
# 输出:Hello, world, China
# --------------------
# 输入:翻译成日文:冬天下雪
# 输出:冬に雪が降る
# --------------------
# 输入:翻译成韩文: 夏天很热
# 输出:여름은 매우 덥습니다
# --------------------
# 批量调用耗时:2.07秒
# 循环调用耗时:22.83秒
# 批量调用节省的时间:90.93%
# 进程已结束,退出代码为 0
2. 异步调用(Async)
描述:非阻塞式调用,允许程序在等待AI响应时执行其他任务
适用场景:高并发的Web服务(如:FastAPI,Tornado)
from datetime import time
from common import Common
import time
common = Common()
model = common.get_model()
# 定义翻译文本列表
texts = [
"春天来了",
"你好,世界",
"你好,世界,中国",
"冬天下雪",
"夏天很热"
]
import asyncio
async def translate_async(text:str,idx:int)->str:
""" 异步翻译 """
print(f"任务{idx} 开始发送")
start = time.time()
response = await model.ainvoke(f"{text}")
print(f"任务{idx} 结束,耗时:{time.time() - start:.2f}秒")
return response.content
async def main():
# 并发处理多个任务
tasks = []
for i,t in enumerate(texts):
if i < 3:
task = translate_async(f"翻译成英文:{t}",i)
elif i==3:
task = translate_async(f"翻译成日文:{t}",i)
else:
task = translate_async(f"翻译成韩文:{t}",i)
tasks.append(task)
results = await asyncio.gather(*tasks)
for i, result in enumerate(results):
print(f"输入:{texts[i]}")
print(f"输出:{result}")
print("-" * 20)
# 启动异步任务
asyncio.run(main())
3. 流式输出(Streaming)
描述:实时返回生成的内容,而非等待完整结果。
适用场景:提升实时聊天机器人、长文本生成等应用的用户体验
五、结构之美:从非结构化文本到可用数据
KeyTechnology:通过Pydantic定义你期望的Python对象结构,LangChain负责将模型输出可靠地转换为该结构
"这部电影的主角是艾玛,导演是汤姆,上映于2023年"
↓
with_structured_output
↓
{
"title":"电影信息",
"protagonist":"艾玛",
"director":"汤姆",
"release_year":2023
}
from common import Common
common = Common()
model = common.get_model()
from pydantic import BaseModel,Field
# 定义输出结构
class SentimentAnalysis(BaseModel):
"""情感分析结果"""
sentiment:str = Field(description="情感倾向:positive/nagative/neutral")
confidence:float = Field(description="置信度,0-1之间")
keywords:list[str] = Field(description="关键词列表")
# 使用with_structured_output
structured_model = model.with_structured_output(SentimentAnalysis)
# 调用
text = "这个课程内容很实用啊,学到了很多知识,强烈推荐!"
result = structured_model.invoke(f"分析以下文本的情感:\n{text}")
print(f"类型:{type(result)}")
print(f"情感:{result.sentiment}")
print(f"置信度:{result.confidence}")
print(f"关键词:{result.keywords}")
# 输出:
# 类型:<class '__main__.SentimentAnalysis'>
# 情感:positive
# 置信度:0.95
# 关键词:['实用', '学到了很多', '强烈推荐']
""" 复杂的结构化输出 """
from common import Common
from pydantic import BaseModel,Field
from typing import List
common = Common()
model = common.get_model()
class Aspect(BaseModel):
"""评论维度"""
name:str = Field(description="维度名称,如:质量、价格、服务")
score:int = Field(description="评分,1-5分")
comment:str = Field(description="具体评价")
class ProductReview(BaseModel):
"""产品评论分析"""
overall_sentiment:str = Field(description="整体情感,如:Positive、Negative、Neutral")
overall_score:int = Field(description="综合评分,1-5分")
aspects:List[Aspect] = Field(description="各维度评价")
summary:str = Field(description="一句话总结")
# 创建结构化的模型
structured_model = model.with_structured_output(ProductReview)
# 测试
review_text = """
这款笔记本电脑性能非常强大,运行大型软件毫无压力。
屏幕色彩鲜艳,看视频很舒服。
不过价格有点贵,而且风扇噪音较大。
客服态度非常好,物流也很快
总体来说还是值得购买的,推荐!!
"""
result = structured_model.invoke(f"分析以产品的评论:\n{review_text}")
print(f"整体情感:{result.overall_sentiment}")
print(f"综合评分:{result.overall_score}")
print(f"各维度评价:")
for aspect in result.aspects:
print(f" - {aspect.name}: {aspect.score}/5 - {aspect.comment}")
print(f"总结:{result.summary}")
# 输出
# 整体情感:positive
# 综合评分:4
# 各维度评价:
# - 性能: 5/5 - 这款笔记本电脑性能非常强大,运行大型软件毫无压力。
# - 屏幕: 5/5 - 屏幕色彩鲜艳,看视频很舒服。
# - 价格: 3/5 - 不过价格有点贵
# - 噪音: 2/5 - 风扇噪音较大
# - 客服: 5/5 - 客服态度非常好
# - 物流: 5/5 - 物流也很快
# 总结:这款笔记本电脑在性能、屏幕显示、客服和物流方面表现优秀,但价格偏高且风扇噪音较大。用户总体上持正面评价,认为值得购买并推荐。
六、实战
1. Model参数详解
from langchain.chat_models import init_chat_model
model = init_chat_model(
model:str, # 必须,模型名称
model_provider:str, # 必须 提供商名称
temperature:float = 0.7, # 随机性(0 - 2)
max_tokens:int | None = None, # 最大输出token数
timeout:float | None = None, # 超时时间(秒)
max_retries:int = 2, # 重试次数
# 认证参数
api_key:str | None = None, # API秘钥
base_url:str | None = None, # 自定义 API 地址
# 高级参数
streaming:bool = False, # 是否默认流式输出
cache:bool = False, # 是否缓存响应
metadata:dict | None = None # 元数据标签
)
2. 智能文案生成器
"""
实战项目:智能文案生成器(LangChain 1.0)
功能:
- 多种文案类型和风格
- 批量生成
- AI 自动评分
- 导出到文件
"""
import os
from dotenv import load_dotenv
from common import Common
from pydantic import BaseModel,Field
from typing import List,Literal
import json
from datetime import datetime
load_dotenv()
common = Common()
# 定义结构化输出
class CopywritingScore(BaseModel):
"""文案评分"""
creativity:int = Field(description="创意性,1-10分")
clarity:int = Field(description="清晰度,1-10分")
appeal:int = Field(description="吸引力,1-10分")
overall:int = Field(description="综合评分,1-10分")
comment:str = Field(description="简短评语")
class Copywriting(BaseModel):
"""文案结果"""
content:str = Field(description="文案内容")
score:CopywritingScore = Field(description="质量评分")
class CopywritingBatch(BaseModel):
"""文案批量结果"""
results:List[Copywriting] = Field(description="文案列表")
class SmartCopywriter:
"""智能文案生成器"""
def __init__(self):
self.model = common.get_model()
self.structured_model = self.model.with_structured_output(CopywritingBatch)
def generate(
self,
product:str,
copy_type:Literal["广告","社交媒体","邮件","博客"],
style:Literal["正式","轻松","幽默","专业"],
count:int = 3
)->List[Copywriting]:
"""
生成文案
Args:
product : 产品或服务描述
copy_type: 文案类型
style: 文案风格
count: 生成数量
Returns:
文案列表(带评分)
"""
prompt = f"""你是一个专业的文案撰写专家
任务:为以下产品创作{copy_type}文案
产品信息:
{product}
要求:
- 文案类型:{copy_type}
- 风格:{style}
- 生成数量:{count}个不同版本
- 每个文案都要有创意,不要重复
- 为每个文案打分并给出评语
输出:
请输出{count}个文案,每个文案包含内容和评分
"""
result = self.structured_model.invoke(prompt)
return result.results
def export_to_file(self,copies:List[Copywriting],file_name:str=None):
"""导出到文件"""
if not file_name:
file_name = f"copywriting_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
data = {
"generated_at":datetime.now().isoformat(),
"copies":[
{
"content":copy.content,
"score":{
"creativity":copy.score.creativity,
"clarity":copy.score.clarity,
"appeal":copy.score.appeal,
"overall":copy.score.overall,
"comment":copy.score.comment
}
}
for copy in copies
]
}
with open(file_name,"w",encoding="utf-8") as f:
json.dump(data,f,ensure_ascii=False,indent=4)
return file_name
def main():
"""主函数"""
copywriter = SmartCopywriter()
print("*"*70)
print("= 智能文案生成器(LangChain 1.0)")
print("*"*70)
# # 示例1:广告文案
# print("\n示例1:广告文案")
# print("-"*70)
# product1 = """
# 产品:AI编程助手
# 特点:
# - 实时代码补全
# - 智能错误监测
# - 支持20+编程语言
# - 提高开发效率50%
# """
# copies1 = copywriter.generate(product1,"广告","专业",3)
# for i, copy in enumerate(copies1):
# print(f"文案版本{i+1}:")
# print(f"- 内容:{copy.content}")
# print(f"- 评分:创意:{copy.score.creativity},清晰度:{copy.score.clarity},吸引力:{copy.score.appeal},综合评分:{copy.score.overall}")
# print(f"- 评语:{copy.score.comment}")
# print("-"*70)
#
# # 示例2:社交媒体文案
# print("\n" + "="*70)
# print("示例2:社交媒体文案")
# print("-"*70)
# product2 = """
# 活动:LangChain 1.0 完整课程上线
# 内容:
# - 10节完整课程
# - 基于最新1.0版本
# - 包含实战项目
# - 适合Python开发者
# """
# copies2 = copywriter.generate(product2,"社交媒体","轻松",3)
# for i, copy in enumerate(copies2):
# print(f"文案版本{i+1}:")
# print(f"- 内容:{copy.content}")
# print(f"- 评分:创意:{copy.score.creativity},清晰度:{copy.score.clarity},吸引力:{copy.score.appeal},综合评分:{copy.score.overall}")
# print(f"- 评语:{copy.score.comment}")
#
# # 导出
# print("\n" + "=" * 70)
# file_name = copywriter.export_to_file(copies1+copies2,"generated_copies.json")
# print(f"已导出到文件:{file_name}")
# 交互模式
while True:
print("请输入产品信息(可多行,输入空行结束):")
lines = []
while True:
line = input()
if line == "":
break
if line.lower() == "quit":
print("已退出")
return
lines.append(line)
if not lines:
continue
product = "\n".join(lines)
copy_type = input("请选择文案类型(广告、社交媒体、邮件、博客):") or "广告"
style = input("请选择文案风格(正式、轻松、幽默、专业):") or "专业"
count = int(input("请输入生成数量:") or 3)
print("\n正在生成文案...")
copies = copywriter.generate(product,copy_type,style,count)
for i, copy in enumerate(copies):
print(f"文案版本{i+1}:")
print(f"- 内容:{copy.content}")
print(f"- 评分:创意:{copy.score.creativity},清晰度:{copy.score.clarity},吸引力:{copy.score.appeal},综合评分:{copy.score.overall}")
print(f"- 评语:{copy.score.comment}")
print("-"*70)
save = input("是否保存到文件?(y/n)")
if save.lower() == "y":
file_name = copywriter.export_to_file(copies)
print(f"已导出到文件:{file_name}")
if __name__ == "__main__":
main()