LangChain - 构建 AI 应用的强大框架

一、什么是 LangChain?

LangChain 是一个用于开发基于大语言模型(LLM)应用程序的框架,它提供了一系列工具和抽象,让开发者能够更容易地构建复杂的 AI 应用。

二、核心概念

1. 基础组件

从示例代码中我们可以看到几个重要的基础组件:

1. 环境配置

js 复制代码
import os
os.environ["OPENAI_API_KEY"] = "your-api-key"
os.environ["OPENAI_BASE_URL"] = "your-base-url"

2. 聊天模型

js 复制代码
from langchain_openai import ChatOpenAI
chat = ChatOpenAI(
    model="gpt-3.5-turbo",
    temperature=0.8,
    max_tokens=60    
)

3. 基础LLM

js 复制代码
from langchain_openai import OpenAI
llm = OpenAI(model_name="gpt-3.5-turbo-instruct")

2. 消息类型

LangChain 支持多种消息类型:

js 复制代码
from langchain.schema import (
    SystemMessage,  # 系统消息
    HumanMessage    # 用户消息
)
messages = [
    SystemMessage(content="你是一个很棒的风水师"),
    HumanMessage(content="请给我的花店起个名")
]

3. 模板系统

LangChain 提供了强大的模板系统:

js 复制代码
from langchain.prompts import PromptTemplate
template = """你是一位专业的鲜花店的文案撰写员。
对于售价为{price} 元的{flower_name},你能提供一个吸引人的简短描述吗?
"""
prompt = PromptTemplate.from_template(template)
input = prompt.format(flower_name="玫瑰",price="99")

三、实际应用示例

1. 简单对话

js 复制代码
chat = ChatOpenAI(    model="gpt-3.5-turbo",   
temperature=0.8,    
max_tokens=60    
)

messages = [    SystemMessage(content="你是一个很棒的风水师"),
HumanMessage(content="请给我的花店起个名")]

response = chat(messages)
print(response.content)

2. 模板化文案生成

js 复制代码
template = """你是一位专业的鲜花店的文案撰写员。
对于售价为{price} 元的{flower_name},你能提供一个吸引人的简短描述吗?
"""

prompt = PromptTemplate.from_template(template)

input = prompt.format(flower_name="玫瑰",price="99")

model = OpenAI(model_name="gpt-3.5-turbo-instruct")output = model.invoke(input)

2. 格式化输出格式

js 复制代码
# 格式化输出
from langchain.output_parsers import StructuredOutputParser, ResponseSchema

response_schemas = [
    ResponseSchema(name="description",description="鲜花的描述文案"),
    ResponseSchema(name="reason",description="为什么要这样写这个文案"),
]

output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
print(output_parser)

format_instruction = output_parser.get_format_instructions()
print(format_instruction)

output = PromptTemplate.from_template(template,
partial_variables={"format_instruction":format_instructions})

input = prompt.format_prompt(
    flower_name="玫瑰",
    price="99",
    format_instruction=format_instruction
)
print(input)

output = model.invoke(input)
print(output)
相关推荐
阑梦清川1 分钟前
如何使用coze搭建可以自动生成图像的智能体
aigc
bug菌1 小时前
程序员转型产品经理,是逃避技术还是拥抱未来?Trae可替你回答!
aigc·ai编程·trae
不大姐姐AI智能体2 小时前
涨粉16w,最新Coze智能体工作流:1分钟批量生成英语启蒙短文朗读视频,宝妈也能月入过万
aigc
bug菌3 小时前
当产品迭代遇上AI编程,Trae能否重新定义“快速交付“?
aigc·ai编程·trae
维李设论3 小时前
前端智能化 | AG-UI实践及原理浅析
前端·aigc·agent
猫头虎3 小时前
猫头虎AI分享|一款Coze、Dify类开源AI应用超级智能体Agent快速构建工具:FastbuildAI
人工智能·开源·github·aigc·ai编程·ai写作·ai-native
bug菌4 小时前
还在为多平台开发头疼?看Trae如何让你一人顶一个团队!
aigc·ai编程·trae
bug菌4 小时前
还在为团队协作扯皮?看字节Trae如何让代码评审变成"享受"!
aigc·ai编程·trae
大志说编程4 小时前
LangChain框架入门16:智能客服系统RAG应用实战
后端·langchain·aigc
用户5191495848455 小时前
1989年的模糊测试技术如何在2018年仍发现Linux漏洞
人工智能·aigc