Tag: Google Colab

  • สร้าง chatbot ส่วนตัว ใน 5 ขั้นตอน ด้วย OpenAI library ใน Python — ตัวอย่างการสร้าง Gemini chatbot

    สร้าง chatbot ส่วนตัว ใน 5 ขั้นตอน ด้วย OpenAI library ใน Python — ตัวอย่างการสร้าง Gemini chatbot

    ในบทความนี้ เราจะมาดูวิธีสร้าง chatbot ส่วนตัว ด้วย openai library ใน Python ใน 5 ขั้นตอนกัน:

    1. Import libraries
    2. Create a client
    3. Create a chat history
    4. Create a chat function
    5. Chat

    Note: เราจะรัน code ตัวอย่างบน Google Colab ซึ่งทุกคนสามารถดูได้ Gemini Chatbot in Google Colab

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


    1. 🏁 Step 1. Import Libraries
    2. 💁‍♂️ Step 2. Create a Client
    3. 🙊 Step 3. Create a Chat History
    4. 📨 Step 4. Create a Chat Function
    5. 💬 Step 5. Chat
    6. 👍 Google Colab
    7. 📃 References

    🏁 Step 1. Import Libraries

    ในขั้นแรก เราจะโหลด 2 libraries ที่เกี่ยวข้อง ซึ่งได้แก่:

    1. openai: สำหรับเรียกใช้ API ของ AI service *
    2. display และ Markdown: สำหรับแสดง markdown text (อย่างคำตอบที่ส่งมาจาก AI) ให้อ่านง่าย
    # Import libraries
    
    # For Gemini
    from openai import OpenAI
    
    # For text rendering
    from IPython.display import display, Markdown
    

    Note: * openai library ถูกออกแบบสำหรับ OpenAI API แต่สามารถใช้งานกับ AI อื่น ๆ ได้ เช่น:


    💁‍♂️ Step 2. Create a Client

    ในขั้นที่ 2 เราจะสร้าง client เพื่อเชื่อมต่อกับ AI ที่เป็น “สมอง” ของ chatbot ด้วย OpenAI() ซึ่งต้องการ 2 arguments ได้แก่:

    1. api_key: รหัส API ของเรา
    2. base_url: URL สำหรับเรียกใช้ API

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

    # Create client
    client = OpenAI(
        api_key="YOUR_API_KEY_HERE",
        base_url="<https://generativelanguage.googleapis.com/v1beta/openai/>"
    )
    

    Note:

    • ใส่ API key ใน "YOUR_API_KEY_HERE"
    • ดูวิธีสร้าง API key ฟรีได้ที่ Using Gemini API keys
    • สำหรับคนที่จะเรียกใช้ OpenAI API (ChatGPT) แทน Gemini เราสามารถข้ามการเขียน base_url ไปได้

    🙊 Step 3. Create a Chat History

    ในขั้นที่ 3 เราจะสร้าง chat history เพื่อเก็บ:

    1. System prompt ที่กำหนดพฤติกรรมของ chatbot (ในตัวอย่าง เราจะกำหนดให้เป็นผู้ช่วยที่กระตือรือร้น)
    2. ประวัติการพูดคุยระหว่างเรากับ chatbot ซึ่งจะทำให้ chatbot จำสิ่งที่คุยกันได้
    # Set system prompt
    system_prompt = """
    You are a helpful, cheerful, and optimistic assistant.
    
    Be concise, validate answers, and admit when you don’t know.
    
    Make responses clear, easy to read, and sprinkle in playful emoji.
    """
    
    # Instantiate chat history
    chat_history = [
        {
            "role": "system",
            "content": system_prompt
        }
    ]
    

    📨 Step 4. Create a Chat Function

    ในขั้นที่ 4 เราจะสร้าง function ที่จะทำให้เราถาม-ตอบกับ chatbot แบบ real-time ได้:

    # Create a function for chatbot
    def chatbot(model="gemini-2.5-flash"):
    
        # Set chat history as global variable
        global chat_history
    
        # Print chat header
        display(Markdown("# 🟢 --- Chat Begins ---"))
    
        # Print chat instruction
        print("ℹ️ Type \\"end chat\\" to exit.")
    
        # Loop through conversation
        while True:
    
            # Render user prompt display
            display(Markdown("## 🧑‍💻 You:"))
    
            # Get user input
            user_prompt = input("")
    
            # Check if user wants to exit chat
            if user_prompt.lower() == "end chat":
    
                # Print goodbye message
                display(Markdown("## ✨ Assistant:\\n" + "👋 See you later!"))
    
                # End chat
                break
    
            # Append user input to chat history
            chat_history.append(
                {
                    "role": "user",
                    "content": user_prompt
                }
            )
    
            # Get response
            response = client.chat.completions.create(
    
                # Set prompt
                messages=chat_history,
    
                # Set model
                model=model
            )
    
            # Append response to history
            chat_history.append(
                {
                    "role": "assistant",
                    "content": response.choices[0].message.content
                }
            )
    
            # Render response
            display(Markdown("## ✨ Assistant:\\n" + response.choices[0].message.content + "\\n"))
    

    💬 Step 5. Chat

    ในขั้นสุดท้าย เราจะเรียกใช้งาน chatbot() เพื่อเริ่มคุยกับ AI เลย:

    # Start chatting
    chatbot()
    

    ผลลัพธ์:


    👍 Google Colab

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


    📃 References