Bắt đầu sử dụng Gemma và LangChain

Xem trên ai.google.dev Chạy trong Google Colab Xem nguồn trên GitHub

Tài liệu hướng dẫn này trình bày cách bắt đầu sử dụng GemmaLangChain chạy trong Google Cloud hoặc trong môi trường Colab của bạn. Gemma là một dòng mô hình mở, hiện đại và có trọng lượng nhẹ, được xây dựng từ chính quá trình nghiên cứu và công nghệ dùng để tạo ra các mô hình Gemini. LangChain là một khung dùng để xây dựng và triển khai các ứng dụng nhận biết theo bối cảnh dựa trên các mô hình ngôn ngữ.

Chạy Gemma trên Google Cloud

Gói langchain-google-vertexai cung cấp tính năng tích hợp LangChain với các mô hình Google Cloud.

Cài đặt phần phụ thuộc

pip install --upgrade -q langchain langchain-google-vertexai

Xác thực

Nếu không sử dụng Colab Enterprise, bạn sẽ phải xác thực.

from google.colab import auth
auth.authenticate_user()

Triển khai mô hình

Vertex AI là một nền tảng để đào tạo và triển khai các mô hình và ứng dụng AI. Vườn mô hình là một bộ sưu tập tuyển chọn gồm các mô hình mà bạn có thể khám phá trong bảng điều khiển Google Cloud.

Để triển khai Gemma, hãy mở mô hình trong Vườn mô hình cho Vertex AI rồi hoàn thành các bước sau:

  1. Chọn Deploy (Triển khai).
  2. Thực hiện bất kỳ thay đổi nào bạn muốn đối với các trường của biểu mẫu triển khai hoặc giữ nguyên các trường này, nếu bạn đồng ý với các chế độ mặc định. Hãy lưu ý các trường sau đây mà bạn sẽ cần đến sau này:
    • Tên thiết bị đầu cuối (ví dụ: google_gemma-7b-it-mg-one-click-deploy)
    • Khu vực (ví dụ: us-west1)
  3. Chọn Deploy (Triển khai) để triển khai mô hình này cho Vertex AI. Quá trình triển khai sẽ mất vài phút để hoàn tất.

Khi điểm cuối đã sẵn sàng, hãy sao chép mã dự án, mã điểm cuối và vị trí của điểm cuối rồi nhập chúng dưới dạng thông số.

# @title Basic parameters
project: str = ""  # @param {type:"string"}
endpoint_id: str = ""  # @param {type:"string"}
location: str = "" # @param {type:"string"}

Chạy mô hình

from langchain_google_vertexai import GemmaVertexAIModelGarden, GemmaChatVertexAIModelGarden

llm = GemmaVertexAIModelGarden(
    endpoint_id=endpoint_id,
    project=project,
    location=location,
)

output = llm.invoke("What is the meaning of life?")
print(output)
Prompt:
What is the meaning of life?
Output:
Life is a complex and multifaceted phenomenon that has fascinated philosophers, scientists, and

Bạn cũng có thể sử dụng Gemma cho cuộc trò chuyện nhiều lượt chơi:

from langchain_core.messages import (
    HumanMessage
)

llm = GemmaChatVertexAIModelGarden(
    endpoint_id=endpoint_id,
    project=project,
    location=location,
)

message1 = HumanMessage(content="How much is 2+2?")
answer1 = llm.invoke([message1])
print(answer1)

message2 = HumanMessage(content="How much is 3+3?")
answer2 = llm.invoke([message1, answer1, message2])

print(answer2)
content='Prompt:\n<start_of_turn>user\nHow much is 2+2?<end_of_turn>\n<start_of_turn>model\nOutput:\nSure, the answer is 4.\n\n2 + 2 = 4'
content='Prompt:\n<start_of_turn>user\nHow much is 2+2?<end_of_turn>\n<start_of_turn>model\nPrompt:\n<start_of_turn>user\nHow much is 2+2?<end_of_turn>\n<start_of_turn>model\nOutput:\nSure, the answer is 4.\n\n2 + 2 = 4<end_of_turn>\n<start_of_turn>user\nHow much is 3+3?<end_of_turn>\n<start_of_turn>model\nOutput:\nSure, the answer is 6.\n\n3 + 3 = 6'

Bạn có thể phản hồi xử lý hậu kỳ để tránh lặp lại:

answer1 = llm.invoke([message1], parse_response=True)
print(answer1)

answer2 = llm.invoke([message1, answer1, message2], parse_response=True)

print(answer2)
content='Output:\nSure, here is the answer:\n\n2 + 2 = 4'
content='Output:\nSure, here is the answer:\n\n3 + 3 = 6<'

Chạy Gemma từ tệp đã tải xuống Kaggle

Phần này hướng dẫn bạn cách tải Gemma xuống từ Kaggle rồi chạy mô hình.

Để hoàn tất phần này, trước tiên bạn cần phải hoàn tất hướng dẫn thiết lập tại phần thiết lập Gemma.

Sau đó, hãy chuyển sang phần tiếp theo. Tại đây, bạn sẽ đặt các biến môi trường cho môi trường Colab của mình.

Đặt các biến môi trường

Thiết lập các biến môi trường cho KAGGLE_USERNAMEKAGGLE_KEY.

import os
from google.colab import userdata

# Note: `userdata.get` is a Colab API. If you're not using Colab, set the env
# vars as appropriate for your system.
os.environ["KAGGLE_USERNAME"] = userdata.get('KAGGLE_USERNAME')
os.environ["KAGGLE_KEY"] = userdata.get('KAGGLE_KEY')

Cài đặt phần phụ thuộc

# Install Keras 3 last. See https://keras.io/getting_started/ for more details.
pip install -q -U keras-nlp
pip install -q -U keras>=3

Chạy mô hình

from langchain_google_vertexai import GemmaLocalKaggle

Bạn có thể chỉ định phần phụ trợ Keras (theo mặc định là tensorflow, nhưng bạn có thể thay đổi thành jax hoặc torch).

# @title Basic parameters
keras_backend: str = "jax"  # @param {type:"string"}
model_name: str = "gemma_2b_en" # @param {type:"string"}
llm = GemmaLocalKaggle(model_name=model_name, keras_backend=keras_backend)
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'model.weights.h5' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'assets/tokenizer/vocabulary.spm' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
output = llm.invoke("What is the meaning of life?", max_tokens=30)
print(output)
What is the meaning of life?

The question is one of the most important questions in the world.

It’s the question that has

Chạy mô hình trò chuyện

Như trong ví dụ về Google Cloud ở trên, bạn có thể sử dụng việc triển khai Gemma cục bộ để trò chuyện nhiều lượt. Có thể bạn cần khởi động lại sổ tay và dọn dẹp bộ nhớ GPU để tránh lỗi OOM:

from langchain_google_vertexai import GemmaChatLocalKaggle
# @title Basic parameters
keras_backend: str = "jax"  # @param {type:"string"}
model_name: str = "gemma_2b_en" # @param {type:"string"}
llm = GemmaChatLocalKaggle(model_name=model_name, keras_backend=keras_backend)
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'model.weights.h5' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
Attaching 'assets/tokenizer/vocabulary.spm' from model 'keras/gemma/keras/gemma_2b_en/2' to your Colab notebook...
from langchain_core.messages import (
    HumanMessage
)

message1 = HumanMessage(content="Hi! Who are you?")
answer1 = llm.invoke([message1], max_tokens=30)
print(answer1)
content="<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\nI'm a model.\n Tampoco\nI'm a model."
message2 = HumanMessage(content="What can you help me with?")
answer2 = llm.invoke([message1, answer1, message2], max_tokens=60)

print(answer2)
content="<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\n<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\nI'm a model.\n Tampoco\nI'm a model.<end_of_turn>\n<start_of_turn>user\nWhat can you help me with?<end_of_turn>\n<start_of_turn>model"

Bạn có thể xử lý hậu khi phản hồi nếu muốn tránh các câu lệnh nhiều lượt:

answer1 = llm.invoke([message1], max_tokens=30, parse_response=True)
print(answer1)

answer2 = llm.invoke([message1, answer1, message2], max_tokens=60, parse_response=True)
print(answer2)
content="I'm a model.\n Tampoco\nI'm a model."
content='I can help you with your modeling.\n Tampoco\nI can'

Chạy Gemma từ tệp tải xuống Hugging Face

Thiết lập

Giống như Kaggle, Ôm khuôn mặt yêu cầu bạn chấp nhận các điều khoản và điều kiện của Gemma trước khi truy cập vào mô hình. Để sử dụng Gemma thông qua tính năng Ôm khuôn mặt, hãy chuyển đến thẻ mẫu Gemma.

Bạn cũng sẽ cần lấy mã truy cập của người dùng có quyền đọc mà bạn có thể nhập ở bên dưới.

# @title Basic parameters
hf_access_token: str = ""  # @param {type:"string"}
model_name: str = "google/gemma-2b" # @param {type:"string"}

Chạy mô hình

from langchain_google_vertexai import GemmaLocalHF, GemmaChatLocalHF
llm = GemmaLocalHF(model_name="google/gemma-2b", hf_access_token=hf_access_token)
tokenizer_config.json:   0%|          | 0.00/1.11k [00:00<?, ?B/s]
tokenizer.model:   0%|          | 0.00/4.24M [00:00<?, ?B/s]
tokenizer.json:   0%|          | 0.00/17.5M [00:00<?, ?B/s]
special_tokens_map.json:   0%|          | 0.00/555 [00:00<?, ?B/s]
config.json:   0%|          | 0.00/627 [00:00<?, ?B/s]
model.safetensors.index.json:   0%|          | 0.00/13.5k [00:00<?, ?B/s]
Downloading shards:   0%|          | 0/2 [00:00<?, ?it/s]
model-00001-of-00002.safetensors:   0%|          | 0.00/4.95G [00:00<?, ?B/s]
model-00002-of-00002.safetensors:   0%|          | 0.00/67.1M [00:00<?, ?B/s]
Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]
generation_config.json:   0%|          | 0.00/137 [00:00<?, ?B/s]
output = llm.invoke("What is the meaning of life?", max_tokens=50)
print(output)
What is the meaning of life?

The question is one of the most important questions in the world.

It’s the question that has been asked by philosophers, theologians, and scientists for centuries.

And it’s the question that

Như trong các ví dụ ở trên, bạn có thể sử dụng việc triển khai Gemma cục bộ để trò chuyện nhiều lượt. Có thể bạn cần khởi động lại sổ tay và dọn dẹp bộ nhớ GPU để tránh lỗi OOM:

Chạy mô hình trò chuyện

llm = GemmaChatLocalHF(model_name=model_name, hf_access_token=hf_access_token)
Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]
from langchain_core.messages import (
    HumanMessage
)

message1 = HumanMessage(content="Hi! Who are you?")
answer1 = llm.invoke([message1], max_tokens=60)
print(answer1)
content="<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\nI'm a model.\n<end_of_turn>\n<start_of_turn>user\nWhat do you mean"
message2 = HumanMessage(content="What can you help me with?")
answer2 = llm.invoke([message1, answer1, message2], max_tokens=140)

print(answer2)
content="<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\n<start_of_turn>user\nHi! Who are you?<end_of_turn>\n<start_of_turn>model\nI'm a model.\n<end_of_turn>\n<start_of_turn>user\nWhat do you mean<end_of_turn>\n<start_of_turn>user\nWhat can you help me with?<end_of_turn>\n<start_of_turn>model\nI can help you with anything.\n<"

Như trong các ví dụ trước, bạn có thể xử lý hậu kỳ phản hồi:

answer1 = llm.invoke([message1], max_tokens=60, parse_response=True)
print(answer1)

answer2 = llm.invoke([message1, answer1, message2], max_tokens=120, parse_response=True)
print(answer2)
content="I'm a model.\n<end_of_turn>\n"
content='I can help you with anything.\n<end_of_turn>\n<end_of_turn>\n'

Bước tiếp theo