Tag: google-genai

  • 4 ขั้นตอนในการใช้ google-genai library เพื่อทำงานกับ Gemini API — ตัวอย่างการสร้างสูตรอาหารที่ไม่เหมือนใคร

    4 ขั้นตอนในการใช้ google-genai library เพื่อทำงานกับ Gemini API — ตัวอย่างการสร้างสูตรอาหารที่ไม่เหมือนใคร

    ในบทความนี้ เราจะมาดู 4 ขั้นตอนในการใช้งาน google-genai ซึ่งเป็น official library สำหรับทำงานกับ Gemini API ผ่านตัวอย่างการสร้างสูตรอาหารใน Google Colab กัน:

    1. Import packages
    2. Create client
    3. Create function
    4. Generate response

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    1. 📦 Import Packages
    2. 🧑‍💼 Create Client
    3. 📲 Create Function
    4. 📬 Generate Response
      1. 🤖 Set Model
      2. 🧑‍💻 Set User Prompt
      3. 🛠️ Set Configuration
      4. 📖 Generate Response
      5. 🖨️ Print Response
    5. 😺 Google Colab
    6. 📃 References

    📦 Import Packages

    เริ่มแรก เราจะ import 4 packages ที่จำเป็น ได้แก่:

    FromFunction/ClassFor
    googlegenaiทำงานกับ Gemini API
    google.genai.typesGenerateContentConfigตั้งค่า Gemini
    google.colabuserdataเรียก API key จากเมนู Secrets ใน Google Colab
    pydanticBaseModelกำหนดโครงสร้างของ response จาก Gemini
    # Import packages
    
    # google-genai library
    from google import genai
    from google.genai.types import GenerateContentConfig
    
    # Secret key
    from google.colab import userdata
    
    # pydantic
    from pydantic import BaseModel
    

    🧑‍💼 Create Client

    ในขั้นที่ 2 เราจะสร้าง client สำหรับทำงานกับ Gemini API

    เพื่อความปลอดภัย เราจะเก็บ API key ไว้ในเมนู Secrets ของ Google Colab

    เราสามารถเพิ่ม API key ด้วยการ import ผ่านปุ่ม “Gemini API keys” หรือผ่านการเพิ่ม API key เองด้วยปุ่ม “Add new secret”:

    หลังสร้าง API key ใน Secrets แล้ว เราสามารถเรียกใช้ API key ได้ด้วย userdata.get() ซึ่งต้องการ 1 argument คือ ชื่อ secret:

    # Get API key
    my_api = userdata.get("GOOGLE_API_KEY")
    

    จากนั้น เราจะสร้าง client ด้วย genai.Client() ซึ่งต้องการ 1 argument คือ API key:

    # Create client
    client = genai.Client(api_key=my_api)
    

    Note:

    • ในกรณีที่เราไม่ห่วงความปลอดภัยของ API key เราสามารถใส่ API key ใน genai.Client() ได้โดยตรง เช่น genai.Client(api_key="g04821...")
    • เราสามารถสร้าง API key ได้ฟรี โดยไปที่ Google AI Studio และกด “Create API key”

    📲 Create Function

    ในขั้นที่ 3 เราจะสร้าง function สำหรับเรียกใช้ Gemini ซึ่งต้องการ 3 arguments:

    1. model: Gemini model ที่เราจะเรียกใช้
    2. user_prompt: กำหนด user prompt
    3. config: กำหนดการตั้งค่าต่าง ๆ ของ model

    โดยทั้ง 3 arguments จะอยู่ใน client.models.generate_content():

    # Create a function to get Gemini response
    def get_response(model, user_prompt, config):
    
        # Get response
        response = client.models.generate_content(
    
            # Set model
            model=model,
    
            # Set user prompt
            contents=user_prompt,
    
            # Set config
            config=config
        )
    
        # Return response
        return response.text
    

    📬 Generate Response

    ในขั้นที่ 4 เราจะ get response จาก Gemini โดยใช้ function ที่เราสร้างในขั้นที่ 3

    เนื่องจาก function ต้องการ 3 arguments เราจะต้องกำหนด 3 สิ่งนี้ก่อนที่จะสร้าง response ได้:

    1. Model
    2. User prompt
    3. Configuration

    .

    🤖 Set Model

    ในตัวอย่างนี้ เราจะใช้ model เป็น Gemini 2.5 Flash ซึ่งเราสามารถกำหนดได้ดังนี้:

    # Set model
    gemini_model = "gemini-2.5-flash"
    

    Note: ดูชื่อ model อื่น ๆ ได้ที่ Gemini Models

    .

    🧑‍💻 Set User Prompt

    สำหรับ user prompt เราสามารถกำหนดเป็น string ได้แบบนี้:

    # Set user prompt
    gemini_user_prompt = """
    Create a healthy Thai-inspired burger for one person.
    
    Protein: chicken or tofu
    Bun: whole-wheat if possible (or lettuce wrap)
    
    Deliver (match field names exactly):
    - `menu` (string)
    - `ingredient` (list of items with name, description, amount, unit)
    - `steps` (30-word strings)
    - `calorie_kcal` (float, total for the dish)
    """
    

    .

    🛠️ Set Configuration

    สำหรับ configuration เราสามารถตั้งค่า model ได้หลายค่า

    ในตัวอย่างนี้ เราจะเลือกกำหนด 3 ค่า ได้แก่:

    1. System prompt
    2. Temperature
    3. Output type and structure

    ค่าที่ 1. System prompt คือ prompt ที่กำหนดพฤติกรรมของ Gemini ในการตอบสนองต่อ user prompt ของเรา

    เราสามารถกำหนด system prompt เป็น string ได้แบบนี้:

    # Set system prompt
    system_prompt = """
    You are a highly experienced home cook specialising in healthy Thai-style food.
    
    Constraints:
    - Single-serving
    - Favour grilling/pan-searing over deep-frying
    - Keep ingredients common in Thai kitchens
    - Keep steps <=7
    - Include an approximate total calories for the whole dish
    - Keep language simple
    - Return JSON only that matches the given schema exactly (no extra fields)
    """
    

    ค่าที่ 2. Temperature มีค่าระหว่าง 0 และ 2 โดย:

    • 0 จะทำให้ response ตายตัว (deterministic) มากขึ้น
    • 2 จะทำให้ response สร้างสรรค์ (creative) มากขึ้น

    Note: ค่า default ของ temperature อยู่ที่ 1 (Generate content with the Gemini API in Vertex AI)

    ในตัวอย่าง เราจะกำหนด temperature เป็น 2 เพื่อให้ response มีความสร้างสรรค์สูงสุด:

    # Set temperature
    temp = 2
    

    ค่าที่ 3. สำหรับ output type และ structure เราจะกำหนดดังนี้:

    กำหนด type เป็น "application/json" เพื่อให้ response อยู่ในรูป JSON object:

    # Set output type
    output_type = "application/json"
    

    Note: ดู type อื่น ๆ ได้ที่ Structured output

    กำหนดโครงสร้างของ JSON object ด้วย class และ BaseModel:

    # Set output structure
    class Ingredient(BaseModel):
        name: str
        description: str
        amount: float
        unit: str
    
    class OutputStructure(BaseModel):
        menu: str
        ingredient: list[Ingredient]
        steps: list[str]
        calorie_kcal: float
    

    Note: ดูวิธีใช้ BaseModel ได้ที่ JSON Schema

    หลังกำหนด system prompt, temperature, และ output type กับ structure แล้ว ให้เรารวมค่าทั้งหมดไว้ใน GenerateContentConfig() แบบนี้:

    # Set configuration
    gemini_config = GenerateContentConfig(
    
        # Set system prompt
        system_instruction=system_prompt,
    
        # Set temperature
        temperature=temp,
    
        # Set response type
        response_mime_type=output_type,
    
        # Set response structure
        response_schema=OutputStructure
    )
    

    Note: ดูค่าอื่น ๆ ที่เรากำหนดใน GenerateContentConfig() ได้ที่ Content generation parameters

    .

    📖 Generate Response

    หลังจากกำหนด arguments แล้ว เราจะเรียกใช้ function เพื่อ get response แบบนี้:

    # Generate a recipe
    recipe = get_response(
    
        # Set model
        model=gemini_model,
    
        # Set user prompt
        user_prompt=gemini_user_prompt,
    
        # Set configuration
        config=gemini_config
    )
    

    .

    สุดท้าย เราจะดู response ด้วย print():

    # Print response
    print(recipe)
    

    ผลลัพธ์:

    {
      "menu": "Thai Chicken Burger",
      "ingredient": [
        {
          "name": "Ground Chicken",
          "description": "Lean ground chicken",
          "amount": 150.0,
          "unit": "g"
        },
        {
          "name": "Whole-wheat Burger Bun",
          "description": "Standard size",
          "amount": 1.0,
          "unit": "unit"
        },
        {
          "name": "Lime Juice",
          "description": "Freshly squeezed",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Fish Sauce",
          "description": "Thai fish sauce",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Fresh Ginger",
          "description": "Grated",
          "amount": 1.0,
          "unit": "teaspoon"
        },
        {
          "name": "Garlic",
          "description": "Minced",
          "amount": 1.0,
          "unit": "clove"
        },
        {
          "name": "Cilantro",
          "description": "Fresh, chopped",
          "amount": 2.0,
          "unit": "tablespoons"
        },
        {
          "name": "Green Onion",
          "description": "Chopped",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Red Chilli",
          "description": "Finely minced (optional)",
          "amount": 0.5,
          "unit": "teaspoon"
        },
        {
          "name": "Lettuce Leaf",
          "description": "Fresh, crisp",
          "amount": 1.0,
          "unit": "large"
        },
        {
          "name": "Cucumber",
          "description": "Sliced thinly",
          "amount": 3.0,
          "unit": "slices"
        },
        {
          "name": "Cooking Oil",
          "description": "Any neutral oil",
          "amount": 1.0,
          "unit": "teaspoon"
        }
      ],
      "steps": [
        "Combine ground chicken with fish sauce, lime juice, grated ginger, minced garlic, chopped cilantro, and green onion in a bowl. Mix thoroughly.",
        "Form the seasoned chicken mixture into a single, uniform burger patty. If using chilli, incorporate it now.",
        "Heat cooking oil in a non-stick pan over medium heat. Cook the chicken patty for 5-7 minutes per side, or until it is thoroughly cooked through.",
        "While the patty cooks, lightly toast the whole-wheat burger bun in a dry pan or toaster until golden brown.",
        "Assemble your burger: Place the cooked chicken patty on the bottom half of the toasted bun. Top with fresh lettuce and cucumber slices.",
        "Complete the burger with the top bun. Serve immediately and enjoy your healthy Thai-inspired meal."
      ],
      "calorie_kcal": 450.0
    }
    

    เท่านี้ก็จบ flow การทำงานกับ Gemini API ด้วย google-genai library แล้ว


    😺 Google Colab

    ดูตัวอย่าง code ทั้งหมดได้ที่ Google Colab


    📃 References