Developing LLM Apps with the Vertex AI SDK

1. מבוא

סקירה כללית

אתם מפתחים בחברה לשיווק בתחום הנסיעות. מחלקת המכירות שלכם החליטה שהיא צריכה אפליקציית צ'אט חדשה כדי לעמוד בקצב של חברות ההזמנות והחיפוש הגדולות יותר. הם גם שמעו על AI גנרטיבי, אבל הם לא יודעים עליו הרבה. מחלקות אחרות שמעו על היוזמה הזו, והן רוצות לדעת איך היא יכולה לעזור גם להן לשפר את חוויית הלקוח.

הפעולות שתבצעו:

בשיעור ה-Lab הזה תבנו צ'אט בוט של עוזר אישי לנסיעות באמצעות המודל Gemini 2.5 Flash ב-Vertex AI.

האפליקציה צריכה:

  • עוזר למשתמשים לשאול שאלות על נסיעות, להזמין נסיעות ולקבל מידע על מקומות שהם מתכננים לבקר בהם
  • מספק למשתמשים דרכים לקבל עזרה לגבי תוכניות הנסיעה הספציפיות שלהם
  • לאחזר נתונים בזמן אמת, כמו מזג האוויר, באמצעות כלים

תעבדו בסביבה מוגדרת מראש של Google Cloud, ספציפית ב-Cloud Shell Editor. כבר הגדרנו בשבילכם ממשק משתמש בסיסי לאפליקציית אינטרנט, וגם את ההרשאות שצריך כדי לגשת ל-Vertex AI. האפליקציה הזו פותחה באמצעות Streamlit.

מה תלמדו

בשיעור ה-Lab הזה תלמדו איך לבצע את המשימות הבאות:

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

  1. לוחצים על הקישור הזה כדי לעבור ישירות אל Cloud Shell Editor.
  2. אם תתבקשו לאשר בשלב כלשהו היום, לחצו על Authorize כדי להמשיך. לוחצים כדי לאשר את Cloud Shell.
  3. אם הטרמינל לא מופיע בתחתית המסך, פותחים אותו:
    • לוחצים על הצגה.
    • לוחצים על Terminal (מסוף).פתיחת טרמינל חדש ב-Cloud Shell Editor
  4. בטרמינל, מגדירים את הפרויקט באמצעות הפקודה הבאה:
    gcloud config set project [PROJECT_ID]
    
    • דוגמה:
      gcloud config set project lab-project-id-example
      
    • אם אתם לא זוכרים את מזהה הפרויקט, אתם יכולים להציג את כל מזהי הפרויקטים באמצעות הפקודה הבאה:
      gcloud projects list
      
      הגדרת מזהה הפרויקט בטרמינל של Cloud Shell Editor
  5. ההודעה הבאה אמורה להופיע:
    Updated property [core/project].
    

4. הפעלת ממשקי ה-API

כדי להשתמש ב-Vertex AI SDK ולתקשר עם מודל Gemini, צריך להפעיל את Vertex AI API בפרויקט בענן ב-Google Cloud.

  1. בטרמינל, מפעילים את ממשקי ה-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 הגלובליות של המערכת.

  1. יוצרים תיקייה בשם wanderbot כדי לאחסן את הקוד של אפליקציית העוזר האישי לנסיעות. מריצים את הקוד הבא במסוף:
    mkdir wanderbot && cd wanderbot
    
  2. יוצרים ומפעילים סביבה וירטואלית:
    uv venv --python 3.12
    source .venv/bin/activate
    
    תראו את הקידומת (wanderbot) בשורת הפקודה של הטרמינל, שמציינת שהסביבה הווירטואלית פעילה. זה ייראה בערך כך:

    צילום מסך של הטרמינל עם סביבה וירטואלית פעילה

6. יצירת קובצי התחלה ל-wanderbot

  1. יוצרים ופותחים קובץ app.py חדש לאפליקציה. מריצים את הקוד הבא במסוף:
    cloudshell edit app.py
    
    הפקודה cloudshell edit תפתח את הקובץ app.py בכלי העריכה שמעל הטרמינל.
  2. מדביקים את הקוד הבא לתחילת הדרך של האפליקציה ב-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)
    
  3. יוצרים ופותחים קובץ requirements.txt חדש לקוד האפליקציה. מריצים את הקוד הבא במסוף:
    cloudshell edit requirements.txt
    
    הפקודה cloudshell edit תפתח את הקובץ requirements.txt בכלי העריכה שמעל הטרמינל.
  4. מדביקים את הקוד הבא לתחילת הדרך באפליקציה ב-requirements.txt.
    google-genai
    streamlit
    requests
    
  5. מתקינים את יחסי התלות הנדרשים של 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 לא פתוח, אתם יכולים לפתוח אותו כך:

  1. ללחוץ על הכפתור של Gemini Code Assist (כאן מפעילים את Gemini Code Assist) בחלק העליון של המסך.
  2. לוחצים על Open Gemini Code Assist Chat. תפריט Gemini Code Assist

איך משתמשים ב-Gemini Code Assist כדי להבין את הקוד

אתם יכולים להשתמש ב-Gemini Code Assist Chat כדי להבין טוב יותר את הקוד.

  1. מדגישים או בוחרים את קטע הקוד הרצוי.
  2. מקלידים "הסבר את הקוד הזה" בשיחה עם Gemini.
  3. כדי לשלוח, לוחצים על Enter.

סרטון שמראה איך מדגישים חלק מהקוד, מעבירים את ההנחיה "Explain this" ל-Gemini Code Assist ומקבלים תשובה.

8. הפעלת אפליקציית האינטרנט

לפני שמחברים את האפליקציה הזו למודל שפה גדול (LLM), מפעילים אותה כדי לראות איך היא מתנהגת בהתחלה.

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

    יופיע ממשק צ'אט פשוט של אפליקציית הנסיעות.
  3. מקלידים הודעה כלשהי (למשל Hi!) ולוחצים על Enter.

    ההודעה תופיע בהיסטוריית הצ'אט, אבל תוצג הודעת שגיאה במקום תשובה מהעוזר הדיגיטלי. הסיבה לכך היא שהאפליקציה עדיין לא מחוברת למודל שפה גדול (LLM). שימו לב להתנהגות הזו כדי להבין את נקודת ההתחלה של ה-Lab.

9. אתחול הלקוח של Vertex AI

עיון במודלים הזמינים ב-Vertex AI

פלטפורמת Vertex AI של Google Cloud מספקת גישה למגוון מודלים של AI גנרטיבי. לפני שמשלבים פתרון, אפשר לבדוק את האפשרויות הזמינות במסוף Google Cloud.

  1. במסוף Google Cloud, עוברים אל Model Garden. כדי לעשות את זה, מחפשים את Model Garden בשורת החיפוש שבחלק העליון של המסך ובוחרים ב-Vertex AI.‏(הופעות )
  2. מעיינים במודלים הזמינים. אפשר לסנן לפי קריטריונים כמו אופני שימוש, סוגי משימות ותכונות.

בשיעור ה-Lab הזה תשתמשו במודל Gemini 2.5 Flash, שמתאים לפיתוח אפליקציות צ'אט רספונסיביות בגלל המהירות שלו.

אתחול הלקוח של Vertex AI

עכשיו תשנו את הקטע --- Initialize the Vertex AI Client --- בקובץ app.py כדי להפעיל את הלקוח של Vertex AI. אובייקט הלקוח הזה ישמש לשליחת הנחיות למודל.

  1. פותחים את app.py ב-Cloud Shell Editor.
  2. ב-app.py, מחפשים את השורה PROJECT_ID = None.
  3. מחליפים את None במזהה הפרויקט ב-Google Cloud, במירכאות. (לדוגמה, PROJECT_ID = "google-cloud-labs")
    אם אתם לא זוכרים את מזהה הפרויקט, אתם יכולים להציג את כל מזהי הפרויקטים באמצעות:
    gcloud projects list | awk '/PROJECT_ID/{print $2}'
    
  4. הגדרת הלקוח: בתוך הבלוק 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.

  1. מוצאים את הקטע --- Call the Model --- שבו מוגדרת הפונקציה call_model.
  2. הגדרת התוכן: בקטע # TODO: Prepare the content for the model , מגדירים את תוכן הקלט שיישלח למודל. בהנחיה בסיסית, זה יהיה הקלט של המשתמש.
            contents = [prompt]
    
  3. הגדרת התגובה: מדביקים את הקוד הזה מתחת ל-# TODO: Define response.
            response = client.models.generate_content(
                model=model_name,
                contents=contents,
            )
    
  4. החזרת התשובה: מבטלים את הסימון של השורה הבאה:
            return response.text
    
  5. בודקים את השורה שבה מתבצעת הקריאה לפונקציה 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. בדיקת האפליקציה המקושרת

  1. בטרמינל, מסיימים את התהליך שפועל כרגע (CTRL+C).
  2. מריצים מחדש את הפקודה כדי להפעיל שוב את אפליקציית Streamlit.
    streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080
    
  3. מרעננים את אפליקציית Streamlit. אם אפליקציית Streamlit עדיין פועלת, אתם יכולים פשוט לרענן את דף התצוגה המקדימה באינטרנט בדפדפן.
  4. עכשיו, מקלידים שאלה בשדה הקלט של הצ'אט, למשל:
    What is the best time of year to go to Iceland?
    
  5. לוחצים על Enter.

    באפליקציה אמורה להופיע ההודעה שלכם, סמל של "חושב…" ואז תשובה שנוצרה על ידי מודל Gemini. אם כן, סימן שקישרתם בהצלחה את אפליקציית האינטרנט שלכם ל-LLM ב-Vertex AI. 🙌 🥳

12. הגדרת הוראות מערכת

החיבור הבסיסי עובד, אבל האיכות והסגנון של התשובות של ה-LLM מושפעים מאוד מהקלט שהוא מקבל. הנדסת פרומפטים היא התהליך של תכנון ושיפור של הקלט (הפרומפטים) כדי להנחות את המודל ליצור את הפלט הרצוי.

כדי לעשות את זה, קודם כל יוצרים הוראות מערכת ומעבירים אותן למודל.

אתם יכולים להשתמש ב-Ask Gemini כדי ליצור הוראות מערכת מועילות.

  1. ב-app.py, מאתרים את המשתנה system_instructions, שמוגדר כרגע כ-None.
    system_instructions = None
    
    אתם תחליפו את None במחרוזת מרובת שורות שמספקת הוראות לבוט של עוזר הנסיעות.
  2. שואלים את 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.
    
  3. הגדרת 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.
    """
    
  4. מגדירים את 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}")
    
  5. כדי להוסיף את הוראות המערכת לתשובה, מוסיפים פרמטר config ל-method‏ generate_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. בדיקת האפליקציה עם הוראות המערכת

  1. בטרמינל, מסיימים את התהליך שפועל כרגע (CTRL+C).
  2. מריצים מחדש את הפקודה כדי להפעיל שוב את אפליקציית Streamlit.
    streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080
    
  3. מרעננים את אפליקציית Streamlit. אם אפליקציית Streamlit עדיין פועלת, אתם יכולים פשוט לרענן את דף התצוגה המקדימה באינטרנט בדפדפן.
  4. נסו לשאול את אותה שאלה כמו קודם:
    What is the best time of year to go to Iceland?
    
  5. לוחצים על Enter.
    השוו בין התשובה שקיבלתם הפעם לתשובה שקיבלתם בפעם הקודמת.

14. הגדרת כלי למזג אוויר

עד עכשיו, הצ'אט בוט שלנו הוא בעל ידע, אבל הידע שלו מוגבל לנתונים שהוא אומן לפיהם. אין לו גישה למידע בזמן אמת. לבוט של נסיעות, היכולת לאחזר נתונים בזמן אמת כמו תחזיות מזג אוויר היא יתרון עצום.

כאן נכנסת לתמונה הפעלת כלים, שנקראת גם קריאה להפעלת פונקציות. אנחנו יכולים להגדיר קבוצה של כלים (פונקציות Python) שה-LLM יכול לבחור להפעיל כדי לקבל מידע חיצוני.

איך הכלים פועלים

  1. אנחנו מתארים למודל את הכלים שלנו, כולל מה הם עושים ואילו פרמטרים הם מקבלים.
  2. המשתמש שולח הנחיה (למשל, "מה מזג האוויר בלונדון?").
  3. המודל מקבל את ההנחיה ומזהה שהמשתמש שואל על משהו שהוא יכול לברר באמצעות אחד מהכלים שלו.
  4. במקום להגיב בטקסט, המודל מגיב באובייקט function_call מיוחד, שמציין לאיזה כלי הוא רוצה לקרוא ועם אילו ארגומנטים.
  5. קוד ה-Python שלנו מקבל את ה-function_call הזה, מריץ את הפונקציה get_current_temperature בפועל עם הארגומנטים שסופקו, ומקבל את התוצאה (למשל, 15°C).
  6. אנחנו שולחים את התוצאה הזו בחזרה למודל.
  7. המודל מקבל את התוצאה ויוצר תשובה בשפה טבעית למשתמש (לדוגמה, "הטמפרטורה הנוכחית בלונדון היא 15°C").

התהליך הזה מאפשר למודל לענות על שאלות שהן הרבה מעבר לנתוני האימון שלו, וכך הוא הופך לעוזר אישי הרבה יותר יעיל ושימושי.

הגדרת כלי למזג אוויר

אם מטיילים מחפשים המלצות לפעילויות, ומתלבטים בין פעילויות שמושפעות ממזג האוויר, כלי מזג האוויר יכול לעזור להם. בואו ניצור כלי למודל שלנו כדי לקבל את מזג האוויר הנוכחי. אנחנו צריכים שני חלקים: הצהרת פונקציה שמתארת את הכלי למודל, והפונקציה עצמה ב-Python שמטמיעה אותו.

  1. ב-app.py, מוצאים את התגובה # TODO: Define the weather tool function declaration.
  2. מתחת להערה הזו, מוסיפים את המשתנה 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"],
        },
    }
    
  3. עכשיו מוצאים את התגובה # 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}&current_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. זה מעולה לשאלות בודדות, אבל לא אידיאלי לשיחה עם כמה סבבים, במיוחד כזו שכוללת שימוש בכלים.

שיטה טובה יותר היא להשתמש בשיחת צ'אט, ששומרת על ההקשר של השיחה. עכשיו נארגן את הקוד מחדש כדי להשתמש בשיחת צ'אט, שנדרשת כדי להטמיע את הכלים בצורה נכונה.

  1. מוחקים את הפונקציה הקיימת call_model. נחליף אותו בגרסה מתקדמת יותר.
  2. במקומה, מוסיפים את הפונקציה החדשה 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}"
    
  3. עכשיו נוסיף פונקציית עזר לניהול שיחת הצ'אט. מעל הפונקציה החדשה 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

  1. בפונקציה get_chat, מתחת לתגובה # TODO: Define the tools configuration..., מגדירים את האובייקט tools על ידי יצירת מופע של types.Tool מההצהרה weather_function.
            tools = types.Tool(function_declarations=[weather_function])
    
  2. בקטע # 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
            )
    
  3. בקטע # TODO: Create a new chat session, יוצרים את אובייקט הצ'אט באמצעות client.chats.create(), ומעבירים את שם המודל וההגדרות האישיות שלנו.
            chat = client.chats.create(
                model=model_name,
                config=generate_content_config,
            )
    

הטמעה של call_model

  1. בקטע # TODO: Get the existing chat session... בפונקציה call_model, מפעילים את פונקציית העזר החדשה get_chat.
            chat = get_chat(model_name)
    
  2. עכשיו מחפשים את # TODO: Send the message to the model. שולחים את ההודעה של המשתמש באמצעות השיטה chat.send_message().
                response = chat.send_message(message_content)
    
  3. מחפשים את # 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]
  1. לבסוף, מוצאים את # 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. בדיקת האפליקציה עם הכלים המופעלים

רוצה לראות את התכונה החדשה בפעולה?

  1. בטרמינל, מסיימים את התהליך שפועל כרגע (CTRL+C).
  2. מריצים מחדש את הפקודה כדי להפעיל שוב את אפליקציית Streamlit.
    streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080
    
  3. מרעננים את אפליקציית Streamlit. אם אפליקציית Streamlit עדיין פועלת, אתם יכולים פשוט לרענן את דף התצוגה המקדימה באינטרנט בדפדפן.
  4. עכשיו, שואלים שאלה שאמורה להפעיל את הכלי החדש, למשל:
    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?
    
  5. מקישים על Enter
    משווים את התשובה הזו לתשובות קודמות. מה ההבדל? ‫
    אתם אמורים לראות תשובה שכוללת את הטמפרטורה מהפונקציה. בדקו גם את הטרמינל של Cloud Shell. אמורות להופיע בו הצהרות print שמאשרות שפונקציית Python הופעלה.

18. שיפור הפלט של המודל באמצעות פרמטרים

כל הכבוד! עכשיו העוזר האישי לנסיעות יכול להשתמש בכלים כדי לאחזר נתונים חיצוניים בזמן אמת, מה שהופך אותו להרבה יותר יעיל.

עכשיו, אחרי ששיפרנו את היכולות של המודל, נתאים אישית את התשובות שלו. הפרמטרים של המודל מאפשרים לכם לשלוט בסגנון ובאקראיות של טקסט דינמי מבוסס-AI שנוצר על ידי ה-LLM. שינוי ההגדרות האלה מאפשר לכם להפוך את הפלט של הבוט לממוקד ודטרמיניסטי יותר, או ליצירתי ומגוון יותר.

בשיעור ה-Lab הזה נתמקד ב-temperature וב-top_p. (רשימה מלאה של הפרמטרים שאפשר להגדיר והתיאורים שלהם מופיעה בקטע GenerateContentConfig במאמרי העזרה של ה-API).

  • ‫temperature: קובע את רמת האקראיות של הפלט. ערך נמוך יותר (קרוב יותר ל-0) הופך את הפלט לדטרמיניסטי וממוקד יותר, ואילו ערך גבוה יותר (קרוב יותר ל-2) מגביר את האקראיות והיצירתיות. בבוט של שאלות ותשובות או בבוט של עוזר אישי, בדרך כלל עדיף להגדיר טמפרטורה נמוכה יותר כדי לקבל תשובות עקביות ועובדתיות יותר.
  • ‫top_p: ההסתברות המצטברת המקסימלית של טוקנים שצריך להביא בחשבון במהלך הדגימה. האסימונים ממוינים לפי ההסתברויות שהוקצו להם, כך שרק האסימונים הסבירים ביותר נלקחים בחשבון. המודל מתייחס לטוקנים הסבירים ביותר שסכום ההסתברויות שלהם מגיע לערך של top_p. ערך נמוך יותר מגביל את אפשרויות הבחירה של הטוקנים, וכתוצאה מכך הפלט פחות מגוון

פרמטרים של שיחות

  1. מוצאים את המשתנים temperature ו-top_p, שמוגדרים בחלק העליון של app.py. שימו לב שהם עדיין לא נקראו בשום מקום.
  2. מוסיפים את 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. בדיקה עם פרמטרים של מודל

  1. בטרמינל, מסיימים את התהליך שפועל כרגע (CTRL+C).
  2. מריצים מחדש את הפקודה כדי להפעיל שוב את אפליקציית Streamlit.
    streamlit run app.py --browser.serverAddress=localhost --server.enableCORS=false --server.enableXsrfProtection=false --server.port 8080
    
  3. מרעננים את אפליקציית Streamlit. אם אפליקציית Streamlit עדיין פועלת, אתם יכולים פשוט לרענן את דף התצוגה המקדימה באינטרנט בדפדפן.
  4. נסו לשאול את אותה שאלה כמו קודם,
    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?
    
  5. מקישים על Enter
    משווים את התשובה הזו לתשובות קודמות.

20. מעולה!

שדרגתם בהצלחה את אפליקציית השאלות והתשובות באמצעות Tooling, תכונה מתקדמת שמאפשרת לאפליקציה שמבוססת על Gemini לתקשר עם מערכות חיצוניות ולגשת למידע בזמן אמת.

המשך הניסויים

יש הרבה דרכים להמשיך לשפר את ההנחיה. הנה כמה דוגמאות:

  • משנים את temperature ו-top_p ורואים איך זה משפיע על התשובה של ה-LLM.
  • כדי לראות רשימה מלאה של הפרמטרים שאפשר להגדיר ותיאורים שלהם, עיינו בקטע GenerateContentConfig במאמרי העזרה של ה-API. נסו להגדיר עוד פרמטרים ולשנות אותם כדי לראות מה קורה.

Recap

בשיעור ה-Lab הזה:

  • השתמשתם ב-Cloud Shell Editor ובטרמינל לפיתוח.
  • השתמשתם ב-Vertex AI Python SDK כדי לקשר את האפליקציה למודל Gemini.
  • החלתם הוראות מערכת ופרמטרים של מודלים כדי להנחות את התשובות של ה-LLM.
  • למדתם את המושג "שימוש בכלים" (קריאה להפעלת פונקציות) ואת היתרונות שלו.
  • ארגנו מחדש את הקוד כך שישתמש בשיחת צ'אט עם שמירת מצב, שיטה מומלצת ל-AI בממשק שיחה.
  • הגדרתם כלי למודל באמצעות הצהרת פונקציה.
  • הטמעתם את פונקציית Python כדי לספק את הלוגיקה של הכלי.
  • כתבתם את הקוד שמטפל בבקשות להפעלת פונקציות של המודל ומחזיר את התוצאות.