1. מבוא
סקירה כללית
אתם מפתחים בחברה לשיווק בתחום הנסיעות. מחלקת המכירות שלכם החליטה שהיא צריכה אפליקציית צ'אט חדשה כדי לעמוד בקצב של חברות ההזמנות והחיפוש הגדולות יותר. הם גם שמעו על AI גנרטיבי, אבל הם לא יודעים עליו הרבה. מחלקות אחרות שמעו על היוזמה הזו, והן רוצות לדעת איך היא יכולה לעזור גם להן לשפר את חוויית הלקוח.
הפעולות שתבצעו:
בשיעור ה-Lab הזה תבנו צ'אט בוט של עוזר אישי לנסיעות באמצעות המודל Gemini 2.5 Flash ב-Vertex AI.
האפליקציה צריכה:
- עוזר למשתמשים לשאול שאלות על נסיעות, להזמין נסיעות ולקבל מידע על מקומות שהם מתכננים לבקר בהם
- מספק למשתמשים דרכים לקבל עזרה לגבי תוכניות הנסיעה הספציפיות שלהם
- לאחזר נתונים בזמן אמת, כמו מזג האוויר, באמצעות כלים
תעבדו בסביבה מוגדרת מראש של Google Cloud, ספציפית ב-Cloud Shell Editor. כבר הגדרנו בשבילכם ממשק משתמש בסיסי לאפליקציית אינטרנט, וגם את ההרשאות שצריך כדי לגשת ל-Vertex AI. האפליקציה הזו פותחה באמצעות Streamlit.
מה תלמדו
בשיעור ה-Lab הזה תלמדו איך לבצע את המשימות הבאות:
- בודקים את פלטפורמת Vertex AI כדי לזהות מודלים זמינים של AI גנרטיבי.
- פיתוח ב-Cloud Shell Editor ובטרמינל
- להשתמש ב-Gemini Code Assist כדי להבין את הקוד.
- משתמשים ב-Vertex AI SDK ב-Python כדי לשלוח הנחיות ל-Gemini LLM ולקבל ממנו תשובות.
- להשתמש בהנדסת פרומפטים בסיסית (הוראות למערכת, פרמטרים של מודלים) כדי להתאים אישית את הפלט של Gemini LLM.
- בודקים ומשפרים באופן איטרטיבי אפליקציית צ'אט שמבוססת על LLM על ידי שינוי ההנחיות והפרמטרים כדי לשפר את התשובות.
- להגדיר כלים ולהשתמש בהם במודל Gemini כדי להפעיל קריאה להפעלת פונקציות.
- לארגן את הקוד מחדש כדי להשתמש בשיחת צ'אט עם שמירת מצב, שיטה מומלצת לאפליקציות מבוססות-שיחה.
2. הגדרת הפרויקט
חשבון Google
אם אין לכם חשבון Google אישי, אתם צריכים ליצור חשבון Google.
להשתמש בחשבון אישי במקום בחשבון של מקום עבודה או מוסד לימודים.
כניסה למסוף Google Cloud
נכנסים למסוף Google Cloud באמצעות חשבון Google אישי.
הפעלת חיוב
מימוש קרדיטים ב-Google Cloud (אופציונלי)
כדי להפעיל את הסדנה הזו, צריך חשבון לחיוב עם קרדיט. כדי להתחיל, השתמשו בקרדיטים מהבאנר שבחלק העליון של ה-Codelab הזה. אם כבר יש לכם חשבון לחיוב, אתם יכולים לדלג על השלב הזה.
הגדרת חשבון חיוב אישי
אם הגדרתם חיוב באמצעות קרדיטים ל-Google Cloud, אתם יכולים לדלג על השלב הזה.
כדי להגדיר חשבון חיוב אישי, צריך להיכנס לכאן כדי להפעיל את החיוב במסוף Cloud.
כמה הערות:
- השלמת ה-Lab הזה אמורה לעלות פחות מ-1 דולר ארה"ב במשאבי Cloud.
- כדי למנוע חיובים נוספים, אתם יכולים למחוק את המשאבים לפי השלבים שבסוף ה-Lab.
- משתמשים חדשים זכאים לתקופת ניסיון בחינם בשווי 300$.
יצירת פרויקט (אופציונלי)
אם אין לכם פרויקט קיים שאתם רוצים להשתמש בו ב-Lab הזה, אתם יכולים ליצור פרויקט חדש כאן.
3. פתיחת Cloud Shell Editor
- לוחצים על הקישור הזה כדי לעבור ישירות אל Cloud Shell Editor.
- אם תתבקשו לאשר בשלב כלשהו היום, לחצו על Authorize כדי להמשיך.

- אם הטרמינל לא מופיע בתחתית המסך, פותחים אותו:
- לוחצים על הצגה.
- לוחצים על Terminal (מסוף).

- בטרמינל, מגדירים את הפרויקט באמצעות הפקודה הבאה:
gcloud config set project [PROJECT_ID]- דוגמה:
gcloud config set project lab-project-id-example - אם אתם לא זוכרים את מזהה הפרויקט, אתם יכולים להציג את כל מזהי הפרויקטים באמצעות הפקודה הבאה:
gcloud projects list
- דוגמה:
- ההודעה הבאה אמורה להופיע:
Updated property [core/project].
4. הפעלת ממשקי ה-API
כדי להשתמש ב-Vertex AI SDK ולתקשר עם מודל Gemini, צריך להפעיל את Vertex AI API בפרויקט בענן ב-Google Cloud.
- בטרמינל, מפעילים את ממשקי ה-API:
gcloud services enable \ aiplatform.googleapis.com
מבוא ל-Vertex AI SDK ל-Python
כדי ליצור אינטראקציה עם מודלים שמתארחים ב-Vertex AI מאפליקציית Python, משתמשים ב-Vertex AI SDK ל-Python. ה-SDK הזה מפשט את התהליך של שליחת הנחיות, הגדרת פרמטרים של מודלים וקבלת תשובות, בלי שתצטרכו להתמודד ישירות עם המורכבות של הקריאות ל-API.
במאמר מבוא ל-Vertex AI SDK ל-Python | Google Cloud יש מידע מקיף על Vertex AI SDK ל-Python.
5. יצירת סביבה וירטואלית והתקנת יחסי תלות
לפני שמתחילים פרויקט ב-Python, מומלץ ליצור סביבה וירטואלית. כך מבודדים את יחסי התלות של הפרויקט ומונעים התנגשויות עם פרויקטים אחרים או עם חבילות Python הגלובליות של המערכת.
- יוצרים תיקייה בשם
wanderbotכדי לאחסן את הקוד של אפליקציית העוזר האישי לנסיעות. מריצים את הקוד הבא במסוף:mkdir wanderbot && cd wanderbot - יוצרים ומפעילים סביבה וירטואלית:
תראו את הקידומת (uv venv --python 3.12 source .venv/bin/activatewanderbot) בשורת הפקודה של הטרמינל, שמציינת שהסביבה הווירטואלית פעילה. זה ייראה בערך כך:
6. יצירת קובצי התחלה ל-wanderbot
- יוצרים ופותחים קובץ
app.pyחדש לאפליקציה. מריצים את הקוד הבא במסוף: הפקודהcloudshell edit app.pycloudshell editתפתח את הקובץapp.pyבכלי העריכה שמעל הטרמינל. - מדביקים את הקוד הבא לתחילת הדרך של האפליקציה ב-
app.py:import streamlit as st from google import genai from google.genai import types import requests import logging # --- Defining variables and parameters --- REGION = "global" PROJECT_ID = None # TODO: Insert Project ID GEMINI_MODEL_NAME = "gemini-3.5-flash" temperature = .2 top_p = 0.95 system_instructions = None # --- Tooling --- # TODO: Define the weather tool function declaration # TODO: Define the get_current_temperature function # --- Initialize the Vertex AI Client --- try: # TODO: Initialize the Vertex AI client print(f"VertexAI Client initialized successfully with model {GEMINI_MODEL_NAME}") except Exception as e: st.error(f"Error initializing VertexAI client: {e}") st.stop() # TODO: Add the get_chat function here in Task 15. # --- Call the Model --- def call_model(prompt: str, model_name: str) -> str: """ This function interacts with a large language model (LLM) to generate text based on a given prompt and system instructions. It will be replaced in a later step with a more advanced version that handles tooling. """ try: # TODO: Prepare the content for the model # TODO: Define generate_content configuration (needed for system instructions and parameters) # TODO: Define response logging.info(f"[call_model_response] LLM Response: \"{response.text}\"") # TODO: Uncomment the below "return response.text" line # return response.text except Exception as e: return f"Error: {e}" # --- Presentation Tier (Streamlit) --- # Set the title of the Streamlit application st.title("Travel Chat Bot") # Initialize session state variables if they don't exist if "messages" not in st.session_state: # Initialize the chat history with a welcome message st.session_state["messages"] = [ {"role": "assistant", "content": "How can I help you today?"} ] # Display the chat history for msg in st.session_state.messages: st.chat_message(msg["role"]).write(msg["content"]) # Get user input if prompt := st.chat_input(): # Add the user's message to the chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display the user's message st.chat_message("user").write(prompt) # Show a spinner while waiting for the model's response with st.spinner("Thinking..."): # Get the model's response using the call_model function model_response = call_model(prompt, GEMINI_MODEL_NAME) # Add the model's response to the chat history st.session_state.messages.append( {"role": "assistant", "content": model_response} ) # Display the model's response st.chat_message("assistant").write(model_response) - יוצרים ופותחים קובץ
requirements.txtחדש לקוד האפליקציה. מריצים את הקוד הבא במסוף: הפקודהcloudshell edit requirements.txtcloudshell editתפתח את הקובץrequirements.txtבכלי העריכה שמעל הטרמינל. - מדביקים את הקוד הבא לתחילת הדרך באפליקציה ב-
requirements.txt.google-genai streamlit requests - מתקינים את יחסי התלות הנדרשים של Python לפרויקט הזה. מריצים את הקוד הבא במסוף:
uv pip install -r requirements.txt
7. עיון בקוד
הקבצים שיצרתם כוללים ממשק משתמש בסיסי של אפליקציית צ'אט. זה כולל את הנתונים של:
app.py: זה הקובץ שנעבוד בו. הוא מכיל כרגע את הפרטים הבאים:- ייבואים נחוצים
- משתני סביבה ופרמטרים (חלק מהם הם פלייסהולדרים)
- פונקציית
call_modelריקה, שאותה נמלא - קוד Streamlit לאפליקציית הצ'אט של ממשק המשתמש
requirements.txt:- כולל את דרישות ההתקנה להפעלת
app.py
- כולל את דרישות ההתקנה להפעלת
עכשיו הגיע הזמן לבדוק את הקוד.
פתיחת הצ'אט של Gemini Code Assist
הצ'אט של Gemini Code Assist אמור להיות פתוח בחלונית בצד שמאל ב-Cloud Shell Editor. אם הצ'אט של Gemini Code Assist לא פתוח, אתם יכולים לפתוח אותו כך:
- ללחוץ על הכפתור של Gemini Code Assist (
) בחלק העליון של המסך. - לוחצים על Open Gemini Code Assist Chat.

איך משתמשים ב-Gemini Code Assist כדי להבין את הקוד
אתם יכולים להשתמש ב-Gemini Code Assist Chat כדי להבין טוב יותר את הקוד.
- מדגישים או בוחרים את קטע הקוד הרצוי.
- מקלידים "הסבר את הקוד הזה" בשיחה עם Gemini.
- כדי לשלוח, לוחצים על Enter.

8. הפעלת אפליקציית האינטרנט
לפני שמחברים את האפליקציה הזו למודל שפה גדול (LLM), מפעילים אותה כדי לראות איך היא מתנהגת בהתחלה.
- בספרייה
wanderbot, מריצים את הפקודה הבאה בטרמינל כדי להפעיל את אפליקציית Streamlit ולהפוך אותה לנגישה באופן מקומי בסביבת מעטפת Cloud Shell: צריך להשאיר את חלון הטרמינל הזה פתוח, כי אפליקציית Streamlit תמשיך לפעול. אפשר לפתוח חלון טרמינל חדש ב-Cloud Shell כדי להריץ פקודות אחרות.streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080 - אחרי שמריצים את הפקודה, לוחצים על הכפתור Web Preview בחלק העליון של Cloud Shell Editor ובוחרים באפשרות Preview on port 8080.

יופיע ממשק צ'אט פשוט של אפליקציית הנסיעות. - מקלידים הודעה כלשהי (למשל
Hi!) ולוחצים על Enter.
ההודעה תופיע בהיסטוריית הצ'אט, אבל תוצג הודעת שגיאה במקום תשובה מהעוזר הדיגיטלי. הסיבה לכך היא שהאפליקציה עדיין לא מחוברת למודל שפה גדול (LLM). שימו לב להתנהגות הזו כדי להבין את נקודת ההתחלה של ה-Lab.
9. אתחול הלקוח של Vertex AI
עיון במודלים הזמינים ב-Vertex AI
פלטפורמת Vertex AI של Google Cloud מספקת גישה למגוון מודלים של AI גנרטיבי. לפני שמשלבים פתרון, אפשר לבדוק את האפשרויות הזמינות במסוף Google Cloud.
- במסוף Google Cloud, עוברים אל Model Garden. כדי לעשות את זה, מחפשים את Model Garden בשורת החיפוש שבחלק העליון של המסך ובוחרים ב-Vertex AI.(
) - מעיינים במודלים הזמינים. אפשר לסנן לפי קריטריונים כמו אופני שימוש, סוגי משימות ותכונות.
בשיעור ה-Lab הזה תשתמשו במודל Gemini 2.5 Flash, שמתאים לפיתוח אפליקציות צ'אט רספונסיביות בגלל המהירות שלו.
אתחול הלקוח של Vertex AI
עכשיו תשנו את הקטע --- Initialize the Vertex AI Client --- בקובץ app.py כדי להפעיל את הלקוח של Vertex AI. אובייקט הלקוח הזה ישמש לשליחת הנחיות למודל.
- פותחים את
app.pyב-Cloud Shell Editor. - ב-
app.py, מחפשים את השורהPROJECT_ID = None. - מחליפים את
Noneבמזהה הפרויקט ב-Google Cloud, במירכאות. (לדוגמה,PROJECT_ID = "google-cloud-labs")
אם אתם לא זוכרים את מזהה הפרויקט, אתם יכולים להציג את כל מזהי הפרויקטים באמצעות:gcloud projects list | awk '/PROJECT_ID/{print $2}' - הגדרת הלקוח: בתוך הבלוק
try, מאתחלים את הלקוח.client = genai.Client( enterprise=True, project=PROJECT_ID, location=REGION, )
אתחול לקוח מעודכן
בשלב הזה, הקטע Initialize the Client ייראה כך:
# --- Initialize the Client ---
try:
client = genai.Client(
enterprise=True,
project=PROJECT_ID,
location=REGION,
)
print(f"GenAI Client initialized successfully with model {GEMINI_MODEL_NAME}")
except Exception as e:
st.error(f"Error initializing GenAI client: {e}")
st.stop()
10. הכנת הנתונים וקריאה למודל
עכשיו תכינו את התוכן שיישלח למודל, ותבצעו קריאה למודל Gemini.
- מוצאים את הקטע
--- Call the Model ---שבו מוגדרת הפונקציהcall_model. - הגדרת התוכן: בקטע
# TODO: Prepare the content for the model, מגדירים את תוכן הקלט שיישלח למודל. בהנחיה בסיסית, זה יהיה הקלט של המשתמש.contents = [prompt] - הגדרת התגובה: מדביקים את הקוד הזה מתחת ל-
# TODO: Define response.response = client.models.generate_content( model=model_name, contents=contents, ) - החזרת התשובה: מבטלים את הסימון של השורה הבאה:
return response.text - בודקים את השורה שבה מתבצעת הקריאה לפונקציה
call_model, בחלק התחתון של הקובץ בבלוקwith. אם אתם לא מבינים מה קורה כאן, הדגישו את השורה ובקשו מ-Gemini Code Assist להסביר.
דרך מפורשת יותר להגדיר את contents
הדרך שלמעלה להגדרת contents פועלת כי ה-SDK חכם מספיק כדי להבין שרשימה שמכילה מחרוזות מייצגת קלט טקסט של משתמש. הוא מעצב אותו באופן אוטומטי בצורה שמתאימה ל-API של המודל.
עם זאת, הדרך המפורשת והבסיסית יותר לבנות קלט כוללת שימוש באובייקטים מסוג types.Part ו-types.Content, באופן הבא:
user_message_parts = [types.Part.from_text(text=prompt)]
contents = [
types.Content(
role="user", # Indicates the content is from the user
parts=user_message_parts, # A list, allowing multiple types of content
),
]
הפונקציה call_model עודכנה
בשלב הזה, הפונקציה call_model אמורה להיראות כך:
def call_model(prompt: str, model_name: str) -> str:
"""
This function interacts with a large language model (LLM) to generate text based on a given prompt and system instructions.
It will be replaced in a later step with a more advanced version that handles tooling.
"""
try:
contents = [prompt]
# TODO: Define generate_content configuration (needed later for system instructions and parameters)
response = client.models.generate_content(
model=model_name,
contents=contents,
)
logging.info(f"[call_model_response] LLM Response: \"{response.text}\"")
return response.text
except Exception as e:
return f"Error: {e}"
11. בדיקת האפליקציה המקושרת
- בטרמינל, מסיימים את התהליך שפועל כרגע (CTRL+C).
- מריצים מחדש את הפקודה כדי להפעיל שוב את אפליקציית Streamlit.
streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080 - מרעננים את אפליקציית Streamlit. אם אפליקציית Streamlit עדיין פועלת, אתם יכולים פשוט לרענן את דף התצוגה המקדימה באינטרנט בדפדפן.
- עכשיו, מקלידים שאלה בשדה הקלט של הצ'אט, למשל:
What is the best time of year to go to Iceland? - לוחצים על Enter.
באפליקציה אמורה להופיע ההודעה שלכם, סמל של "חושב…" ואז תשובה שנוצרה על ידי מודל Gemini. אם כן, סימן שקישרתם בהצלחה את אפליקציית האינטרנט שלכם ל-LLM ב-Vertex AI. 🙌 🥳
12. הגדרת הוראות מערכת
החיבור הבסיסי עובד, אבל האיכות והסגנון של התשובות של ה-LLM מושפעים מאוד מהקלט שהוא מקבל. הנדסת פרומפטים היא התהליך של תכנון ושיפור של הקלט (הפרומפטים) כדי להנחות את המודל ליצור את הפלט הרצוי.
כדי לעשות את זה, קודם כל יוצרים הוראות מערכת ומעבירים אותן למודל.
אתם יכולים להשתמש ב-Ask Gemini כדי ליצור הוראות מערכת מועילות.
- ב-
app.py, מאתרים את המשתנהsystem_instructions, שמוגדר כרגע כ-None. אתם תחליפו אתsystem_instructions = NoneNoneבמחרוזת מרובת שורות שמספקת הוראות לבוט של עוזר הנסיעות. - שואלים את Gemini Code Assist: מזינים את ההנחיה הבאה ב-Gemini Code Assist (או יוצרים הנחיה משלכם):
I am a developer at a travel marketing company, and my sales department has decided that they need a new chat application to keep up with the bigger booking and search companies. I'm building a simple travel assistant chatbot using the Gemini 2.5 Flash model on Vertex AI. The application should: - Helps users ask questions about travel, book travel, and learn about places they are going to go - Provides users ways to get help about their specific travel plans - Provides all this in a production quality way (multiple environments, logging and monitoring, etc.) Please create system instructions appropriate for that chat app. Be thorough. Do not alter the code in any way beyond providing me with system instructions. - הגדרת
system_instructions: מגדירים אתsystem_instructionsכך שיהיה שווה להוראות המערכת שיצרתם באמצעות Gemini Code Assist. אתם יכולים גם להשתמש בהוראות המערכת האלה, שנוצרו על ידי Gemini באמצעות הנחיה דומה.system_instructions = """ You are a sophisticated travel assistant chatbot designed to provide comprehensive support to users throughout their travel journey. Your capabilities include answering travel-related questions, assisting with booking travel arrangements, offering detailed information about destinations, and providing support for existing travel plans. **Core Functionalities:** 1. **Travel Information and Recommendations:** * Answer user inquiries about travel destinations, including popular attractions, local customs, visa requirements, weather conditions, and safety advice. * Provide personalized recommendations for destinations, activities, and accommodations based on user preferences, interests, and budget. * Offer insights into the best times to visit specific locations, considering factors like weather, crowds, and pricing. * Suggest alternative destinations or activities if the user's initial choices are unavailable or unsuitable. 2. **Booking Assistance:** * Facilitate the booking of flights, hotels, rental cars, tours, and activities. * Search for available options based on user-specified criteria such as dates, destinations, budget, and preferences. * Present clear and concise information about available options, including pricing, amenities, and booking terms. * Guide users through the booking process, ensuring accurate information and secure transactions. * Provide booking confirmations and relevant details, such as booking references and contact information. 3. **Travel Planning and Itinerary Management:** * Assist users in creating detailed travel itineraries, including flights, accommodations, activities, and transportation. * Offer suggestions for optimizing travel plans, such as minimizing travel time or maximizing sightseeing opportunities. * Provide tools for managing and modifying existing itineraries, including adding or removing activities, changing booking dates, or upgrading accommodations. * Offer reminders and notifications for upcoming travel events, such as flight check-in or tour departure times. 4. **Customer Support and Troubleshooting:** * Provide prompt and helpful support to users with questions or issues related to their travel plans. * Assist with resolving booking discrepancies, cancellations, or modifications. * Offer guidance on travel-related emergencies, such as lost luggage or travel delays. * Provide access to relevant contact information for airlines, hotels, and other travel providers. **Interaction Guidelines:** * **Professionalism:** Maintain a polite, respectful, and professional tone in all interactions. * **Clarity and Conciseness:** Provide clear, concise, and easy-to-understand information. Avoid jargon or technical terms unless necessary and always explain them. * **Accuracy:** Ensure all information provided is accurate and up-to-date. Double-check details before sharing them with users. If unsure about something, admit that you don't know and offer to find the information. * **Personalization:** Tailor your responses and recommendations to the specific needs and preferences of each user. * **Proactive Assistance:** Anticipate user needs and offer relevant information or suggestions proactively. * **Error Handling:** Gracefully handle user errors or misunderstandings. Provide helpful guidance and alternative options when necessary. * **Confidentiality:** Respect user privacy and handle personal information with the utmost confidentiality and in compliance with data protection regulations. **Example Interactions:** **User:** "I want to go on a beach vacation in the Caribbean. I have a budget of $2000 per person for a week." **Chatbot:** "Certainly! The Caribbean offers many beautiful beach destinations within your budget. Some popular options include Punta Cana in the Dominican Republic, Cancun in Mexico, and Montego Bay in Jamaica. These destinations offer stunning beaches, all-inclusive resorts, and various activities. Would you like me to search for flights and accommodations for these locations based on your travel dates?" **User:** "My flight is delayed. What should I do?" **Chatbot:** "I'm sorry to hear about the delay. Please check with the airline for the updated departure time and any assistance they can offer. You may be entitled to compensation or rebooking options depending on the length of the delay and the airline's policy. Do you have your flight number handy so I can look up the current status for you?" **User:** "Tell me about the best time to visit Japan." **Chatbot:** "Japan is a fantastic destination with distinct seasons offering unique experiences. Spring (March-May) is famous for the beautiful cherry blossoms, while autumn (September-November) boasts stunning fall foliage. Both seasons have pleasant temperatures, making them ideal for sightseeing. Summer (June-August) can be hot and humid, but it's a great time for festivals and outdoor activities in the mountains. Winter (December-February) offers opportunities for skiing and snowboarding in the Japanese Alps, though some areas may experience heavy snowfall. To recommend the best time for you, could you tell me what you'd like to experience in Japan?" By following these instructions, you will be able to provide exceptional travel assistance and create a positive experience for every user. """ - מגדירים את generate_content: מאתחלים אובייקט הגדרה, שאליו מעבירים את ההוראות האלה למערכת. מכיוון ש-
system_instructionsמוגדר באופן גלובלי בסקריפט שלנו, הפונקציה יכולה לגשת אליו ישירות.generate_content_config = types.GenerateContentConfig( system_instruction=[ types.Part.from_text(text=system_instructions) ], ) logging.info(f"[generate_config_details] System Instruction: {generate_content_config.system_instruction[0].text}") - כדי להוסיף את הוראות המערכת לתשובה, מוסיפים פרמטר
configל-methodgenerate_content, ומגדירים אותו כך שיהיה שווה לאובייקטgenerate_content_configשנוצר למעלה.response = client.models.generate_content( model=model_name, contents=contents, config=generate_content_config, # This is the new line )
הפונקציה call_model עודכנה
הפונקציה המלאה call_model נראית עכשיו כך:
def call_model(prompt: str, model_name: str) -> str:
"""
This function interacts with a large language model (LLM) to generate text based on a given prompt and system instructions.
It will be replaced in a later step with a more advanced version that handles tooling.
"""
try:
contents = [prompt]
generate_content_config = types.GenerateContentConfig(
system_instruction=[
types.Part.from_text(text=system_instructions)
],
)
logging.info(f"[generate_config_details] System Instruction: {generate_content_config.system_instruction[0].text}")
response = client.models.generate_content(
model=model_name,
contents=contents,
config=generate_content_config,
)
logging.info(f"[call_model_response] LLM Response: \"{response.text}\"")
return response.text
except Exception as e:
return f"Error: {e}"
13. בדיקת האפליקציה עם הוראות המערכת
- בטרמינל, מסיימים את התהליך שפועל כרגע (CTRL+C).
- מריצים מחדש את הפקודה כדי להפעיל שוב את אפליקציית Streamlit.
streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080 - מרעננים את אפליקציית Streamlit. אם אפליקציית Streamlit עדיין פועלת, אתם יכולים פשוט לרענן את דף התצוגה המקדימה באינטרנט בדפדפן.
- נסו לשאול את אותה שאלה כמו קודם:
What is the best time of year to go to Iceland? - לוחצים על Enter.
השוו בין התשובה שקיבלתם הפעם לתשובה שקיבלתם בפעם הקודמת.
14. הגדרת כלי למזג אוויר
עד עכשיו, הצ'אט בוט שלנו הוא בעל ידע, אבל הידע שלו מוגבל לנתונים שהוא אומן לפיהם. אין לו גישה למידע בזמן אמת. לבוט של נסיעות, היכולת לאחזר נתונים בזמן אמת כמו תחזיות מזג אוויר היא יתרון עצום.
כאן נכנסת לתמונה הפעלת כלים, שנקראת גם קריאה להפעלת פונקציות. אנחנו יכולים להגדיר קבוצה של כלים (פונקציות Python) שה-LLM יכול לבחור להפעיל כדי לקבל מידע חיצוני.
איך הכלים פועלים
- אנחנו מתארים למודל את הכלים שלנו, כולל מה הם עושים ואילו פרמטרים הם מקבלים.
- המשתמש שולח הנחיה (למשל, "מה מזג האוויר בלונדון?").
- המודל מקבל את ההנחיה ומזהה שהמשתמש שואל על משהו שהוא יכול לברר באמצעות אחד מהכלים שלו.
- במקום להגיב בטקסט, המודל מגיב באובייקט
function_callמיוחד, שמציין לאיזה כלי הוא רוצה לקרוא ועם אילו ארגומנטים. - קוד ה-Python שלנו מקבל את ה-
function_callהזה, מריץ את הפונקציהget_current_temperatureבפועל עם הארגומנטים שסופקו, ומקבל את התוצאה (למשל, 15°C). - אנחנו שולחים את התוצאה הזו בחזרה למודל.
- המודל מקבל את התוצאה ויוצר תשובה בשפה טבעית למשתמש (לדוגמה, "הטמפרטורה הנוכחית בלונדון היא 15°C").
התהליך הזה מאפשר למודל לענות על שאלות שהן הרבה מעבר לנתוני האימון שלו, וכך הוא הופך לעוזר אישי הרבה יותר יעיל ושימושי.
הגדרת כלי למזג אוויר
אם מטיילים מחפשים המלצות לפעילויות, ומתלבטים בין פעילויות שמושפעות ממזג האוויר, כלי מזג האוויר יכול לעזור להם. בואו ניצור כלי למודל שלנו כדי לקבל את מזג האוויר הנוכחי. אנחנו צריכים שני חלקים: הצהרת פונקציה שמתארת את הכלי למודל, והפונקציה עצמה ב-Python שמטמיעה אותו.
- ב-
app.py, מוצאים את התגובה# TODO: Define the weather tool function declaration. - מתחת להערה הזו, מוסיפים את המשתנה
weather_function. זהו מילון שמספק למודל את כל מה שהוא צריך לדעת על המטרה, הפרמטרים והארגומנטים הנדרשים של הפונקציה.weather_function = { "name": "get_current_temperature", "description": "Gets the current temperature for a given location.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name, e.g. San Francisco", }, }, "required": ["location"], }, } - עכשיו מוצאים את התגובה
# TODO: Define the get_current_temperature function. מתחתיה, מוסיפים את קוד ה-Python הבא. הפונקציה הזו:- שולחים קריאה ל-Geocoding API כדי לקבל את הקואורדינטות של המיקום.
- משתמשים בקואורדינטות האלה כדי לשלוח קריאה ל-Weather API.
- מחזירים מחרוזת פשוטה עם הטמפרטורה והיחידה.
def get_current_temperature(location: str) -> str: """Gets the current temperature for a given location.""" try: # --- Get Latitude and Longitude for the location --- geocode_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1&language=en&format=json" geocode_response = requests.get(geocode_url) geocode_data = geocode_response.json() if not geocode_data.get("results"): return f"Could not find coordinates for {location}." lat = geocode_data["results"][0]["latitude"] lon = geocode_data["results"][0]["longitude"] # --- Get Weather for the coordinates --- weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true" weather_response = requests.get(weather_url) weather_data = weather_response.json() temperature = weather_data["current_weather"]["temperature"] unit = "°C" return f"{temperature}{unit}" except Exception as e: return f"Error fetching weather: {e}"
15. שכתוב קוד לצ'אט ולכלים
הפונקציה הנוכחית שלנו, call_model, משתמשת בקריאה פשוטה וחד-פעמית ל-generate_content. זה מעולה לשאלות בודדות, אבל לא אידיאלי לשיחה עם כמה סבבים, במיוחד כזו שכוללת שימוש בכלים.
שיטה טובה יותר היא להשתמש בשיחת צ'אט, ששומרת על ההקשר של השיחה. עכשיו נארגן את הקוד מחדש כדי להשתמש בשיחת צ'אט, שנדרשת כדי להטמיע את הכלים בצורה נכונה.
- מוחקים את הפונקציה הקיימת
call_model. נחליף אותו בגרסה מתקדמת יותר. - במקומה, מוסיפים את הפונקציה החדשה
call_modelמקטע הקוד שבהמשך. הפונקציה החדשה הזו מכילה את הלוגיקה לטיפול בלולאת קריאת ה-API לכלי שדיברנו עליה קודם. שימו לב שיש בו כמה הערות TODO שנשלים בשלבים הבאים.# --- Call the Model --- def call_model(prompt: str, model_name: str) -> str: """ This function interacts with a large language model (LLM) to generate text based on a given prompt. It maintains a chat session and handles function calls from the model to external tools. """ try: # TODO: Get the existing chat session or create a new one. message_content = prompt # Start the tool-calling loop while True: # TODO: Send the message to the model. # Check if the model wants to call a tool has_tool_calls = False for part in response.candidates[0].content.parts: if part.function_call: has_tool_calls = True function_call = part.function_call logging.info(f"Function to call: {function_call.name}") logging.info(f"Arguments: {function_call.args}") # TODO: Call the appropriate function if the model requests it. elif part.text: logging.info("No function call found in the response.") logging.info(response.text) # If no tool call was made, break the loop if not has_tool_calls: break # TODO: Return the model's final text response. except Exception as e: return f"Error: {e}" - עכשיו נוסיף פונקציית עזר לניהול שיחת הצ'אט. מעל הפונקציה החדשה
call_model, מוסיפים את הפונקציהget_chat. הפונקציה הזו תיצור שיחת צ'אט חדשה עם הוראות המערכת והגדרות הכלים שלנו, או תאחזר את השיחה הקיימת. זו שיטה טובה לארגון הקוד.def get_chat(model_name: str): if f"chat-{model_name}" not in st.session_state: # TODO: Define the tools configuration for the model # TODO: Define the generate_content configuration, including tools # TODO: Create a new chat session st.session_state[f"chat-{model_name}"] = chat return st.session_state[f"chat-{model_name}"]
עכשיו הגדרתם את התשתית ללוגיקה המתקדמת של הצ'אט, שכוללת כלים.
16. הטמעת הלוגיקה של קריאת API לכלי
עכשיו נמלא את TODOs כדי שהלוגיקה של קריאת ה-API לכלי תפעל באופן מלא.
הטמעה של get_chat
- בפונקציה
get_chat, מתחת לתגובה# TODO: Define the tools configuration..., מגדירים את האובייקטtoolsעל ידי יצירת מופע שלtypes.Toolמההצהרהweather_function.tools = types.Tool(function_declarations=[weather_function]) - בקטע
# TODO: Define the generate_content configuration..., מגדירים אתgenerate_content_configומוודאים שהאובייקטtoolsמועבר למודל. ככה המודל לומד על הכלים שהוא יכול להשתמש בהם.generate_content_config = types.GenerateContentConfig( system_instruction=[types.Part.from_text(text=system_instructions)], tools=[tools] # Pass the tool definition here ) - בקטע
# TODO: Create a new chat session, יוצרים את אובייקט הצ'אט באמצעותclient.chats.create(), ומעבירים את שם המודל וההגדרות האישיות שלנו.chat = client.chats.create( model=model_name, config=generate_content_config, )
הטמעה של call_model
- בקטע
# TODO: Get the existing chat session...בפונקציהcall_model, מפעילים את פונקציית העזר החדשהget_chat.chat = get_chat(model_name) - עכשיו מחפשים את
# TODO: Send the message to the model. שולחים את ההודעה של המשתמש באמצעות השיטהchat.send_message().response = chat.send_message(message_content) - מחפשים את
# TODO: Call the appropriate function.... כאן אנחנו בודקים איזו פונקציה המודל רוצה ומפעילים אותה.
if function_call.name == "get_current_temperature":
result = get_current_temperature(**function_call.args)
function_response_part = types.Part.from_function_response(
name=function_call.name,
response={"result": result},
)
message_content = [function_response_part]
- לבסוף, מוצאים את
# TODO: Return the model's final text responseומוסיפים את פקודת החזרה.return response.text
הפונקציה get_chat עודכנה
הפונקציה המעודכנת get_chat אמורה להיראות עכשיו כך:
def get_chat(model_name: str):
if f"chat-{model_name}" not in st.session_state:
# Tools
tools = types.Tool(function_declarations=[weather_function])
# Initialize a configuration object
generate_content_config = types.GenerateContentConfig(
system_instruction=[types.Part.from_text(text=system_instructions)],
tools=[tools]
)
chat = client.chats.create(
model=model_name,
config=generate_content_config,
)
st.session_state[f"chat-{model_name}"] = chat
return st.session_state[f"chat-{model_name}"]
הפונקציה call_model עודכנה
הפונקציה המעודכנת call_model אמורה להיראות עכשיו כך:
def call_model(prompt: str, model_name: str) -> str:
try:
chat = get_chat(model_name)
message_content = prompt
while True:
response = chat.send_message(message_content)
has_tool_calls = False
for part in response.candidates[0].content.parts:
if part.function_call:
has_tool_calls = True
function_call = part.function_call
logging.info(f"Function to call: {function_call.name}")
logging.info(f"Arguments: {function_call.args}")
if function_call.name == "get_current_temperature":
result = get_current_temperature(**function_call.args)
function_response_part = types.Part.from_function_response(
name=function_call.name,
response={"result": result},
)
message_content = [function_response_part]
elif part.text:
logging.info("No function call found in the response.")
logging.info(response.text)
if not has_tool_calls:
break
return response.text
except Exception as e:
return f"Error: {e}"
17. בדיקת האפליקציה עם הכלים המופעלים
רוצה לראות את התכונה החדשה בפעולה?
- בטרמינל, מסיימים את התהליך שפועל כרגע (CTRL+C).
- מריצים מחדש את הפקודה כדי להפעיל שוב את אפליקציית Streamlit.
streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080 - מרעננים את אפליקציית Streamlit. אם אפליקציית Streamlit עדיין פועלת, אתם יכולים פשוט לרענן את דף התצוגה המקדימה באינטרנט בדפדפן.
- עכשיו, שואלים שאלה שאמורה להפעיל את הכלי החדש, למשל:
I'm looking for something to do in New York today. What do you recommend? Would it be a good day to go to Ellis Island? - מקישים על Enter
משווים את התשובה הזו לתשובות קודמות. מה ההבדל?
אתם אמורים לראות תשובה שכוללת את הטמפרטורה מהפונקציה. בדקו גם את הטרמינל של Cloud Shell. אמורות להופיע בו הצהרות print שמאשרות שפונקציית Python הופעלה.
18. שיפור הפלט של המודל באמצעות פרמטרים
כל הכבוד! עכשיו העוזר האישי לנסיעות יכול להשתמש בכלים כדי לאחזר נתונים חיצוניים בזמן אמת, מה שהופך אותו להרבה יותר יעיל.
עכשיו, אחרי ששיפרנו את היכולות של המודל, נתאים אישית את התשובות שלו. הפרמטרים של המודל מאפשרים לכם לשלוט בסגנון ובאקראיות של טקסט דינמי מבוסס-AI שנוצר על ידי ה-LLM. שינוי ההגדרות האלה מאפשר לכם להפוך את הפלט של הבוט לממוקד ודטרמיניסטי יותר, או ליצירתי ומגוון יותר.
בשיעור ה-Lab הזה נתמקד ב-temperature וב-top_p. (רשימה מלאה של הפרמטרים שאפשר להגדיר והתיאורים שלהם מופיעה בקטע GenerateContentConfig במאמרי העזרה של ה-API).
-
temperature: קובע את רמת האקראיות של הפלט. ערך נמוך יותר (קרוב יותר ל-0) הופך את הפלט לדטרמיניסטי וממוקד יותר, ואילו ערך גבוה יותר (קרוב יותר ל-2) מגביר את האקראיות והיצירתיות. בבוט של שאלות ותשובות או בבוט של עוזר אישי, בדרך כלל עדיף להגדיר טמפרטורה נמוכה יותר כדי לקבל תשובות עקביות ועובדתיות יותר. -
top_p: ההסתברות המצטברת המקסימלית של טוקנים שצריך להביא בחשבון במהלך הדגימה. האסימונים ממוינים לפי ההסתברויות שהוקצו להם, כך שרק האסימונים הסבירים ביותר נלקחים בחשבון. המודל מתייחס לטוקנים הסבירים ביותר שסכום ההסתברויות שלהם מגיע לערך שלtop_p. ערך נמוך יותר מגביל את אפשרויות הבחירה של הטוקנים, וכתוצאה מכך הפלט פחות מגוון
פרמטרים של שיחות
- מוצאים את המשתנים
temperatureו-top_p, שמוגדרים בחלק העליון שלapp.py. שימו לב שהם עדיין לא נקראו בשום מקום. - מוסיפים את
temperatureואתtop_pלפרמטרים שמוגדרים בתוךGenerateContentConfigבפונקציהget_chat.generate_content_config = types.GenerateContentConfig( temperature=temperature, top_p=top_p, system_instruction=[types.Part.from_text(text=system_instructions)], tools=[tools] # Pass the tool definition here )
הפונקציה get_chat עודכנה
עכשיו אפליקציית get_chat נראית כך:
def get_chat(model_name: str):
if f"chat-{model_name}" not in st.session_state:
# Tools
tools = types.Tool(function_declarations=[weather_function])
# Initialize a configuration object
generate_content_config = types.GenerateContentConfig(
temperature=temperature,
top_p=top_p,
system_instruction=[types.Part.from_text(text=system_instructions)],
tools=[tools]
)
chat = client.chats.create(
model=model_name,
config=generate_content_config,
)
st.session_state[f"chat-{model_name}"] = chat
return st.session_state[f"chat-{model_name}"]
19. בדיקה עם פרמטרים של מודל
- בטרמינל, מסיימים את התהליך שפועל כרגע (CTRL+C).
- מריצים מחדש את הפקודה כדי להפעיל שוב את אפליקציית Streamlit.
streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080 - מרעננים את אפליקציית Streamlit. אם אפליקציית Streamlit עדיין פועלת, אתם יכולים פשוט לרענן את דף התצוגה המקדימה באינטרנט בדפדפן.
- נסו לשאול את אותה שאלה כמו קודם,
I'm looking for something to do in New York today. What do you recommend? Would it be a good day to go to Ellis Island? - מקישים על Enter
משווים את התשובה הזו לתשובות קודמות.
20. מעולה!
שדרגתם בהצלחה את אפליקציית השאלות והתשובות באמצעות Tooling, תכונה מתקדמת שמאפשרת לאפליקציה שמבוססת על Gemini לתקשר עם מערכות חיצוניות ולגשת למידע בזמן אמת.
המשך הניסויים
יש הרבה דרכים להמשיך לשפר את ההנחיה. הנה כמה דוגמאות:
- משנים את
temperatureו-top_pורואים איך זה משפיע על התשובה של ה-LLM. - כדי לראות רשימה מלאה של הפרמטרים שאפשר להגדיר ותיאורים שלהם, עיינו בקטע
GenerateContentConfigבמאמרי העזרה של ה-API. נסו להגדיר עוד פרמטרים ולשנות אותם כדי לראות מה קורה.
Recap
בשיעור ה-Lab הזה:
- השתמשתם ב-Cloud Shell Editor ובטרמינל לפיתוח.
- השתמשתם ב-Vertex AI Python SDK כדי לקשר את האפליקציה למודל Gemini.
- החלתם הוראות מערכת ופרמטרים של מודלים כדי להנחות את התשובות של ה-LLM.
- למדתם את המושג "שימוש בכלים" (קריאה להפעלת פונקציות) ואת היתרונות שלו.
- ארגנו מחדש את הקוד כך שישתמש בשיחת צ'אט עם שמירת מצב, שיטה מומלצת ל-AI בממשק שיחה.
- הגדרתם כלי למודל באמצעות הצהרת פונקציה.
- הטמעתם את פונקציית Python כדי לספק את הלוגיקה של הכלי.
- כתבתם את הקוד שמטפל בבקשות להפעלת פונקציות של המודל ומחזיר את התוצאות.