
胜算云
AI模型算力聚合平台,聚合全球100+大模型
相关链接:GitHub项目地址Python版开发文档JS/TS版开发文档
LangChain是用在开发由大型语言模型(LLMs)驱动的应用程序的框架。框架通过简化LLM应用的开发、生产化和部署过程,帮助开发者快速构建智能代理和应用。LangChain的核心功能包括快速上手的开发体验、强大的生产化支持以及灵活的部署选项。框架由多个开源库组成,如langchain-core、langchain和langgraph,提供从基础抽象到复杂应用编排的全面支持。LangChain集成LangSmith和LangGraph,分别用在应用的评估和生产级编排,帮助开发者从原型到生产无缝过渡。

langchain包:pip install langchain
langchain-openai包:pip install langchain-openai
langchain-anthropic包:pip install langchain-anthropic
langchain-community包:pip install langchain-community
export OPENAI_API_KEY=your_openai_api_key
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain
# 初始化聊天模型
model = ChatOpenAI(model_name="gpt-3.5-turbo")
# 定义聊天提示模板
prompt_template = ChatPromptTemplate.from_template(
"You are a helpful assistant. Answer the user's question: {question}"
)
# 创建LLM链
chain = LLMChain(llm=model, prompt=prompt_template)
# 运行链
response = chain.invoke({"question": "What is the capital of France?"})
print(response)
from langchain.agents import create_agent
from langchain.tools import Tool
# 定义一个简单的工具函数
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
# 创建智能代理
agent = create_agent(
model="gpt-3.5-turbo",
tools=[Tool(name="get_weather", func=get_weather, description="Get weather for a given city")],
prompt="You are a helpful assistant that can get weather information."
)
# 运行智能代理
response = agent.invoke({"messages": [{"role": "user", "content": "What is the weather in Paris?"}]})
print(response)
from langchain.smith import LangSmith
# 初始化LangSmith
langsmith = LangSmith()
# 评估应用
evaluation_result = langsmith.evaluate(chain, input={"question": "What is the capital of France?"})
print(evaluation_result)
from langchain.graph import LangGraph
# 初始化LangGraph
graph = LangGraph()
# 将应用添加到LangGraph
graph.add_chain(chain)
# 部署为API
api = graph.deploy_as_api()
print(api.url)