🚀 Попробуйте Zilliz Cloud, полностью управляемый Milvus, бесплатно — ощутите 10-кратное увеличение производительности! Попробовать сейчас>

milvus-logo
LFAI
Главная
  • Интеграции
  • Home
  • Docs
  • Интеграции

  • Модели встраивания

  • Джина А.И.

Интеграция Milvus с Jina AI

Open In Colab GitHub Repository

В этом руководстве показано, как использовать вкрапления Jina AI и Milvus для решения задач поиска и извлечения информации по сходству.

Кто такая Jina AI

Jina AI, основанная в 2020 году в Берлине, является передовой компанией в области искусственного интеллекта, нацеленной на революцию в будущем искусственного интеллекта благодаря своей поисковой базе. Специализируясь на мультимодальном искусственном интеллекте, Jina AI стремится предоставить предприятиям и разработчикам возможность использовать мощь мультимодальных данных для создания стоимости и снижения затрат с помощью интегрированного набора компонентов, включая встраивания, ретрансляторы, оперативное управление и основную инфраструктуру. Передовые встраивания Jina AI отличаются высочайшей производительностью и имеют модель длиной 8192 токена, идеально подходящую для комплексного представления данных. Благодаря многоязыковой поддержке и бесшовной интеграции с ведущими платформами, такими как OpenAI, эти вставки облегчают работу с кросс-языковыми приложениями.

Встраивание Milvus и Jina AI

Для эффективного хранения и поиска этих вкраплений с точки зрения скорости и масштаба требуется специальная инфраструктура, разработанная для этой цели. Milvus - это широко известная передовая векторная база данных с открытым исходным кодом, способная работать с крупными векторными данными. Milvus обеспечивает быстрый и точный поиск векторов (вкраплений) по множеству метрик. Его масштабируемость позволяет легко работать с огромными объемами данных изображений, обеспечивая высокую производительность поисковых операций даже при росте массивов данных.

Примеры

Встраивания Jina были интегрированы в библиотеку моделей PyMilvus. Сейчас мы продемонстрируем примеры кода, чтобы показать, как использовать вкрапления Jina в действии.

Прежде чем мы начнем, нам нужно установить библиотеку моделей для PyMilvus.

$ pip install -U pymilvus
$ pip install "pymilvus[model]"

Если вы используете Google Colab, для включения только что установленных зависимостей может потребоваться перезапуск среды выполнения. (Нажмите на меню "Runtime" в верхней части экрана и выберите "Restart session" из выпадающего меню).

Встраивание общего назначения

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

from pymilvus.model.dense import JinaEmbeddingFunction

jina_api_key = "<YOUR_JINA_API_KEY>"
ef = JinaEmbeddingFunction(
    "jina-embeddings-v3", 
    jina_api_key,
    task="retrieval.passage",
    dimensions=1024
)

query = "what is information retrieval?"
doc = "Information retrieval is the process of finding relevant information from a large collection of data or documents."

qvecs = ef.encode_queries([query])  # This method uses `retrieval.query` as the task
dvecs = ef.encode_documents([doc])  # This method uses `retrieval.passage` as the task

Двуязычные вкрапления

Двуязычные модели Jina AI улучшают многоязычные платформы, глобальную поддержку и межъязыковое обнаружение контента. Разработанные для немецко-английских и китайско-английских переводов, они способствуют взаимопониманию между различными языковыми группами, упрощая взаимодействие между языками.

from pymilvus.model.dense import JinaEmbeddingFunction

jina_api_key = "<YOUR_JINA_API_KEY>"
ef = JinaEmbeddingFunction("jina-embeddings-v2-base-de", jina_api_key)

query = "what is information retrieval?"
doc = "Information Retrieval ist der Prozess, relevante Informationen aus einer großen Sammlung von Daten oder Dokumenten zu finden."

qvecs = ef.encode_queries([query])
dvecs = ef.encode_documents([doc])

Встраивание кода

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

from pymilvus.model.dense import JinaEmbeddingFunction

jina_api_key = "<YOUR_JINA_API_KEY>"
ef = JinaEmbeddingFunction("jina-embeddings-v2-base-code", jina_api_key)

# Case1: Enhanced Code Navigation
# query: text description of the functionality
# document: relevant code snippet

query = "function to calculate average in Python."
doc = """
def calculate_average(numbers):
    total = sum(numbers)
    count = len(numbers)
    return total / count
"""

# Case2: Streamlined Code Review
# query: text description of the programming concept
# document: relevante code snippet or PR

query = "pull quest related to Collection"
doc = "fix:[restful v2] parameters of create collection ..."

# Case3: Automatic Documentation Assistance
# query: code snippet you need explanation
# document: relevante document or DocsString

query = "What is Collection in Milvus"
doc = """
In Milvus, you store your vector embeddings in collections. All vector embeddings within a collection share the same dimensionality and distance metric for measuring similarity.
Milvus collections support dynamic fields (i.e., fields not pre-defined in the schema) and automatic incrementation of primary keys.
"""

qvecs = ef.encode_queries([query])
dvecs = ef.encode_documents([doc])

Семантический поиск с Jina & Milvus

Благодаря мощной функции векторного встраивания мы можем объединить встраивания, полученные с помощью моделей искусственного интеллекта Jina, с векторной базой данных Milvus Lite для выполнения семантического поиска.

from pymilvus.model.dense import JinaEmbeddingFunction
from pymilvus import MilvusClient

jina_api_key = "<YOUR_JINA_API_KEY>"
DIMENSION = 1024  # `jina-embeddings-v3` supports flexible embedding sizes (32, 64, 128, 256, 512, 768, 1024), allowing for truncating embeddings to fit your application. 
ef = JinaEmbeddingFunction(
    "jina-embeddings-v3", 
    jina_api_key,
    task="retrieval.passage",
    dimensions=DIMENSION,
)


doc = [
    "In 1950, Alan Turing published his seminal paper, 'Computing Machinery and Intelligence,' proposing the Turing Test as a criterion of intelligence, a foundational concept in the philosophy and development of artificial intelligence.",
    "The Dartmouth Conference in 1956 is considered the birthplace of artificial intelligence as a field; here, John McCarthy and others coined the term 'artificial intelligence' and laid out its basic goals.",
    "In 1951, British mathematician and computer scientist Alan Turing also developed the first program designed to play chess, demonstrating an early example of AI in game strategy.",
    "The invention of the Logic Theorist by Allen Newell, Herbert A. Simon, and Cliff Shaw in 1955 marked the creation of the first true AI program, which was capable of solving logic problems, akin to proving mathematical theorems.",
]

dvecs = ef.encode_documents(doc) # This method uses `retrieval.passage` as the task

data = [
    {"id": i, "vector": dvecs[i], "text": doc[i], "subject": "history"}
    for i in range(len(dvecs))
]

milvus_client = MilvusClient("./milvus_jina_demo.db")
COLLECTION_NAME = "demo_collection"  # Milvus collection name
if milvus_client.has_collection(collection_name=COLLECTION_NAME):
    milvus_client.drop_collection(collection_name=COLLECTION_NAME)
milvus_client.create_collection(collection_name=COLLECTION_NAME, dimension=DIMENSION)

res = milvus_client.insert(collection_name=COLLECTION_NAME, data=data)

print(res["insert_count"])

Что касается аргумента MilvusClient:

  • Установка uri в качестве локального файла, например./milvus.db, является наиболее удобным методом, поскольку он автоматически использует Milvus Lite для хранения всех данных в этом файле.
  • Если у вас большой объем данных, вы можете настроить более производительный сервер Milvus на docker или kubernetes. В этом случае используйте ури сервера, напримерhttp://localhost:19530, в качестве uri.
  • Если вы хотите использовать Zilliz Cloud, полностью управляемый облачный сервис для Milvus, настройте uri и token, которые соответствуют публичной конечной точке и ключу Api в Zilliz Cloud.

Теперь, когда все данные находятся в векторной базе Milvus, мы можем выполнить семантический поиск, сгенерировав векторное вложение для запроса и выполнив векторный поиск.

queries = "What event in 1956 marked the official birth of artificial intelligence as a discipline?"
qvecs = ef.encode_queries([queries]) # This method uses `retrieval.query` as the task

res = milvus_client.search(
    collection_name=COLLECTION_NAME,  # target collection
    data=[qvecs[0]],  # query vectors
    limit=3,  # number of returned entities
    output_fields=["text", "subject"],  # specifies fields to be returned
)[0]

for result in res:
    print(result)
{'id': 1, 'distance': 0.8802614808082581, 'entity': {'text': "The Dartmouth Conference in 1956 is considered the birthplace of artificial intelligence as a field; here, John McCarthy and others coined the term 'artificial intelligence' and laid out its basic goals.", 'subject': 'history'}}

Jina Reranker

Jina Ai также предоставляет реранкеры для дальнейшего повышения качества поиска после использования вкраплений.

from pymilvus.model.reranker import JinaRerankFunction

jina_api_key = "<YOUR_JINA_API_KEY>"

rf = JinaRerankFunction("jina-reranker-v1-base-en", jina_api_key)

query = "What event in 1956 marked the official birth of artificial intelligence as a discipline?"

documents = [
    "In 1950, Alan Turing published his seminal paper, 'Computing Machinery and Intelligence,' proposing the Turing Test as a criterion of intelligence, a foundational concept in the philosophy and development of artificial intelligence.",
    "The Dartmouth Conference in 1956 is considered the birthplace of artificial intelligence as a field; here, John McCarthy and others coined the term 'artificial intelligence' and laid out its basic goals.",
    "In 1951, British mathematician and computer scientist Alan Turing also developed the first program designed to play chess, demonstrating an early example of AI in game strategy.",
    "The invention of the Logic Theorist by Allen Newell, Herbert A. Simon, and Cliff Shaw in 1955 marked the creation of the first true AI program, which was capable of solving logic problems, akin to proving mathematical theorems.",
]

rf(query, documents)
[RerankResult(text="The Dartmouth Conference in 1956 is considered the birthplace of artificial intelligence as a field; here, John McCarthy and others coined the term 'artificial intelligence' and laid out its basic goals.", score=0.9370958209037781, index=1),
 RerankResult(text='The invention of the Logic Theorist by Allen Newell, Herbert A. Simon, and Cliff Shaw in 1955 marked the creation of the first true AI program, which was capable of solving logic problems, akin to proving mathematical theorems.', score=0.35420963168144226, index=3),
 RerankResult(text="In 1950, Alan Turing published his seminal paper, 'Computing Machinery and Intelligence,' proposing the Turing Test as a criterion of intelligence, a foundational concept in the philosophy and development of artificial intelligence.", score=0.3498658835887909, index=0),
 RerankResult(text='In 1951, British mathematician and computer scientist Alan Turing also developed the first program designed to play chess, demonstrating an early example of AI in game strategy.', score=0.2728956639766693, index=2)]

Попробуйте Managed Milvus бесплатно

Zilliz Cloud работает без проблем, поддерживается Milvus и в 10 раз быстрее.

Начать
Обратная связь

Была ли эта страница полезной?