การพัฒนาแอป LLM ด้วย Vertex AI SDK

1. บทนำ

ภาพรวม

คุณเป็นนักพัฒนาซอฟต์แวร์ที่บริษัทการตลาดด้านการท่องเที่ยว ฝ่ายขายของคุณตัดสินใจว่าต้องการแอปพลิเคชันแชทใหม่เพื่อให้ทันกับบริษัทจองและค้นหาที่ใหญ่กว่า นอกจากนี้ยังเคยได้ยินเกี่ยวกับ Generative AI แต่ไม่ทราบข้อมูลมากนัก แผนกอื่นๆ ได้ยินเกี่ยวกับโครงการริเริ่มนี้และอยากทราบว่าโครงการนี้จะช่วยปรับปรุงประสบการณ์ของลูกค้าได้อย่างไร

สิ่งที่คุณจะทำ

ในห้องทดลองนี้ คุณจะสร้างแชทบ็อตผู้ช่วยด้านการเดินทางโดยใช้โมเดล Gemini 2.5 Flash ใน Vertex AI

แอปพลิเคชันควรมีลักษณะดังนี้

  • ช่วยให้ผู้ใช้ถามคำถามเกี่ยวกับการเดินทาง จองการเดินทาง และดูข้อมูลเกี่ยวกับสถานที่ที่วางแผนจะไป
  • ให้ผู้ใช้มีวิธีรับความช่วยเหลือเกี่ยวกับแผนการเดินทางที่เฉพาะเจาะจง
  • สามารถดึงข้อมูลแบบเรียลไทม์ เช่น สภาพอากาศ โดยใช้เครื่องมือ

คุณจะทำงานในสภาพแวดล้อม Google Cloud ที่กำหนดค่าไว้ล่วงหน้า โดยเฉพาะภายในเครื่องมือแก้ไข Cloud Shell ระบบได้ตั้งค่าฟรอนท์เอนด์ของเว็บแอปพลิเคชันพื้นฐานไว้ให้คุณแล้ว พร้อมด้วยสิทธิ์ที่จำเป็นในการเข้าถึง Vertex AI แอปนี้สร้างขึ้นโดยใช้ Streamlit

สิ่งที่คุณจะได้เรียนรู้

ในห้องปฏิบัติการนี้ คุณจะได้เรียนรู้วิธีทำงานต่อไปนี้

2. การตั้งค่าโปรเจ็กต์

บัญชี Google

หากยังไม่มีบัญชี Google ส่วนบุคคล คุณต้องสร้างบัญชี Google

ใช้บัญชีส่วนตัวแทนบัญชีของที่ทำงานหรือโรงเรียน

ลงชื่อเข้าใช้คอนโซล Google Cloud

ลงชื่อเข้าใช้คอนโซล Google Cloud โดยใช้บัญชี Google ส่วนบุคคล

เปิดใช้การเรียกเก็บเงิน

แลกรับเครดิต Google Cloud (ไม่บังคับ)

หากต้องการจัดเวิร์กช็อปนี้ คุณต้องมีบัญชีสำหรับการเรียกเก็บเงินที่มีเครดิตอยู่บ้าง ใช้เครดิตจากแบนเนอร์ที่ด้านบนของ Codelab นี้เพื่อเริ่มต้นใช้งาน หากเชื่อมต่อกับบัญชีสำหรับการเรียกเก็บเงินอยู่แล้ว คุณสามารถข้ามขั้นตอนนี้ได้

ตั้งค่าบัญชีสำหรับการเรียกเก็บเงินส่วนบุคคล

หากตั้งค่าการเรียกเก็บเงินโดยใช้เครดิต Google Cloud คุณสามารถข้ามขั้นตอนนี้ได้

หากต้องการตั้งค่าบัญชีสำหรับการเรียกเก็บเงินส่วนบุคคล ให้ไปที่นี่เพื่อเปิดใช้การเรียกเก็บเงินใน Cloud Console

ข้อควรทราบมีดังนี้

  • การทำห้องทดลองนี้ให้เสร็จสมบูรณ์ควรใช้ทรัพยากร Cloud ไม่เกิน $1 USD
  • คุณสามารถทำตามขั้นตอนที่ตอนท้ายของห้องทดลองนี้เพื่อลบทรัพยากรเพื่อหลีกเลี่ยงการเรียกเก็บเงินเพิ่มเติม
  • ผู้ใช้ใหม่มีสิทธิ์รับช่วงทดลองใช้ฟรีมูลค่า $300 USD

สร้างโปรเจ็กต์ (ไม่บังคับ)

หากไม่มีโปรเจ็กต์ปัจจุบันที่ต้องการใช้สำหรับห้องทดลองนี้ ให้สร้างโปรเจ็กต์ใหม่ที่นี่

3. เปิดเครื่องมือแก้ไข Cloud Shell

  1. คลิกลิงก์นี้เพื่อไปยังเครื่องมือแก้ไข Cloud Shell โดยตรง
  2. หากระบบแจ้งให้คุณให้สิทธิ์ในขั้นตอนใดก็ตามในวันนี้ ให้คลิกให้สิทธิ์เพื่อดำเนินการต่อ คลิกเพื่อให้สิทธิ์ Cloud Shell
  3. หากเทอร์มินัลไม่ปรากฏที่ด้านล่างของหน้าจอ ให้เปิดเทอร์มินัลโดยทำดังนี้
    • คลิกดู
    • คลิก Terminalเปิดเทอร์มินัลใหม่ในเครื่องมือแก้ไข Cloud Shell
  4. ในเทอร์มินัล ให้ตั้งค่าโปรเจ็กต์ด้วยคำสั่งต่อไปนี้
    gcloud config set project [PROJECT_ID]
    
    • ตัวอย่าง
      gcloud config set project lab-project-id-example
      
    • หากจำรหัสโปรเจ็กต์ไม่ได้ คุณสามารถแสดงรายการรหัสโปรเจ็กต์ทั้งหมดได้โดยใช้คำสั่งต่อไปนี้
      gcloud projects list
      
      ตั้งค่ารหัสโปรเจ็กต์ในเทอร์มินัลเครื่องมือแก้ไข Cloud Shell
  5. คุณควรเห็นข้อความต่อไปนี้
    Updated property [core/project].
    

4. เปิดใช้ API

หากต้องการใช้ Vertex AI SDK และโต้ตอบกับโมเดล Gemini คุณต้องเปิดใช้ Vertex AI API ในโปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Google

  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 ได้ที่ข้อมูลเบื้องต้นเกี่ยวกับ Vertex AI SDK สำหรับ Python | Google Cloud

5. สร้างสภาพแวดล้อมเสมือนและติดตั้งทรัพยากร Dependency

ก่อนเริ่มโปรเจ็กต์ Python ใดๆ แนวทางปฏิบัติแนะนำคือให้สร้างสภาพแวดล้อมเสมือนจริง ซึ่งจะแยกทรัพยากร Dependency ของโปรเจ็กต์ออก เพื่อป้องกันความขัดแย้งกับโปรเจ็กต์อื่นๆ หรือแพ็กเกจ 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. ติดตั้งทรัพยากร Dependency ของ 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. เลือกเปิดแชท Gemini Code Assist เมนู Gemini Code Assist

ใช้ Gemini Code Assist เพื่อทำความเข้าใจโค้ด

คุณสามารถใช้ Gemini Code Assist Chat เพื่อทำความเข้าใจโค้ดได้ดียิ่งขึ้น

  1. ไฮไลต์หรือเลือกส่วนโค้ดที่ต้องการ
  2. พิมพ์ "อธิบายโค้ดนี้" ในแชทกับ Gemini
  3. คลิก Enter เพื่อส่ง

วิดีโอที่แสดงการไฮไลต์ส่วนหนึ่งของโค้ด โดยส่ง "อธิบายโค้ดนี้" ไปยัง 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. หลังจากเรียกใช้คำสั่งแล้ว ให้คลิกปุ่มตัวอย่างบนเว็บที่ด้านบนของเครื่องมือแก้ไข Cloud Shell แล้วเลือกแสดงตัวอย่างในพอร์ต 8080
    เมนูตัวอย่างเปิดอยู่ โดยมี

    คุณจะเห็นอินเทอร์เฟซแชทที่เรียบง่ายสำหรับแอปการเดินทาง
  3. พิมพ์ข้อความใดก็ได้ (เช่น Hi!) แล้วกด ENTER

    คุณจะสังเกตเห็นว่าข้อความจะปรากฏในประวัติการแชท แต่คุณจะได้รับข้อความแสดงข้อผิดพลาดแทนการตอบกลับจากผู้ช่วย เนื่องจากแอปพลิเคชันยังไม่ได้เชื่อมต่อกับโมเดลภาษาขนาดใหญ่ สังเกตลักษณะการทำงานนี้เพื่อทำความเข้าใจจุดเริ่มต้นของห้องทดลอง

9. เริ่มต้นไคลเอ็นต์ Vertex AI

สำรวจโมเดลที่พร้อมใช้งานใน Vertex AI

แพลตฟอร์ม Vertex AI ของ Google Cloud ให้สิทธิ์เข้าถึงโมเดล Generative AI ที่หลากหลาย ก่อนที่จะผสานรวม คุณสามารถสำรวจตัวเลือกที่มีอยู่ในคอนโซล Google Cloud

  1. จากคอนโซล Google Cloud ให้ไปที่ Model Garden โดยค้นหา "Model Garden" ในแถบค้นหาที่ด้านบนของหน้าจอ แล้วเลือก Vertex AI (รายการ )
  2. เรียกดูโมเดลที่ใช้ได้ คุณสามารถกรองตามสิ่งต่างๆ เช่น รูปแบบ ประเภทงาน และฟีเจอร์

สำหรับวัตถุประสงค์ของห้องทดลองนี้ คุณจะใช้โมเดล Gemini 2.5 Flash ซึ่งเป็นตัวเลือกที่ดีสำหรับการสร้างแอปพลิเคชันแชทที่ตอบสนองได้ดีเนื่องจากมีความเร็ว

เริ่มต้นไคลเอ็นต์ Vertex AI

ตอนนี้คุณจะแก้ไขส่วน --- Initialize the Vertex AI Client --- ใน app.py เพื่อเริ่มต้นไคลเอ็นต์ Vertex AI ระบบจะใช้ออบเจ็กต์ไคลเอ็นต์นี้เพื่อส่งพรอมต์ไปยังโมเดล

  1. เปิด app.py ในเครื่องมือแก้ไข Cloud Shell
  2. ใน app.py ให้ค้นหาบรรทัด PROJECT_ID = None
  3. แทนที่ None ด้วยรหัสโปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Google ในเครื่องหมายคำพูด (เช่น 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 ---
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 ฉลาดพอที่จะเข้าใจว่ารายการที่มีสตริงแสดงถึงการป้อนข้อความของผู้ใช้ โดยจะจัดรูปแบบให้ถูกต้องสำหรับ Model 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 จะได้รับอิทธิพลอย่างมากจากอินพุตที่ได้รับ วิศวกรรมพรอมต์ (Prompt Engineering) คือกระบวนการออกแบบและปรับแต่งอินพุต (พรอมต์) เหล่านี้เพื่อแนะนำโมเดลในการสร้างเอาต์พุตที่ต้องการ

ด้วยเหตุนี้ คุณจะเริ่มต้นด้วยการสร้างคำสั่งของระบบและส่งไปยังโมเดล

คุณจะใช้ฟีเจอร์ขอความช่วยเหลือจาก 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. หากต้องการเพิ่มคำสั่งของระบบลงใน response ให้เพิ่มพารามิเตอร์ config ลงในเมธอด 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")

กระบวนการนี้ช่วยให้โมเดลตอบคำถามได้มากกว่าข้อมูลฝึกฝน ทำให้เป็นผู้ช่วยที่มีประสิทธิภาพและมีประโยชน์มากขึ้น

กำหนดเครื่องมือสภาพอากาศ

หากผู้เดินทางกำลังมองหาคำแนะนำเกี่ยวกับกิจกรรมที่น่าสนใจ และกำลังเลือกกิจกรรมที่ได้รับผลกระทบจากสภาพอากาศ เครื่องมือสภาพอากาศก็อาจมีประโยชน์ มาสร้างเครื่องมือสำหรับโมเดลของเราเพื่อรับข้อมูลสภาพอากาศปัจจุบันกัน เราต้องการ 2 ส่วน ได้แก่ การประกาศฟังก์ชันที่อธิบายเครื่องมือให้โมเดลทราบ และฟังก์ชัน Python จริงที่ใช้เครื่องมือนั้น

  1. ค้นหาความคิดเห็น # TODO: Define the weather tool function declaration ใน app.py
  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 ใหม่จากบล็อกโค้ดด้านล่างแทน ฟังก์ชันใหม่นี้มีตรรกะในการจัดการลูปการเรียกใช้เครื่องมือที่เราพูดถึงก่อนหน้านี้ โปรดสังเกตว่ามี TODO comments หลายรายการที่เราจะดำเนินการให้เสร็จสมบูรณ์ในขั้นตอนถัดไป
    # --- 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. ตอนนี้เรามาเพิ่มฟังก์ชันตัวช่วยเพื่อจัดการเซสชันการแชทกัน เพิ่มฟังก์ชัน get_chat ไว้เหนือฟังก์ชัน call_model ใหม่ ฟังก์ชันนี้จะสร้างเซสชันการแชทใหม่ที่มีคำสั่งของระบบและคำจำกัดความของเครื่องมือ หรือเรียกข้อมูลเซสชันที่มีอยู่ ซึ่งเป็นแนวทางปฏิบัติที่ดีในการจัดระเบียบโค้ด
    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. ใช้ตรรกะการเรียกใช้เครื่องมือ

ตอนนี้เรามาเติม TODOs เพื่อให้ตรรกะการเรียกใช้เครื่องมือทำงานได้อย่างสมบูรณ์

ใช้ 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"
            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 ด้วย คุณควรเห็นคำสั่งพิมพ์ที่ยืนยันว่าฟังก์ชัน Python ทำงานแล้ว

18. ปรับแต่งเอาต์พุตของโมเดลด้วยพารามิเตอร์

ทำได้ดีมาก ตอนนี้ผู้ช่วยด้านการเดินทางของคุณสามารถใช้เครื่องมือเพื่อดึงข้อมูลภายนอกแบบเรียลไทม์ได้แล้ว ซึ่งทำให้มีประสิทธิภาพมากขึ้นอย่างมาก

เมื่อเราปรับปรุงสิ่งที่โมเดลทำได้แล้ว มาปรับแต่งวิธีที่โมเดลตอบกลับกัน พารามิเตอร์โมเดลช่วยให้คุณควบคุมสไตล์และความสุ่มของข้อความที่ LLM สร้างขึ้นได้ การปรับการตั้งค่าเหล่านี้จะช่วยให้เอาต์พุตของบ็อตมีความเฉพาะเจาะจงและเป็นเชิงกำหนดมากขึ้น หรือมีความสร้างสรรค์และหลากหลายมากขึ้น

สำหรับห้องทดลองนี้ เราจะมุ่งเน้นที่ 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. ยินดีด้วย

คุณได้อัปเกรดแอปพลิเคชันถามและตอบด้วยเครื่องมือ ซึ่งเป็นฟีเจอร์ที่มีประสิทธิภาพที่ช่วยให้แอปที่ทำงานด้วยระบบ Gemini สามารถโต้ตอบกับระบบภายนอกและเข้าถึงข้อมูลแบบเรียลไทม์ได้

การทดสอบอย่างต่อเนื่อง

คุณมีตัวเลือกมากมายในการเพิ่มประสิทธิภาพพรอมต์ต่อไป ลองพิจารณาตัวอย่างต่อไปนี้

  • ปรับ temperature และ top_p แล้วดูว่าค่าเหล่านี้เปลี่ยนแปลงคำตอบที่ LLM ให้มาอย่างไร
  • ดูรายการพารามิเตอร์ที่กำหนดค่าได้ทั้งหมดและคำอธิบายได้ที่ GenerateContentConfig ในเอกสารอ้างอิง API ลองกำหนดพารามิเตอร์เพิ่มเติมและปรับพารามิเตอร์เหล่านั้นเพื่อดูว่าจะเกิดอะไรขึ้น

สรุป

ในห้องทดลองนี้ คุณได้ทำสิ่งต่อไปนี้

  • ใช้ Cloud Shell Editor และเทอร์มินัลสำหรับการพัฒนา
  • ใช้ Vertex AI Python SDK เพื่อเชื่อมต่อแอปพลิเคชันกับโมเดล Gemini
  • ใช้คำสั่งของระบบและพารามิเตอร์โมเดลเพื่อเป็นแนวทางในการตอบกลับของ LLM
  • ได้เรียนรู้แนวคิดของการใช้เครื่องมือ (การเรียกใช้ฟังก์ชัน) และประโยชน์ของการใช้เครื่องมือ
  • เปลี่ยนโครงสร้างภายในโค้ดเพื่อใช้เซสชันการแชทแบบเก็บสถานะ ซึ่งเป็นแนวทางปฏิบัติแนะนำสำหรับ AI แบบสนทนา
  • กำหนดเครื่องมือสำหรับโมเดลโดยใช้การประกาศฟังก์ชัน
  • ใช้ฟังก์ชัน Python เพื่อระบุตรรกะของเครื่องมือ
  • เขียนโค้ดเพื่อจัดการคำขอการเรียกใช้ฟังก์ชันของโมเดลและแสดงผลลัพธ์