AI开发-python-langchain框架(3-13-串行流程 )

现在有这样一个需求,要求使用AI智能化完成这个任务。

  • 1、先处理大纲:构建大纲提示词 → 获得大纲内容

  • 2、再处理注意事项:构建注意事项提示词 → 获得注意事项内容

  • 3、最后整合生成文章:整合所有信息 → 构建最终提示词 → 获得完整文章

流程图如下:

代码实现:

复制代码
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
#目标写一个文章 先让大模型生成大纲和需要注意事项 然后仍给大模型生成文章

#模型接入
DEEPSEEK_API_KEY = "123"  # 替换为实际的 API Key
llm = ChatOpenAI(
    api_key=DEEPSEEK_API_KEY,
    base_url="http://qwen3-32b-awq.model.xjipc.com/openai/v1",
    model="qwen3-32b-awq",
    temperature=0.3,
    max_tokens=10240,
)

#生成大纲提示词
outlinePromptTemplate = '''主题:{theme}
如果要根据主题写一篇文章,请列出文章的大纲。'''
outlinePrompt = ChatPromptTemplate.from_template(outlinePromptTemplate)


#生成注意事项提示词
tipsPromptTemplate = '''主题:{theme}
如果要根据主题写一篇文章,应该需要注意哪些方面,才能把这篇文章写好。
'''
tipsPrompt = ChatPromptTemplate.from_template(tipsPromptTemplate)
tipsPrompt

#主题
query = "2025年中国经济走向与运行趋势"
strParser = StrOutputParser()

#生成大纲
outlineChain = outlinePrompt | llm | strParser
outline = outlineChain.invoke({"theme":query})

#生成注意事项
tipsChain = tipsPrompt | llm | strParser
tips = tipsChain.invoke({"theme":query})
print('------------大纲--------------')
print(outline)

print('------------注意事项--------------')
print(tips)

#最终生成文章提示词
articlePromptTemplate = '''主题:{theme}
大纲:
{outline}

注意事项:
{tips}

请根据上面的主题、大纲和注意事项写出丰富的完整文章内容。
'''

articlePrompt = ChatPromptTemplate.from_template(articlePromptTemplate)



#生成最终文章
articleChain = articlePrompt | llm | strParser
resutl = articleChain.invoke({
    "theme":query,
    "outline":outline,
    "tips":tips
})
print('------------生成最终文章--------------')
print(resutl)

缺点时间效率低

  • 总耗时累加:总执行时间 = 生成大纲时间 + 生成注意事项时间 + 生成文章时间

  • 如果每个LLM调用需要3秒,总耗时至少9秒

如何优化改成并行,下一篇对该流程进行优化改进。

更多学习资料尽在 老虎网盘资源