การสร้างข้อความ

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

การป้อนข้อความ

วิธีที่ง่ายที่สุดในการสร้างข้อความโดยใช้ Gemini API คือการให้อินพุตแบบข้อความเท่านั้นรายการเดียวแก่โมเดล ดังที่แสดงในตัวอย่างต่อไปนี้

PythonJavaScriptGoREST
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["How does AI work?"]
)
print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: "How does AI work?",
  });
  console.log(response.text);
}

await main();
// import packages here

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
  if err != nil {
    log.Fatal(err)
  }
  defer client.Close()

  model := client.GenerativeModel("gemini-2.0-flash")
  resp, err := model.GenerateContent(ctx, genai.Text("How does AI work?"))
  if err != nil {
    log.Fatal(err)
  }
  printResponse(resp) // helper function for printing content parts
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "How does AI work?"
          }
        ]
      }
    ]
  }'

อินพุตรูปภาพ

Gemini API รองรับอินพุตแบบหลายรูปแบบที่รวมไฟล์ข้อความและสื่อ ตัวอย่างต่อไปนี้แสดงวิธีสร้างข้อความจากอินพุตข้อความและรูปภาพ

PythonJavaScriptGoREST
from PIL import Image
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")

image = Image.open("/path/to/organ.png")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=[image, "Tell me about this instrument"]
)
print(response.text)
import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const image = await ai.files.upload({
    file: "/path/to/organ.png",
  });
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: [
      createUserContent([
        "Tell me about this instrument",
        createPartFromUri(image.uri, image.mimeType),
      ]),
    ],
  });
  console.log(response.text);
}

await main();
model := client.GenerativeModel("gemini-2.0-flash")

imgData, err := os.ReadFile(filepath.Join(testDataDir, "organ.jpg"))
if err != nil {
  log.Fatal(err)
}

resp, err := model.GenerateContent(ctx,
  genai.Text("Tell me about this instrument"),
  genai.ImageData("jpeg", imgData))
if err != nil {
  log.Fatal(err)
}

printResponse(resp)
# Use a temporary file to hold the base64 encoded image data
TEMP_B64=$(mktemp)
trap 'rm -f "$TEMP_B64"' EXIT
base64 $B64FLAGS $IMG_PATH > "$TEMP_B64"

# Use a temporary file to hold the JSON payload
TEMP_JSON=$(mktemp)
trap 'rm -f "$TEMP_JSON"' EXIT

cat > "$TEMP_JSON" << EOF
{
  "contents": [
    {
      "parts": [
        {
          "text": "Tell me about this instrument"
        },
        {
          "inline_data": {
            "mime_type": "image/jpeg",
            "data": "$(cat "$TEMP_B64")"
          }
        }
      ]
    }
  ]
}
EOF

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d "@$TEMP_JSON"

เอาต์พุตสตรีมมิง

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

PythonJavaScriptGoREST
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")

response = client.models.generate_content_stream(
    model="gemini-2.0-flash",
    contents=["Explain how AI works"]
)
for chunk in response:
    print(chunk.text, end="")
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const response = await ai.models.generateContentStream({
    model: "gemini-2.0-flash",
    contents: "Explain how AI works",
  });

  for await (const chunk of response) {
    console.log(chunk.text);
  }
}

await main();
model := client.GenerativeModel("gemini-1.5-flash")
iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
  resp, err := iter.Next()
  if err == iterator.Done {
    break
  }
  if err != nil {
    log.Fatal(err)
  }
  printResponse(resp)
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \
  -H 'Content-Type: application/json' \
  --no-buffer \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works"
          }
        ]
      }
    ]
  }'

การสนทนาแบบหลายรอบ

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

ตัวอย่างโค้ดต่อไปนี้แสดงการใช้งานแชทพื้นฐาน

PythonJavaScriptGoREST
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")
chat = client.chats.create(model="gemini-2.0-flash")

response = chat.send_message("I have 2 dogs in my house.")
print(response.text)

response = chat.send_message("How many paws are in my house?")
print(response.text)

for message in chat.get_history():
    print(f'role - {message.role}',end=": ")
    print(message.parts[0].text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const chat = ai.chats.create({
    model: "gemini-2.0-flash",
    history: [
      {
        role: "user",
        parts: [{ text: "Hello" }],
      },
      {
        role: "model",
        parts: [{ text: "Great to meet you. What would you like to know?" }],
      },
    ],
  });

  const response1 = await chat.sendMessage({
    message: "I have 2 dogs in my house.",
  });
  console.log("Chat response 1:", response1.text);

  const response2 = await chat.sendMessage({
    message: "How many paws are in my house?",
  });
  console.log("Chat response 2:", response2.text);
}

await main();
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()

cs.History = []*genai.Content{
  {
    Parts: []genai.Part{
      genai.Text("Hello, I have 2 dogs in my house."),
    },
    Role: "user",
  },
  {
    Parts: []genai.Part{
      genai.Text("Great to meet you. What would you like to know?"),
    },
    Role: "model",
  },
}

res, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))
if err != nil {
  log.Fatal(err)
}
printResponse(res)
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "Hello"
          }
        ]
      },
      {
        "role": "model",
        "parts": [
          {
            "text": "Great to meet you. What would you like to know?"
          }
        ]
      },
      {
        "role": "user",
        "parts": [
          {
            "text": "I have two dogs in my house. How many paws are in my house?"
          }
        ]
      }
    ]
  }'

นอกจากนี้ คุณยังใช้การสตรีมร่วมกับแชทได้ด้วย ดังที่แสดงในตัวอย่างต่อไปนี้

PythonJavaScriptGoREST
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")
chat = client.chats.create(model="gemini-2.0-flash")

response = chat.send_message_stream("I have 2 dogs in my house.")
for chunk in response:
    print(chunk.text, end="")

response = chat.send_message_stream("How many paws are in my house?")
for chunk in response:
    print(chunk.text, end="")

for message in chat.get_history():
    print(f'role - {message.role}', end=": ")
    print(message.parts[0].text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const chat = ai.chats.create({
    model: "gemini-2.0-flash",
    history: [
      {
        role: "user",
        parts: [{ text: "Hello" }],
      },
      {
        role: "model",
        parts: [{ text: "Great to meet you. What would you like to know?" }],
      },
    ],
  });

  const stream1 = await chat.sendMessageStream({
    message: "I have 2 dogs in my house.",
  });
  for await (const chunk of stream1) {
    console.log(chunk.text);
    console.log("_".repeat(80));
  }

  const stream2 = await chat.sendMessageStream({
    message: "How many paws are in my house?",
  });
  for await (const chunk of stream2) {
    console.log(chunk.text);
    console.log("_".repeat(80));
  }
}

await main();
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()

cs.History = []*genai.Content{
  {
    Parts: []genai.Part{
      genai.Text("Hello, I have 2 dogs in my house."),
    },
    Role: "user",
  },
  {
    Parts: []genai.Part{
      genai.Text("Great to meet you. What would you like to know?"),
    },
    Role: "model",
  },
}

iter := cs.SendMessageStream(ctx, genai.Text("How many paws are in my house?"))
for {
  resp, err := iter.Next()
  if err == iterator.Done {
    break
  }
  if err != nil {
    log.Fatal(err)
  }
  printResponse(resp)
}
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "Hello"
          }
        ]
      },
      {
        "role": "model",
        "parts": [
          {
            "text": "Great to meet you. What would you like to know?"
          }
        ]
      },
      {
        "role": "user",
        "parts": [
          {
            "text": "I have two dogs in my house. How many paws are in my house?"
          }
        ]
      }
    ]
  }'

พารามิเตอร์การกําหนดค่า

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

ตัวอย่างต่อไปนี้แสดงวิธีกําหนดค่าพารามิเตอร์ของโมเดล

PythonJavaScriptGoREST
from google import genai
from google.genai import types

client = genai.Client(api_key="GEMINI_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["Explain how AI works"],
    config=types.GenerateContentConfig(
        max_output_tokens=500,
        temperature=0.1
    )
)
print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: "Explain how AI works",
    config: {
      maxOutputTokens: 500,
      temperature: 0.1,
    },
  });
  console.log(response.text);
}

await main();
model := client.GenerativeModel("gemini-1.5-pro-latest")
model.SetTemperature(0.9)
model.SetTopP(0.5)
model.SetTopK(20)
model.SetMaxOutputTokens(100)
model.SystemInstruction = genai.NewUserContent(genai.Text("You are Yoda from Star Wars."))
model.ResponseMIMEType = "application/json"
resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
if err != nil {
  log.Fatal(err)
}
printResponse(resp)
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works"
          }
        ]
      }
    ],
    "generationConfig": {
      "stopSequences": [
        "Title"
      ],
      "temperature": 1.0,
      "maxOutputTokens": 800,
      "topP": 0.8,
      "topK": 10
    }
  }'

ต่อไปนี้คือพารามิเตอร์โมเดลบางส่วนที่คุณกําหนดค่าได้ (รูปแบบการตั้งชื่อจะแตกต่างกันไปตามภาษาโปรแกรม)

  • stopSequences: ระบุชุดลำดับอักขระ (สูงสุด 5 ชุด) ที่จะหยุดการสร้างเอาต์พุต หากระบุไว้ API จะหยุดที่ stop_sequence ที่ปรากฏขึ้นครั้งแรก ระบบจะไม่รวมลําดับการหยุดไว้เป็นส่วนหนึ่งของคําตอบ
  • temperature: ควบคุมความสุ่มของเอาต์พุต ใช้ค่าที่สูงขึ้นสําหรับคําตอบที่สร้างสรรค์มากขึ้น และใช้ค่าที่ต่ำลงสําหรับคําตอบที่แน่นอนมากขึ้น ค่าที่ใช้ได้อยู่ในช่วง [0.0, 2.0]
  • maxOutputTokens: กําหนดจํานวนโทเค็นสูงสุดที่จะรวมไว้ในตัวเลือก
  • topP: เปลี่ยนวิธีที่โมเดลเลือกโทเค็นสําหรับเอาต์พุต ระบบจะเลือกโทเค็นจากความน่าจะเป็นสูงสุดไปจนถึงต่ำสุดจนกว่าผลรวมของความน่าจะเป็นจะเท่ากับค่า topP ค่าเริ่มต้นของ topP คือ 0.95
  • topK: เปลี่ยนวิธีที่โมเดลเลือกโทเค็นสําหรับเอาต์พุต topK เท่ากับ 1 หมายความว่าโทเค็นที่เลือกมีแนวโน้มมากที่สุดในบรรดาโทเค็นทั้งหมดในคลังคำของโมเดล ส่วนtopK เท่ากับ 3 หมายความว่าระบบจะเลือกโทเค็นถัดไปจากโทเค็นที่มีแนวโน้มมากที่สุด 3 รายการโดยใช้อุณหภูมิ ระบบจะกรองโทเค็นเพิ่มเติมตาม topP โดยเลือกโทเค็นสุดท้ายโดยใช้การสุ่มตัวอย่างอุณหภูมิ

วิธีการของระบบ

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

คุณตั้งค่าคำสั่งของระบบได้เมื่อเริ่มต้นโมเดล ดังนี้

PythonJavaScriptGoREST
from google import genai
from google.genai import types

client = genai.Client(api_key="GEMINI_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash",
    config=types.GenerateContentConfig(
        system_instruction="You are a cat. Your name is Neko."),
    contents="Hello there"
)

print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: "Hello there",
    config: {
      systemInstruction: "You are a cat. Your name is Neko.",
    },
  });
  console.log(response.text);
}

await main();
// import packages here

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
  if err != nil {
    log.Fatal(err)
  }
  defer client.Close()

  model := client.GenerativeModel("gemini-2.0-flash")
  model.SystemInstruction = &genai.Content{
    Parts: []genai.Part{genai.Text(`
      You are a cat. Your name is Neko.
    `)},
  }
  resp, err := model.GenerateContent(ctx, genai.Text("Hello there"))
  if err != nil {
    log.Fatal(err)
  }
  printResponse(resp) // helper function for printing content parts
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "system_instruction": {
      "parts": [
        {
          "text": "You are a cat. Your name is Neko."
        }
      ]
    },
    "contents": [
      {
        "parts": [
          {
            "text": "Hello there"
          }
        ]
      }
    ]
  }'

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

โมเดลที่รองรับ

โมเดลทั้งหมดในตระกูล Gemini รองรับการสร้างข้อความ ดูข้อมูลเพิ่มเติมเกี่ยวกับรูปแบบและความสามารถของรูปแบบได้ที่รูปแบบ

เคล็ดลับเกี่ยวกับพรอมต์

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

ขั้นตอนถัดไป