扣子空间
字节跳动推出的多功能AI智能体
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 ChatOpenAIfrom langchain.prompts import ChatPromptTemplatefrom 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_agentfrom 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# 初始化LangSmithlangsmith = LangSmith()# 评估应用evaluation_result = langsmith.evaluate(chain, input={"question": "What is the capital of France?"})print(evaluation_result)
from langchain.graph import LangGraph# 初始化LangGraphgraph = LangGraph()# 将应用添加到LangGraphgraph.add_chain(chain)# 部署为APIapi = graph.deploy_as_api()print(api.url)