Embed a Single Chunk
Exit
Embed a Single Chunk
Call the Gemini embedding API and return the vector for one piece of text
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
The embedding API call
Use client.models.embed_content() to convert text into a vector. Pass the model name, the text, and a config object that sets the task type.
| Argument | Value |
|---|---|
model | "gemini-embedding-001" |
contents | The text string to embed |
config | types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT") |
The function returns a response object. Access the vector with result.embeddings[0].values.
from google.genai import types
result = client.models.embed_content(
model="gemini-embedding-001",
contents=text,
config=types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT")
)
return result.embeddings[0].values
Instructions
Complete the embed_text function. The starter code provides the signature.
- Create a variable named
result. Assign itclient.models.embed_content(model="gemini-embedding-001", contents=text, config=types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT")). - Return
result.embeddings[0].values.
import os
import pypdf
from dotenv import load_dotenv
from google import genai
from google.genai import types
def extract_text(pdf_path):
reader = pypdf.PdfReader(pdf_path)
pages = [page.extract_text() for page in reader.pages]
return "\n".join(pages)
def chunk_text(text, chunk_size=500, overlap=100):
chunks = []
for i in range(0, len(text), chunk_size - overlap):
chunks.append(text[i : i + chunk_size])
return chunks
def preview_chunks(chunks):
print(f"Total chunks: {len(chunks)}")
print(f"First chunk:\n{chunks[0]}")
def create_client():
load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
return client
def embed_text(client, text):
# Step 1: Call client.models.embed_content()
# Step 2: Return result.embeddings[0].values
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding