Большие языковые модели (LLM) — это модели, меняющие правила игры, которые позволяют разработчикам создавать приложения, которые ранее были невозможны. Однако использование только LLM часто недостаточно для разработки действительно надежного приложения. Реальная сила появляется, когда вы можете интегрировать их с другими источниками вычислений или знаний.

В этом уроке мы рассмотрим Langchain, библиотеку, которая позволяет нам разрабатывать приложения ИИ путем интеграции различных компонентов, таких как обертки моделей, цепочки, агенты и т. д.…

Примечание: библиотека LangChain доступна как на python, так и на javascript, но в этом руководстве мы будем использовать библиотеку python.

Настраивать

Сосновая шишка

В этом уроке мы будем использовать Pinecone, векторную базу данных для векторного поиска. Что такое хранилище векторов, мы определим далее в статье. Но сначала нам нужно создать учетную запись на pinecone и получить ключ API и имя среды (https://app.pinecone.io/).

Затем, если у вас есть учетная запись openai (в противном случае получите новую), получите ключ openai api с сайта платформы openai: https://platform.openai.com/account/api-keys

Теперь мы определяем файл .env со всеми собранными нами переменными.

OPENAI_API_KEY="..."
PINECONE_ENV="..."
PINECONE_API_KEY="..."

Установите требования

python-dotenv==1.0.0
langchain==0.0.137
pinecone-client==2.2.1
openai==0.27.8

Загрузить переменные среды

from dotenv import load_dotenv,find_dotenv
load_dotenv(find_dotenv())

Компоненты ленгчейн

В этом руководстве мы рассмотрим самые основные компоненты LangChain, которые позволяют нам создавать надежные приложения ИИ.

Эти компоненты:

  • Модели
  • Подсказки
  • Цепи
  • Вложения и хранилища векторов
  • Агенты

Модели (оболочки LLM)

Модели, по сути, являются обертками над большими языковыми моделями, мы можем выбирать между gpt-3.5-turbo и gpt-4, а в целях эксперимента мы выбираем gpt-3.5-turbo, поскольку он дешевле.

Примечание: вы также можете использовать LLM от других поставщиков, таких как Huggingface, Cohere и т. д. Например, вы можете использовать модели с открытым исходным кодом из открытой таблицы лидеров LLM от HuggingFace: https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard. Это возможно с помощью интеграции Huggingface с ленгчейном (https://python.langchain.com/docs/modules/model_io/models/llms/integrations/huggingface_hub)

Во-первых, давайте попробуем протестировать openai API.

from langchain.llms import OpenAI
llm = OpenAI(model_name="gpt-3.5-turbo")
llm("What is a good title for a tutorial about the library 'langchain'?")

# output : '"Introduction to Langchain: A Beginner\'s Guide to Utilizing the Library\'s Features"'

Мы также можем использовать модель чата, как показано на игровой площадке openai (https://platform.openai.com/playground?mode=chat&model=gpt-3.5-turbo), определив SystemMessage, который определяет контекст, и HumanMessage, который определяет наш ввод.

chat = ChatOpenAI(model_name="gpt-3.5-turbo",temperature=0.3)
messages = [
    SystemMessage(content="You are a helpful email assistant"),
    HumanMessage(content="Write an email to my landlord asking him for a rent decrease")
]
response=chat(messages)
print(response.content,end='\\n')

Примечание: Параметр температуры используется для контроля баланса между креативностью и согласованностью генерируемого контента.

  1. Более низкая температура (например, 0,0–0,4): для фактических и точных ответов.
  2. Умеренная температура (например, 0,5–0,7): идеально подходит для общего создания контента, сочетая креативность и последовательность.
  3. Более высокие настройки температуры (например, 0,8–1,0): генерируйте инновационные и неожиданные результаты, отлично подходят для мозговых штурмов, контента в социальных сетях и свежих взглядов на тему.

Подсказки

Далее мы собираемся использовать PromptTemplate, который позволяет нам форматировать приглашение в соответствии с пользовательским вводом. Это позволяет нам исключить стандартную часть подсказки и использовать одну и ту же структуру подсказки с разными входными данными.

from langchain import PromptTemplate

template = """
You are an expert machine learning engineer with an expertise in natural language processing. 
Explain the concept of {concept} in a couple of lines
"""

prompt = PromptTemplate(
    input_variables=["concept"],
    template=template,
)

llm(prompt.format(concept="large language model"))

#output : 'A large language model is a powerful machine learning model that can understand and generate human-like text. It is trained on extensive amounts of data, allowing it to learn patterns and generate coherent and contextually relevant responses to text input.'

Цепочки

Теперь, когда мы определили PromptTemplate и LLM, мы будем использовать «цепочку», которая позволит нам складывать их друг в друга. Цепочки — это компоненты, которые позволяют нам интегрировать разные блоки и объединять их в один блок.

# Import LLMChain and define chain with language model and prompt as arguments.

from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)

# Run the chain only specifying the input variable.
print(chain.run("large language model"))  

# output : A large language model is an advanced machine learning model that is trained on vast amounts of textual data, enabling it to understand and generate coherent human-like language. These models have billions of parameters and can perform various language tasks such as text completion, translation, summarization, and conversational interfaces.

Мы определяем вторую цепочку, которая берет концепцию и объясняет ее, как будто вам пять лет, в 500 словах.

# Define a second prompt

second_prompt = PromptTemplate(
    input_variables=["ml_concept"],
    template="Turn the concept description of {ml_concept} and explain it to me like I'm five in 500 words",
)
chain_two = LLMChain(llm=llm, prompt=second_prompt)

Кроме того, мы можем складывать цепочки вместе, чтобы создавать еще большие цепочки, где одна цепочка берет результат предыдущей и использует его в качестве входных данных.

from langchain.chains import SimpleSequentialChain
overall_chain = SimpleSequentialChain(chains=[chain, chain_two], verbose=True)

explanation = overall_chain.run("large language model")
print(explanation)

# output :
# Sure! Imagine you have a really smart robot friend who can read and understand books, websites, and all sorts of texts. This friend can learn from all of that information and become really good at talking and writing like a human. This is what we call a "large language model."

# This robot friend is like a super student who has read thousands and thousands of books and has gotten really good at understanding and using words. It's like having a teacher who knows so much about language that it can help you with any question or task involving words.

# For example, let's say you ask your robot friend, "What's the weather like today?" It will read and remember lots of information about weather forecasts and use that knowledge to give you an answer. Or you could ask it, "Can you tell me a story about a dragon?" and it would create a cool story using its knowledge of dragons from all the books it has read.
# ...

# These language models are very big and powerful because they've learned from so much information. The more texts they read and understand, the smarter they become. It's like the more books they read, the more answers and ideas they have. They learn from all sorts of books, websites, and even conversations people have had with them.

# So, in short, a large language model is like a super-smart robot friend who has read a ton of books and can help you with language-related tasks and answer your questions. It's like your personal language expert powered by artificial intelligence.

Встраивание и векторные хранилища

Чтобы использовать Langchain для наших проприетарных данных, мы используем векторные хранилища, такие как сосновая шишка, где мы будем хранить наши данные после того, как разобьем их на фрагменты и преобразуем в векторы (встраивания).

Во-первых, мы разбиваем наши данные на части, используя разделитель текста из библиотеки langchain.

from langchain.text_splitter import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size = 100,
    chunk_overlap  = 0,
)
texts = text_splitter.create_documents([explanation])

Во-вторых, мы превращаем эти фрагменты во вложения. Здесь мы используем модель OpenAI для создания вложений.

# Import and instantiate OpenAI embeddings
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(model_name="ada")
# Turn the first text chunk into a vector with the embedding
query_result = embeddings.embed_query(texts[0].page_content)
print(query_result)
# output :

Наконец, мы используем Pinecone в качестве векторного хранилища для сохранения сгенерированных вложений. Используя пользовательский интерфейс pinecone, мы сначала должны создать индекс с именем «langchain-quickstart» и установить размер векторов равным размеру вложений openai = 1024, а также выбрать принимаемое расстояние (евклидово, косинусное или скалярное произведение).

# Import and initialize Pinecone client
import os
import pinecone
from langchain.vectorstores import Pinecone
pinecone.init(
    api_key=os.getenv('PINECONE_API_KEY'),
    environment=os.getenv('PINECONE_ENV')
)
# Upload vectors to Pinecone
index_name = "langchain-quickstart"
search = Pinecone.from_documents(texts, embeddings, index_name=index_name)

И теперь мы можем запросить наши недавно сохраненные данные (например, мы можем выполнить поиск сходства)

query = "Why is there all this hype about large language models?"
result = search.similarity_search(query)
print(result)
# output: 
# [Document(page_content="These language models are very big and powerful because they've learned from so much information.", metadata={}), Document(page_content='These language models are super useful because they can do so many things with words! They can help', metadata={}), Document(page_content='talking and writing like a human. This is what we call a "large language model."', metadata={}), Document(page_content='So, in short, a large language model is like a super-smart robot friend who has read a ton of books', metadata={})]

Агенты

Агент — это оболочка вокруг модели, которая принимает пользовательский ввод и выполняет набор задач/действий. Мы можем использовать наш агент для создания работающего приложения ИИ.

В нашем случае мы создадим агент на Python, но существуют и другие типы агентов (https://python.langchain.com/docs/modules/agents/toolkits/)

# Import Python REPL tool and instantiate Python agent
from langchain.agents.agent_toolkits import create_python_agent
from langchain.tools.python.tool import PythonREPLTool
from langchain.python import PythonREPL
from langchain.llms.openai import OpenAI
agent_executor = create_python_agent(
    llm=OpenAI(temperature=0, max_tokens=1000),
    tool=PythonREPLTool(),
    verbose=True
)
agent_executor.run("What is the 10th fibonacci number?")

# output:
# > Entering new AgentExecutor chain...
#  I need to calculate the 10th fibonacci number
# Action: Python REPL
# Action Input: def fibonacci(n):
#     if n == 0:
#         return 0
#     elif n == 1:
#         return 1
#     else:
#         return fibonacci(n-1) + fibonacci(n-2)

# print(fibonacci(10))
# Observation: 55

# Thought: I now know the final answer
# Final Answer: 55

# > Finished chain.
# '55'

Заключение

Мы узнали о LangChain, платформе с открытым исходным кодом для обработки и понимания естественного языка. LangChain предоставляет оболочки для нескольких популярных моделей, таких как GPT-3.5-turbo и GPT-4, а также такие компоненты, как подсказки, цепочки, вложения, хранилища векторов и агенты.

Эти компоненты являются строительными блоками для правильного приложения ИИ (персональный помощник, анализатор документов, пользовательский чат-бот…).

Рекомендации