Что такое LangChain?
LangChain — Python фреймворк для построения приложений на основе LLM. Предоставляет абстракции для цепочек вызовов, памяти, инструментов и агентов.
Установка
python3 -m venv langchain-env
source langchain-env/bin/activate
pip install langchain langchain-community langchain-ollama
pip install python-dotenv chromadbПодключение к Ollama
from langchain_ollama import OllamaLLM
llm = OllamaLLM(model="llama3.2", base_url="http://localhost:11434")
response = llm.invoke("Расскажи о преимуществах VDS")
print(response)Простая цепочка (Chain)
from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import OllamaLLM
prompt = ChatPromptTemplate.from_messages([
("system", "Ты помощник по хостингу."),
("user", "{question}")
])
llm = OllamaLLM(model="llama3.2")
chain = prompt | llm
result = chain.invoke({"question": "Чем VDS отличается от хостинга?"})
print(result)Агент с инструментами
from langchain.agents import create_react_agent, AgentExecutor
from langchain.tools import tool
from langchain_ollama import OllamaLLM
from langchain import hub
@tool
def get_server_info(query: str) -> str:
# Возвращает информацию о тарифах VDS
return "VDS Start 2GB RAM от 299 руб/мес"
llm = OllamaLLM(model="llama3.2", temperature=0)
tools = [get_server_info]
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = executor.invoke({"input": "Какой тариф нужен для AI-агента?"})
print(result["output"])ReAct-агенты работают по схеме: Reason (думать) + Act (действовать). Они пошагово решают задачу, вызывая инструменты по мере необходимости.
Версии: Используйте langchain >= 0.2 с новым синтаксисом LCEL. Старые цепочки через LLMChain устарели.