במאמר קודם, השתמשנו בOllama בעזרת LangChain ו SingleStore. לangChain סיפקה פתרון יעיל וצר בשילוב עבור התאמה של Ollama עם SingleStore. אך מה אם נסלק LangChain? במאמר זה, אנחנו נראה דוגמה לשימוש בOllama עם SingleStore ללא הסמכה על לangChain. נראה שאף על פי שאנחנו יכולים להשיג את אותם התוצאות שהוצגו במאמר הקודם, מספר הקוד יגדל, ונדרשת לנו לנהל יותר מחלק של המידבור שלangChain מטפלת בהם בדרך כלל.
קבצי הערון השימושיים במאמר זה זמינים בGitHub.
הקדמה
מהמאמר הקודם, נעבור על אותן השלבים כדי להגדיר את הסביבה המבחנת שלנו כפי שנתתם באחד המבטים:
- הקדמה
- השתמש במכונה מודל או ב
venv
. - יצירת חשבון בסינגלסטורDB כלOU
- השתמש בקבוצת הדמות Ollamaכשם קבוצת העבודה ובשםollama-demoעבור המרחב. שימו לב לסיסמהולשםשם המארח. תרשו בהקשר מהר לגישה מכל מקום על ידי הגדרת המחסום בתוךקבוצת הדמות Ollama > מחסום.
- יצירת בסיסת נתונים
CREATE DATABASE IF NOT EXISTS ollama_demo;
- התקנת Jupyter
pip install notebook
- התקנת Ollama
curl -fsSL https://ollama.com/install.sh | sh
- משתנה סביבתי
export SINGLESTOREDB_URL="admin:<password>@<host>:3306/ollama_demo"
חילוף<password>
ו<host>
עם הערכים של הסביבה שלך.
- התחלת Jupyter
jupyter notebook
מלאת הגשת המערכים
ראשית, קבוצת חלונות:
!pip install ollama numpy pandas sqlalchemy-singlestoredb --quiet --no-warn-script-location
בהמשך, אנחנו ניטרל חברות:
import ollama
import os
import numpy as np
import pandas as pd
from sqlalchemy import create_engine, text
אנחנו ניצור תאי הכיוון בעזרת all-minilm
(45 מגabyte בזמן כתיבת המסמך):
ollama.pull("all-minilm")
{'status': 'success'}
לשימוש בLLM שלנו נשתמש בllama2
(3.8 גבייט בזמן הכתיבה):
ollama.pull("llama2")
תוצאת דוגמה:
{'status': 'success'}
הלאה, נשתמש בטקסט הדוגמה מאתר האינטרנט של Ollama:
documents = [
"Llamas are members of the camelid family meaning they're pretty closely related to vicuñas and camels",
"Llamas were first domesticated and used as pack animals 4,000 to 5,000 years ago in the Peruvian highlands",
"Llamas can grow as much as 6 feet tall though the average llama between 5 feet 6 inches and 5 feet 9 inches tall",
"Llamas weigh between 280 and 450 pounds and can carry 25 to 30 percent of their body weight",
"Llamas are vegetarians and have very efficient digestive systems",
"Llamas live to be about 20 years old, though some only live for 15 years and others live to be 30 years old"
]
df_data = []
for doc in documents:
response = ollama.embeddings(
model = "all-minilm",
prompt = doc
)
embedding = response["embedding"]
embedding_array = np.array(embedding).astype(np.float32)
df_data.append({"content": doc, "vector": embedding_array})
df = pd.DataFrame(df_data)
dimensions = len(df.at[0, "vector"])
נקבע את ההטמעות לall-minilm
ונעבור דרך כל מסמך כדי לבנות את התוכן עבור DataFrame של Pandas. בנוסף, נהפוך את ההטמעות לתבנית 32-ביט כי זו התבנית המכונה עבור סוג המידע VECTOR
של SingleStore. לבסוף, נקבע את מספר המימדים של ההטמעות עבור המסמך הראשון בDataFrame של Pandas.
הלאה, ניצור חיבור למופע של SingleStore שלנו:
connection_url = "singlestoredb://" + os.environ.get("SINGLESTOREDB_URL")
db_connection = create_engine(connection_url)
עכשיו ניצור טבלה עם העמודה vector
תוך שימוש בהמימדים שקבענו מקודם:
query = text("""
CREATE TABLE IF NOT EXISTS pandas_docs (
id BIGINT AUTO_INCREMENT NOT NULL,
content LONGTEXT,
vector VECTOR(:dimensions) NOT NULL,
PRIMARY KEY(id)
);
""")
with db_connection.connect() as conn:
conn.execute(query, {"dimensions": dimensions})
נכתוב את DataFrame של Pandas לטבלה:
df.to_sql(
"pandas_docs",
con = db_connection,
if_exists = "append",
index = False,
chunksize = 1000
)
תוצאת דוגמה:
6
עכשיו ניצור מדד כדי להתאים את האחד שיצרנו במאמר הקודם:
query = text("""
ALTER TABLE pandas_docs ADD VECTOR INDEX (vector)
INDEX_OPTIONS '{
"metric_type": "EUCLIDEAN_DISTANCE"
}';
""")
with db_connection.connect() as conn:
conn.execute(query)
נשאל שאלה, כך שהיא:
prompt = "What animals are llamas related to?"
response = ollama.embeddings(
prompt = prompt,
model = "all-minilm"
)
embedding = response["embedding"]
embedding_array = np.array(embedding).astype(np.float32)
query = text("""
SELECT content
FROM pandas_docs
ORDER BY vector <-> :embedding_array ASC
LIMIT 1;
""")
with db_connection.connect() as conn:
results = conn.execute(query, {"embedding_array": embedding_array})
row = results.fetchone()
data = row[0]
print(data)
נהפוך את הפרומט להטמעות, נוודא שההטמעות הופכות לתבנית 32-ביט ואז נבצע את שאילתת SQL שמשתמשת בסימון החזיתי <->
עבור מרחק אורכי:
תוצאת דוגמה:
Llamas are members of the camelid family meaning they're pretty closely related to vicuñas and camels
הלאה, נשתמש בLLM, ככה שהוא:
output = ollama.generate(
model = "llama2",
prompt = f"Using this data: {data}. Respond to this prompt: {prompt}"
)
print(output["response"])
תוצאת דוגמה:
Llamas are members of the camelid family, which means they are closely related to other animals such as:
1. Vicuñas: Vicuñas are small, wild camelids that are native to South America. They are known for their soft, woolly coats and are considered an endangered species due to habitat loss and poaching.
2. Camels: Camels are large, even-toed ungulates that are native to Africa and the Middle East. They are known for their distinctive humps on their backs, which store water and food for long periods of time.
Both llamas and vicuñas are classified as members of the family Camelidae, while camels are classified as belonging to the family Dromedaryae. Despite their differences in size and habitat, all three species share many similarities in terms of their physical characteristics and behavior.
סיכום
במאמר זה, שיכפלנו את הצעדים שעקבנו אחריהם במאמר הקודם והשגנו תוצאות דומות. עם זאת, היינו צריכים לכתוב סדרה של הצהרות SQL ולנהל מספר צעדים שלאונג' ציין היה עומד להתמודד עבורנו. בנוסף, עלול להיות יותר זמן ועלות על שומרון בקוד במשך הזמן הארוך לעומת הפתרון של לאנג' ציין.
השימוש בלאנג' ציין במקום כתיבת קוד מותאם אישית לגישה לבסיס נתונים מציע מספר יתרונות, כמו יעילות, נגישות ואמינות.
לאנג' ציין יש ספרית של מודולים מוכנים מראש לאינטראקציה עם בסיס נתונים, מפחית זמן ומאמץ פיתוח. מפתחים יכולים להשתמש במודולים אלה כדי ליישם במהירות מספר מנגנונים שונים של בסיס נתונים בלי להתחיל מהתחלה.
לאנג' ציין מופשט רבים מהמורכבויות הכרוכות בניהול בסיס נתונים, מאפשר למפתחים להתמקד במשימות ברמה גבוהה במקום בפרטיות הביצוע. זה משפרים את הפרודוקטיביות וזמן ההשקעה בשוק ליישומיות המונעות על בסיס נתונים.
לאנג' ציין יש קהילה גדולה, פעילה וגדלה של מפתחים, זמין ב־GitHub, ויש לו תיעוד מקיף ודוגמאות.
בסיכום, לאנג' ציין מציע למפתחים פלטפורמה חזקה, יעילה ואמינה לבניית יישומיות מונעות על בסיס נתונים, מאפשרת להם להתמ
Source:
https://dzone.com/articles/ollama-plus-singlestore-minus-langchain