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)
相关推荐
2601_956865779 小时前
怎么用AI生成带货视频?电商内容创作工具推荐与选择思路
人工智能·aigc·音视频
Sirius Wu10 小时前
OpenClaw(UpClaw)三层Tool全链路治理深度详解
网络·人工智能·架构·aigc
日光明媚12 小时前
LongLive-英伟达-数字人实时生成
人工智能·计算机视觉·aigc·音视频
程序员佳佳12 小时前
模型网关灰度不是调百分比:把放量、观测和回滚做成账本
java·数据库·人工智能·redis·gpt·aigc·embedding
码农阿强12 小时前
GPT-5.6 Sol/Terra/Luna 三模型全量上架StartAPI|分层选型+可运行调用代码实战
大数据·人工智能·gpt·ai·aigc
Z-D-K15 小时前
AI对Anthropic的J-space的分析(1)
ai·aigc·人机交互·agent·agi
TrisighT16 小时前
Agent 的工具调用我从来不用官方推荐那套写法——4 个我实测下来更稳的隐藏用法
aigc·openai·cursor
leeyi16 小时前
调试 Agent 的 3 个姿势:日志、断点、可视化(第49篇-E35)
aigc·agent·devops
Sirius Wu19 小时前
OpenClaw 四层 Langfuse 全链路追踪完整详解
人工智能·ai·aigc
程序员佳佳1 天前
不是接口调不通,而是链路没拆清:Dify RAG、向量引擎与 timeout 排查实战
gpt·aigc·文心一言·gpu算力