Tuning

เมธอด: TunModels.generateContent

สร้างการตอบสนองจากโมเดลที่มีอินพุต GenerateContentRequest

ความสามารถในการป้อนข้อมูลจะแตกต่างกันไปในแต่ละโมเดล รวมถึงโมเดลที่ปรับแต่งด้วย ดูรายละเอียดได้ในคู่มือรุ่นและคู่มือการปรับแต่ง

ปลายทาง

โพสต์ https://generativelanguage.googleapis.com/v1beta/{model=tunedModels/*}:generateContent

พารามิเตอร์เส้นทาง

model string

ต้องระบุ ชื่อของ Model ที่จะใช้ในการสร้างการดำเนินการให้เสร็จสมบูรณ์

รูปแบบ: name=models/{model} โดยใช้รูปแบบ tunedModels/{tunedmodel}

เนื้อหาของคำขอ

เนื้อหาของคำขอมีข้อมูลที่มีโครงสร้างต่อไปนี้

ช่อง
contents[] object (Content)

ต้องระบุ เนื้อหาของการสนทนาปัจจุบันกับโมเดล

สำหรับการค้นหาแบบเลี้ยวเดียว อินสแตนซ์นี้เป็นอินสแตนซ์เดียว สำหรับการค้นหาแบบหลายเลี้ยว ช่องนี้เป็นฟิลด์ที่ซ้ำได้ซึ่งมีประวัติการสนทนาและคำขอล่าสุด

tools[] object (Tool)

ไม่บังคับ รายการของ Tools ที่โมเดลอาจใช้เพื่อสร้างคำตอบถัดไป

Tool คือโค้ดที่ช่วยให้ระบบโต้ตอบกับระบบภายนอกเพื่อดำเนินการหรือชุดการดำเนินการที่อยู่นอกเหนือความรู้และขอบเขตของโมเดลได้ เครื่องมือที่รองรับมีเพียง Function ในขณะนี้

toolConfig object (ToolConfig)

ไม่บังคับ การกำหนดค่าเครื่องมือสำหรับ Tool ที่ระบุไว้ในคำขอ

safetySettings[] object (SafetySetting)

ไม่บังคับ รายการอินสแตนซ์ SafetySetting ที่ไม่ซ้ำกันสำหรับการบล็อกเนื้อหาที่ไม่ปลอดภัย

สิ่งนี้จะบังคับใช้ในGenerateContentRequest.contentsและGenerateContentResponse.candidates ประเภท SafetyCategory แต่ละประเภทไม่ควรมีการตั้งค่ามากกว่า 1 รายการ API จะบล็อกเนื้อหาและการตอบกลับทั้งหมดที่ไม่ตรงตามเกณฑ์ที่การตั้งค่าเหล่านี้กำหนดไว้ รายการนี้จะลบล้างการตั้งค่าเริ่มต้นสำหรับแต่ละ SafetyCategory ที่ระบุใน safetySettings หากไม่มี SafetySetting สำหรับ SafetyCategory ที่ระบุในรายการ API จะใช้การตั้งค่าความปลอดภัยเริ่มต้นสำหรับหมวดหมู่นั้น สนับสนุนหมวดหมู่อันตราย HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT

systemInstruction object (Content)

ไม่บังคับ คำสั่งของระบบชุดนักพัฒนาแอป ขณะนี้มีเพียงข้อความเท่านั้น

generationConfig object (GenerationConfig)

ไม่บังคับ ตัวเลือกการกำหนดค่าสำหรับการสร้างและเอาต์พุตโมเดล

cachedContent string

ไม่บังคับ ชื่อของเนื้อหาที่แคชซึ่งใช้เป็นบริบทในการแสดงการคาดการณ์ หมายเหตุ: ใช้การแคชอย่างชัดแจ้งเท่านั้น ซึ่งผู้ใช้สามารถควบคุมการแคชได้ (เช่น เนื้อหาที่จะแคช) และประหยัดต้นทุนอย่างแน่นอน รูปแบบ: cachedContents/{cachedContent}

ตัวอย่างคำขอ

ข้อความ

Python

model = genai.GenerativeModel("gemini-1.5-flash")
response = model.generate_content("Write a story about a magic backpack.")
print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Write a story about a magic backpack.";

const result = await model.generateContent(prompt);
console.log(result.response.text());

Kotlin

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)

Swift

let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

let prompt = "Write a story about a magic backpack."
let response = try await generativeModel.generateContent(prompt)
if let text = response.text {
  print(text)
}

Dart

final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Write a story about a magic backpack.';

final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Java

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Content content =
    new Content.Builder().addText("Write a story about a magic backpack.").build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);

รูปภาพ

Python

import PIL.Image

model = genai.GenerativeModel("gemini-1.5-flash")
organ = PIL.Image.open(media / "organ.jpg")
response = model.generate_content(["Tell me about this instrument", organ])
print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType,
    },
  };
}

const prompt = "Describe how this product might be manufactured.";
// Note: The only accepted mime types are some image types, image/*.
const imagePart = fileToGenerativePart(
  `${mediaPath}/jetpack.jpg`,
  "image/jpeg",
);

const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());

Kotlin

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val image: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image)
val inputContent = content {
  image(image)
  text("What's in this picture?")
}

val response = generativeModel.generateContent(inputContent)
print(response.text)

Swift

let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

guard let image = UIImage(systemName: "cloud.sun") else { fatalError() }

let prompt = "What's in this picture?"

let response = try await generativeModel.generateContent(image, prompt)
if let text = response.text {
  print(text)
}

Dart

final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);

Future<DataPart> fileToPart(String mimeType, String path) async {
  return DataPart(mimeType, await File(path).readAsBytes());
}

final prompt = 'Describe how this product might be manufactured.';
final image = await fileToPart('image/jpeg', 'resources/jetpack.jpg');

final response = await model.generateContent([
  Content.multi([TextPart(prompt), image])
]);
print(response.text);

Java

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap image = BitmapFactory.decodeResource(context.getResources(), R.drawable.image);

Content content =
    new Content.Builder()
        .addText("What's different between these pictures?")
        .addImage(image)
        .build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);

เสียง

Python

model = genai.GenerativeModel("gemini-1.5-flash")
sample_audio = genai.upload_file(media / "sample.mp3")
response = model.generate_content(["Give me a summary of this audio file.", sample_audio])
print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType,
    },
  };
}

const prompt = "Give me a summary of this audio file.";
// Note: The only accepted mime types are some image types, image/*.
const audioPart = fileToGenerativePart(
  `${mediaPath}/samplesmall.mp3`,
  "audio/mp3",
);

const result = await model.generateContent([prompt, audioPart]);
console.log(result.response.text());

วิดีโอ

Python

import time

# Video clip (CC BY 3.0) from https://peach.blender.org/download/
myfile = genai.upload_file(media / "Big_Buck_Bunny.mp4")
print(f"{myfile=}")

# Videos need to be processed before you can use them.
while myfile.state.name == "PROCESSING":
    print("processing video...")
    time.sleep(5)
    myfile = genai.get_file(myfile.name)

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content([myfile, "Describe this video clip"])
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
// import { GoogleAIFileManager, FileState } from "@google/generative-ai/server";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/Big_Buck_Bunny.mp4`,
  { mimeType: "video/mp4" },
);

let file = await fileManager.getFile(uploadResult.file.name);
while (file.state === FileState.PROCESSING) {
  process.stdout.write(".");
  // Sleep for 10 seconds
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  // Fetch the file from the API again
  file = await fileManager.getFile(uploadResult.file.name);
}

if (file.state === FileState.FAILED) {
  throw new Error("Video processing failed.");
}

const prompt = "Describe this video clip";
const videoPart = {
  fileData: {
    fileUri: uploadResult.file.uri,
    mimeType: uploadResult.file.mimeType,
  },
};

const result = await model.generateContent([prompt, videoPart]);
console.log(result.response.text());

แชท

Python

model = genai.GenerativeModel("gemini-1.5-flash")
chat = model.start_chat(
    history=[
        {"role": "user", "parts": "Hello"},
        {"role": "model", "parts": "Great to meet you. What would you like to know?"},
    ]
)
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)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: [{ text: "Hello" }],
    },
    {
      role: "model",
      parts: [{ text: "Great to meet you. What would you like to know?" }],
    },
  ],
});
let result = await chat.sendMessage("I have 2 dogs in my house.");
console.log(result.response.text());
result = await chat.sendMessage("How many paws are in my house?");
console.log(result.response.text());

เปลือกหอย

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_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?"}]},
      ]
    }' 2> /dev/null | grep "text"

Kotlin

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey)

val chat =
    generativeModel.startChat(
        history =
            listOf(
                content(role = "user") { text("Hello, I have 2 dogs in my house.") },
                content(role = "model") {
                  text("Great to meet you. What would you like to know?")
                }))

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

Swift

let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default
  )

// Optionally specify existing chat history
let history = [
  ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."),
  ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"),
]

// Initialize the chat with optional chat history
let chat = generativeModel.startChat(history: history)

// To generate text output, call sendMessage and pass in the message
let response = try await chat.sendMessage("How many paws are in my house?")
if let text = response.text {
  print(text)
}

Dart

final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final chat = model.startChat(history: [
  Content.text('hello'),
  Content.model([TextPart('Great to meet you. What would you like to know?')])
]);
var response =
    await chat.sendMessage(Content.text('I have 2 dogs in my house.'));
print(response.text);
response =
    await chat.sendMessage(Content.text('How many paws are in my house?'));
print(response.text);

Java

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

// (optional) Create previous chat history for context
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();

Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();

List<Content> history = Arrays.asList(userContent, modelContent);

// Initialize the chat
ChatFutures chat = model.startChat(history);

// Create a new user message
Content.Builder userMessageBuilder = new Content.Builder();
userMessageBuilder.setRole("user");
userMessageBuilder.addText("How many paws are in my house?");
Content userMessage = userMessageBuilder.build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(userMessage);

Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);

แคช

Python

document = genai.upload_file(path=media / "a11.txt")
model_name = "gemini-1.5-flash-001"
cache = genai.caching.CachedContent.create(
    model=model_name,
    system_instruction="You are an expert analyzing transcripts.",
    contents=[document],
)
print(cache)

model = genai.GenerativeModel.from_cached_content(cache)
response = model.generate_content("Please summarize this transcript")
print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const cacheManager = new GoogleAICacheManager(process.env.API_KEY);
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
});

const cacheResult = await cacheManager.create({
  model: "models/gemini-1.5-flash-001",
  contents: [
    {
      role: "user",
      parts: [
        {
          fileData: {
            fileUri: uploadResult.file.uri,
            mimeType: uploadResult.file.mimeType,
          },
        },
      ],
    },
  ],
});

console.log(cacheResult);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModelFromCachedContent(cacheResult);
const result = await model.generateContent(
  "Please summarize this transcript.",
);
console.log(result.response.text());

โมเดลที่ปรับแล้ว

Python

model = genai.GenerativeModel(model_name="tunedModels/my-increment-model")
result = model.generate_content("III")
print(result.text)  # "IV"

โหมด JSON

Python

import typing_extensions as typing

class Recipe(typing.TypedDict):
    recipe_name: str

model = genai.GenerativeModel("gemini-1.5-pro-latest")
result = model.generate_content(
    "List a few popular cookie recipes.",
    generation_config=genai.GenerationConfig(
        response_mime_type="application/json", response_schema=list([Recipe])
    ),
)
print(result)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI, FunctionDeclarationSchemaType } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

const schema = {
  description: "List of recipes",
  type: FunctionDeclarationSchemaType.ARRAY,
  items: {
    type: FunctionDeclarationSchemaType.OBJECT,
    properties: {
      recipeName: {
        type: FunctionDeclarationSchemaType.STRING,
        description: "Name of the recipe",
        nullable: false,
      },
    },
    required: ["recipeName"],
  },
};

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-pro",
  generationConfig: {
    responseMimeType: "application/json",
    responseSchema: schema,
  },
});

const result = await model.generateContent(
  "List a few popular cookie recipes.",
);
console.log(result.response.text());

Kotlin

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-pro",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey,
        generationConfig = generationConfig {
            responseMimeType = "application/json"
            responseSchema = Schema(
                name = "recipes",
                description = "List of recipes",
                type = FunctionType.ARRAY,
                items = Schema(
                    name = "recipe",
                    description = "A recipe",
                    type = FunctionType.OBJECT,
                    properties = mapOf(
                        "recipeName" to Schema(
                            name = "recipeName",
                            description = "Name of the recipe",
                            type = FunctionType.STRING,
                            nullable = false
                        ),
                    ),
                    required = listOf("recipeName")
                ),
            )
        })

val prompt = "List a few popular cookie recipes."
val response = generativeModel.generateContent(prompt)
print(response.text)

Swift

let jsonSchema = Schema(
  type: .array,
  description: "List of recipes",
  items: Schema(
    type: .object,
    properties: [
      "recipeName": Schema(type: .string, description: "Name of the recipe", nullable: false),
    ],
    requiredProperties: ["recipeName"]
  )
)

let generativeModel = GenerativeModel(
  // Specify a model that supports controlled generation like Gemini 1.5 Pro
  name: "gemini-1.5-pro",
  // Access your API key from your on-demand resource .plist file (see "Set up your API key"
  // above)
  apiKey: APIKey.default,
  generationConfig: GenerationConfig(
    responseMIMEType: "application/json",
    responseSchema: jsonSchema
  )
)

let prompt = "List a few popular cookie recipes."
let response = try await generativeModel.generateContent(prompt)
if let text = response.text {
  print(text)
}

Dart

final schema = Schema.array(
    description: 'List of recipes',
    items: Schema.object(properties: {
      'recipeName':
          Schema.string(description: 'Name of the recipe.', nullable: false)
    }, requiredProperties: [
      'recipeName'
    ]));

final model = GenerativeModel(
    model: 'gemini-1.5-pro',
    apiKey: apiKey,
    generationConfig: GenerationConfig(
        responseMimeType: 'application/json', responseSchema: schema));

final prompt = 'List a few popular cookie recipes.';
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Java

Schema<List<String>> schema =
    new Schema(
        /* name */ "recipes",
        /* description */ "List of recipes",
        /* format */ null,
        /* nullable */ false,
        /* list */ null,
        /* properties */ null,
        /* required */ null,
        /* items */ new Schema(
            /* name */ "recipe",
            /* description */ "A recipe",
            /* format */ null,
            /* nullable */ false,
            /* list */ null,
            /* properties */ Map.of(
                "recipeName",
                new Schema(
                    /* name */ "recipeName",
                    /* description */ "Name of the recipe",
                    /* format */ null,
                    /* nullable */ false,
                    /* list */ null,
                    /* properties */ null,
                    /* required */ null,
                    /* items */ null,
                    /* type */ FunctionType.STRING)),
            /* required */ null,
            /* items */ null,
            /* type */ FunctionType.OBJECT),
        /* type */ FunctionType.ARRAY);

GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "application/json";
configBuilder.responseSchema = schema;

GenerationConfig generationConfig = configBuilder.build();

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-pro",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey,
        /* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Content content = new Content.Builder().addText("List a few popular cookie recipes.").build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }
    },
    executor);

การเรียกใช้โค้ด

Python

model = genai.GenerativeModel(model_name="gemini-1.5-flash", tools="code_execution")
response = model.generate_content(
    (
        "What is the sum of the first 50 prime numbers? "
        "Generate and run code for the calculation, and make sure you get all 50."
    )
)

# Each `part` either contains `text`, `executable_code` or an `execution_result`
for part in result.candidates[0].content.parts:
    print(part, "\n")

print("-" * 80)
# The `.text` accessor joins the parts into a markdown compatible text representation.
print("\n\n", response.text)

Kotlin


val model = GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    modelName = "gemini-1.5-pro",
    // Access your API key as a Build Configuration variable (see "Set up your API key" above)
    apiKey = BuildConfig.apiKey,
    tools = listOf(Tool.CODE_EXECUTION)
)

val response = model.generateContent("What is the sum of the first 50 prime numbers?")

// Each `part` either contains `text`, `executable_code` or an `execution_result`
println(response.candidates[0].content.parts.joinToString("\n"))

// Alternatively, you can use the `text` accessor which joins the parts into a markdown compatible
// text representation
println(response.text)

Java

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
        new GenerativeModel(
                /* modelName */ "gemini-1.5-pro",
                // Access your API key as a Build Configuration variable (see "Set up your API key"
                // above)
                /* apiKey */ BuildConfig.apiKey,
                /* generationConfig */ null,
                /* safetySettings */ null,
                /* requestOptions */ new RequestOptions(),
                /* tools */ Collections.singletonList(Tool.CODE_EXECUTION));
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Content inputContent =
        new Content.Builder().addText("What is the sum of the first 50 prime numbers?").build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

ListenableFuture<GenerateContentResponse> response = model.generateContent(inputContent);
Futures.addCallback(
        response,
        new FutureCallback<GenerateContentResponse>() {
            @Override
            public void onSuccess(GenerateContentResponse result) {
                // Each `part` either contains `text`, `executable_code` or an
                // `execution_result`
                Candidate candidate = result.getCandidates().get(0);
                for (Part part : candidate.getContent().getParts()) {
                    System.out.println(part);
                }

                // Alternatively, you can use the `text` accessor which joins the parts into a
                // markdown compatible text representation
                String resultText = result.getText();
                System.out.println(resultText);
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        },
        executor);

การเรียกใช้ฟังก์ชัน

Python

def add(a: float, b: float):
    """returns a + b."""
    return a + b

def subtract(a: float, b: float):
    """returns a - b."""
    return a - b

def multiply(a: float, b: float):
    """returns a * b."""
    return a * b

def divide(a: float, b: float):
    """returns a / b."""
    return a / b

model = genai.GenerativeModel(
    model_name="gemini-1.5-flash", tools=[add, subtract, multiply, divide]
)
chat = model.start_chat(enable_automatic_function_calling=True)
response = chat.send_message(
    "I have 57 cats, each owns 44 mittens, how many mittens is that in total?"
)
print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
async function setLightValues(brightness, colorTemperature) {
  // This mock API returns the requested lighting values
  return {
    brightness,
    colorTemperature,
  };
}

const controlLightFunctionDeclaration = {
  name: "controlLight",
  parameters: {
    type: "OBJECT",
    description: "Set the brightness and color temperature of a room light.",
    properties: {
      brightness: {
        type: "NUMBER",
        description:
          "Light level from 0 to 100. Zero is off and 100 is full brightness.",
      },
      colorTemperature: {
        type: "STRING",
        description:
          "Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.",
      },
    },
    required: ["brightness", "colorTemperature"],
  },
};

// Executable function code. Put it in a map keyed by the function name
// so that you can call it once you get the name string from the model.
const functions = {
  controlLight: ({ brightness, colorTemperature }) => {
    return setLightValues(brightness, colorTemperature);
  },
};

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  tools: { functionDeclarations: [controlLightFunctionDeclaration] },
});
const chat = model.startChat();
const prompt = "Dim the lights so the room feels cozy and warm.";

// Send the message to the model.
const result = await chat.sendMessage(prompt);

// For simplicity, this uses the first function call found.
const call = result.response.functionCalls()[0];

if (call) {
  // Call the executable function named in the function call
  // with the arguments specified in the function call and
  // let it call the hypothetical API.
  const apiResponse = await functions[call.name](call.args);

  // Send the API response back to the model so it can generate
  // a text response that can be displayed to the user.
  const result2 = await chat.sendMessage([
    {
      functionResponse: {
        name: "controlLight",
        response: apiResponse,
      },
    },
  ]);

  // Log the text response.
  console.log(result2.response.text());
}

Kotlin

fun multiply(a: Double, b: Double) = a * b

val multiplyDefinition = defineFunction(
    name = "multiply",
    description = "returns the product of the provided numbers.",
    parameters = listOf(
    Schema.double("a", "First number"),
    Schema.double("b", "Second number")
    )
)

val usableFunctions = listOf(multiplyDefinition)

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key" above)
        apiKey = BuildConfig.apiKey,
        // List the functions definitions you want to make available to the model
        tools = listOf(Tool(usableFunctions))
    )

val chat = generativeModel.startChat()
val prompt = "I have 57 cats, each owns 44 mittens, how many mittens is that in total?"

// Send the message to the generative model
var response = chat.sendMessage(prompt)

// Check if the model responded with a function call
response.functionCalls.first { it.name == "multiply" }.apply {
    val a: String by args
    val b: String by args

    val result = JSONObject(mapOf("result" to multiply(a.toDouble(), b.toDouble())))
    response = chat.sendMessage(
        content(role = "function") {
            part(FunctionResponsePart("multiply", result))
        }
    )
}

// Whenever the model responds with text, show it in the UI
response.text?.let { modelResponse ->
    println(modelResponse)
}

Swift

// Calls a hypothetical API to control a light bulb and returns the values that were set.
func controlLight(brightness: Double, colorTemperature: String) -> JSONObject {
  return ["brightness": .number(brightness), "colorTemperature": .string(colorTemperature)]
}

let generativeModel =
  GenerativeModel(
    // Use a model that supports function calling, like a Gemini 1.5 model
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    tools: [Tool(functionDeclarations: [
      FunctionDeclaration(
        name: "controlLight",
        description: "Set the brightness and color temperature of a room light.",
        parameters: [
          "brightness": Schema(
            type: .number,
            format: "double",
            description: "Light level from 0 to 100. Zero is off and 100 is full brightness."
          ),
          "colorTemperature": Schema(
            type: .string,
            format: "enum",
            description: "Color temperature of the light fixture.",
            enumValues: ["daylight", "cool", "warm"]
          ),
        ],
        requiredParameters: ["brightness", "colorTemperature"]
      ),
    ])]
  )

let chat = generativeModel.startChat()

let prompt = "Dim the lights so the room feels cozy and warm."

// Send the message to the model.
let response1 = try await chat.sendMessage(prompt)

// Check if the model responded with a function call.
// For simplicity, this sample uses the first function call found.
guard let functionCall = response1.functionCalls.first else {
  fatalError("Model did not respond with a function call.")
}
// Print an error if the returned function was not declared
guard functionCall.name == "controlLight" else {
  fatalError("Unexpected function called: \(functionCall.name)")
}
// Verify that the names and types of the parameters match the declaration
guard case let .number(brightness) = functionCall.args["brightness"] else {
  fatalError("Missing argument: brightness")
}
guard case let .string(colorTemperature) = functionCall.args["colorTemperature"] else {
  fatalError("Missing argument: colorTemperature")
}

// Call the executable function named in the FunctionCall with the arguments specified in the
// FunctionCall and let it call the hypothetical API.
let apiResponse = controlLight(brightness: brightness, colorTemperature: colorTemperature)

// Send the API response back to the model so it can generate a text response that can be
// displayed to the user.
let response2 = try await chat.sendMessage([ModelContent(
  role: "function",
  parts: [.functionResponse(FunctionResponse(name: "controlLight", response: apiResponse))]
)])

if let text = response2.text {
  print(text)
}

Dart

Map<String, Object?> setLightValues(Map<String, Object?> args) {
  return args;
}

final controlLightFunction = FunctionDeclaration(
    'controlLight',
    'Set the brightness and color temperature of a room light.',
    Schema.object(properties: {
      'brightness': Schema.number(
          description:
              'Light level from 0 to 100. Zero is off and 100 is full brightness.',
          nullable: false),
      'colorTemperatur': Schema.string(
          description:
              'Color temperature of the light fixture which can be `daylight`, `cool`, or `warm`',
          nullable: false),
    }));

final functions = {controlLightFunction.name: setLightValues};
FunctionResponse dispatchFunctionCall(FunctionCall call) {
  final function = functions[call.name]!;
  final result = function(call.args);
  return FunctionResponse(call.name, result);
}

final model = GenerativeModel(
  model: 'gemini-1.5-pro',
  apiKey: apiKey,
  tools: [
    Tool(functionDeclarations: [controlLightFunction])
  ],
);

final prompt = 'Dim the lights so the room feels cozy and warm.';
final content = [Content.text(prompt)];
var response = await model.generateContent(content);

List<FunctionCall> functionCalls;
while ((functionCalls = response.functionCalls.toList()).isNotEmpty) {
  var responses = <FunctionResponse>[
    for (final functionCall in functionCalls)
      dispatchFunctionCall(functionCall)
  ];
  content
    ..add(response.candidates.first.content)
    ..add(Content.functionResponses(responses));
  response = await model.generateContent(content);
}
print('Response: ${response.text}');

Java

FunctionDeclaration multiplyDefinition =
    defineFunction(
        /* name  */ "multiply",
        /* description */ "returns a * b.",
        /* parameters */ Arrays.asList(
            Schema.numDouble("a", "First parameter"),
            Schema.numDouble("b", "Second parameter")),
        /* required */ Arrays.asList("a", "b"));

Tool tool = new Tool(Arrays.asList(multiplyDefinition), null);

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        /* modelName */ "gemini-1.5-flash",
        // Access your API key as a Build Configuration variable (see "Set up your API key"
        // above)
        /* apiKey */ BuildConfig.apiKey,
        /* generationConfig (optional) */ null,
        /* safetySettings (optional) */ null,
        /* requestOptions (optional) */ new RequestOptions(),
        /* functionDeclarations (optional) */ Arrays.asList(tool));
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

// Create prompt
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText(
    "I have 57 cats, each owns 44 mittens, how many mittens is that in total?");
Content userMessage = userContentBuilder.build();

// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();

// Initialize the chat
ChatFutures chat = model.startChat();

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(userMessage);

Futures.addCallback(
    response,
    new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
        if (!result.getFunctionCalls().isEmpty()) {
          handleFunctionCall(result);
        }
        if (!result.getText().isEmpty()) {
          System.out.println(result.getText());
        }
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace();
      }

      private void handleFunctionCall(GenerateContentResponse result) {
        FunctionCallPart multiplyFunctionCallPart =
            result.getFunctionCalls().stream()
                .filter(fun -> fun.getName().equals("multiply"))
                .findFirst()
                .get();
        double a = Double.parseDouble(multiplyFunctionCallPart.getArgs().get("a"));
        double b = Double.parseDouble(multiplyFunctionCallPart.getArgs().get("b"));

        try {
          // `multiply(a, b)` is a regular java function defined in another class
          FunctionResponsePart functionResponsePart =
              new FunctionResponsePart(
                  "multiply", new JSONObject().put("result", multiply(a, b)));

          // Create prompt
          Content.Builder functionCallResponse = new Content.Builder();
          userContentBuilder.setRole("user");
          userContentBuilder.addPart(functionResponsePart);
          Content userMessage = userContentBuilder.build();

          chat.sendMessage(userMessage);
        } catch (JSONException e) {
          throw new RuntimeException(e);
        }
      }
    },
    executor);

การกำหนดค่าการสร้าง

Python

model = genai.GenerativeModel("gemini-1.5-flash")
response = model.generate_content(
    "Tell me a story about a magic backpack.",
    generation_config=genai.types.GenerationConfig(
        # Only one candidate for now.
        candidate_count=1,
        stop_sequences=["x"],
        max_output_tokens=20,
        temperature=1.0,
    ),
)

print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  generationConfig: {
    candidateCount: 1,
    stopSequences: ["x"],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

const result = await model.generateContent(
  "Tell me a story about a magic backpack.",
);
console.log(result.response.text());

เปลือกหอย

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
        "contents": [{
            "parts":[
                {"text": "Write a story about a magic backpack."}
            ]
        }],
        "safetySettings": [
            {
                "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
                "threshold": "BLOCK_ONLY_HIGH"
            }
        ],
        "generationConfig": {
            "stopSequences": [
                "Title"
            ],
            "temperature": 1.0,
            "maxOutputTokens": 800,
            "topP": 0.8,
            "topK": 10
        }
    }'  2> /dev/null | grep "text"

Kotlin

val config = generationConfig {
  temperature = 0.9f
  topK = 16
  topP = 0.1f
  maxOutputTokens = 200
  stopSequences = listOf("red")
}

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        generationConfig = config)

Swift

let config = GenerationConfig(
  temperature: 0.9,
  topP: 0.1,
  topK: 16,
  candidateCount: 1,
  maxOutputTokens: 200,
  stopSequences: ["red", "orange"]
)

let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    generationConfig: config
  )

Dart

final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Tell me a story about a magic backpack.';

final response = await model.generateContent(
  [Content.text(prompt)],
  generationConfig: GenerationConfig(
    candidateCount: 1,
    stopSequences: ['x'],
    maxOutputTokens: 20,
    temperature: 1.0,
  ),
);
print(response.text);

Java

GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.temperature = 0.9f;
configBuilder.topK = 16;
configBuilder.topP = 0.1f;
configBuilder.maxOutputTokens = 200;
configBuilder.stopSequences = Arrays.asList("red");

GenerationConfig generationConfig = configBuilder.build();

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel("gemini-1.5-flash", BuildConfig.apiKey, generationConfig);

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

การตั้งค่าความปลอดภัย

Python

model = genai.GenerativeModel("gemini-1.5-flash")
unsafe_prompt = "I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them."
response = model.generate_content(
    unsafe_prompt,
    safety_settings={
        "HATE": "MEDIUM",
        "HARASSMENT": "BLOCK_ONLY_HIGH",
    },
)
# If you want to set all the safety_settings to the same value you can just pass that value:
response = model.generate_content(unsafe_prompt, safety_settings="MEDIUM")
try:
    print(response.text)
except:
    print("No information generated by the model.")

print(response.candidates[0].safety_ratings)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  safetySettings: [
    {
      category: HarmCategory.HARM_CATEGORY_HARASSMENT,
      threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
    },
    {
      category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
      threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    },
  ],
});

const unsafePrompt =
  "I support Martians Soccer Club and I think " +
  "Jupiterians Football Club sucks! Write an ironic phrase telling " +
  "them how I feel about them.";

const result = await model.generateContent(unsafePrompt);

try {
  result.response.text();
} catch (e) {
  console.error(e);
  console.log(result.response.candidates[0].safetyRatings);
}

เปลือกหอย

echo '{
    "safetySettings": [
        {'category': HARM_CATEGORY_HARASSMENT, 'threshold': BLOCK_ONLY_HIGH},
        {'category': HARM_CATEGORY_HATE_SPEECH, 'threshold': BLOCK_MEDIUM_AND_ABOVE}
    ],
    "contents": [{
        "parts":[{
            "text": "'I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them.'"}]}]}' > request.json

    curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=$GOOGLE_API_KEY" \
        -H 'Content-Type: application/json' \
        -X POST \
        -d @request.json  2> /dev/null > response.json

    jq .promptFeedback > response.json

Kotlin

val harassmentSafety = SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH)

val hateSpeechSafety = SafetySetting(HarmCategory.HATE_SPEECH, BlockThreshold.MEDIUM_AND_ABOVE)

val generativeModel =
    GenerativeModel(
        // The Gemini 1.5 models are versatile and work with most use cases
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        safetySettings = listOf(harassmentSafety, hateSpeechSafety))

Swift

let safetySettings = [
  SafetySetting(harmCategory: .dangerousContent, threshold: .blockLowAndAbove),
  SafetySetting(harmCategory: .harassment, threshold: .blockMediumAndAbove),
  SafetySetting(harmCategory: .hateSpeech, threshold: .blockOnlyHigh),
]

let generativeModel =
  GenerativeModel(
    // Specify a Gemini model appropriate for your use case
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    safetySettings: safetySettings
  )

Dart

final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'I support Martians Soccer Club and I think '
    'Jupiterians Football Club sucks! Write an ironic phrase telling '
    'them how I feel about them.';

final response = await model.generateContent(
  [Content.text(prompt)],
  safetySettings: [
    SafetySetting(HarmCategory.harassment, HarmBlockThreshold.medium),
    SafetySetting(HarmCategory.hateSpeech, HarmBlockThreshold.low),
  ],
);
try {
  print(response.text);
} catch (e) {
  print(e);
  for (final SafetyRating(:category, :probability)
      in response.candidates.first.safetyRatings!) {
    print('Safety Rating: $category - $probability');
  }
}

Java

SafetySetting harassmentSafety =
    new SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH);

SafetySetting hateSpeechSafety =
    new SafetySetting(HarmCategory.HATE_SPEECH, BlockThreshold.MEDIUM_AND_ABOVE);

// Specify a Gemini model appropriate for your use case
GenerativeModel gm =
    new GenerativeModel(
        "gemini-1.5-flash",
        BuildConfig.apiKey,
        null, // generation config is optional
        Arrays.asList(harassmentSafety, hateSpeechSafety));

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

คำแนะนำของระบบ

Python

model = genai.GenerativeModel(
    "models/gemini-1.5-flash",
    system_instruction="You are a cat. Your name is Neko.",
)
response = model.generate_content("Good morning! How are you?")
print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  systemInstruction: "You are a cat. Your name is Neko.",
});

const prompt = "Good morning! How are you?";

const result = await model.generateContent(prompt);
const response = result.response;
const text = response.text();
console.log(text);

Kotlin

val generativeModel =
    GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        modelName = "gemini-1.5-flash",
        apiKey = BuildConfig.apiKey,
        systemInstruction = content { text("You are a cat. Your name is Neko.") },
    )

Swift

let generativeModel =
  GenerativeModel(
    // Specify a model that supports system instructions, like a Gemini 1.5 model
    name: "gemini-1.5-flash",
    // Access your API key from your on-demand resource .plist file (see "Set up your API key"
    // above)
    apiKey: APIKey.default,
    systemInstruction: ModelContent(role: "system", parts: "You are a cat. Your name is Neko.")
  )

Dart

final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
  systemInstruction: Content.system('You are a cat. Your name is Neko.'),
);
final prompt = 'Good morning! How are you?';

final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Java

GenerativeModel model =
    new GenerativeModel(
        // Specify a Gemini model appropriate for your use case
        /* modelName */ "gemini-1.5-flash",
        /* apiKey */ BuildConfig.apiKey,
        /* generationConfig (optional) */ null,
        /* safetySettings (optional) */ null,
        /* requestOptions (optional) */ new RequestOptions(),
        /* tools (optional) */ null,
        /* toolsConfig (optional) */ null,
        /* systemInstruction (optional) */ new Content.Builder()
            .addText("You are a cat. Your name is Neko.")
            .build());

เนื้อหาการตอบกลับ

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีอินสแตนซ์ GenerateContentResponse

เมธอด: TunModels.create

สร้างโมเดลที่ปรับแต่ง เข้าถึงความคืบหน้าในการปรับแต่งขั้นกลาง (หากมี) ผ่านบริการ google.longrunning.Operations

คุณสามารถเข้าถึงสถานะและผลลัพธ์ผ่านบริการการดำเนินการ ตัวอย่าง: GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222

ปลายทาง

โพสต์ https://generativelanguage.googleapis.com/v1beta/tunedModels

พารามิเตอร์การค้นหา

tunedModelId string

ไม่บังคับ รหัสที่ไม่ซ้ำกันสำหรับโมเดลที่ปรับแต่ง (หากระบุไว้) ค่านี้ต้องยาวไม่เกิน 40 อักขระ โดยอักขระตัวแรกต้องเป็นตัวอักษร และสุดท้ายอาจเป็นตัวอักษรหรือตัวเลข รหัสต้องตรงกับนิพจน์ทั่วไป: a-z?

เนื้อหาของคำขอ

เนื้อความของคำขอมีอินสแตนซ์ของ TunedModel

ตัวอย่างคำขอ

Python

import time

base_model = "models/gemini-1.0-pro-001"
training_data = [
    {"text_input": "1", "output": "2"},
    # ... more examples ...
    # ...
    {"text_input": "seven", "output": "eight"},
]
operation = genai.create_tuned_model(
    # You can use a tuned model here too. Set `source_model="tunedModels/..."`
    display_name="increment",
    source_model=base_model,
    epoch_count=20,
    batch_size=4,
    learning_rate=0.001,
    training_data=training_data,
)

for status in operation.wait_bar():
    time.sleep(10)

result = operation.result()
print(result)
# # You can plot the loss curve with:
# snapshots = pd.DataFrame(result.tuning_task.snapshots)
# sns.lineplot(data=snapshots, x='epoch', y='mean_loss')

model = genai.GenerativeModel(model_name=result.name)
result = model.generate_content("III")
print(result.text)  # IV

เนื้อหาการตอบกลับ

ทรัพยากรนี้แสดงการดำเนินการที่ใช้เวลานานซึ่งเป็นผลมาจากการเรียก API เครือข่าย

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีข้อมูลซึ่งมีโครงสร้างดังต่อไปนี้

ช่อง
name string

ชื่อที่เซิร์ฟเวอร์กำหนด ซึ่งจะไม่ซ้ำกันเฉพาะในบริการเดียวกันที่ส่งคืนมาในตอนแรก หากคุณใช้การแมป HTTP เริ่มต้น name ควรเป็นชื่อทรัพยากรที่ลงท้ายด้วย operations/{unique_id}

metadata object

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

ออบเจ็กต์ที่มีช่องประเภทที่กำหนดเอง ช่องเพิ่มเติม "@type" จะมี URI ที่ระบุประเภท ตัวอย่างเช่น { "id": 1234, "@type": "types.example.com/standard/id" }

done boolean

หากค่าเป็น false แสดงว่าการดำเนินการยังดำเนินอยู่ หากเป็น true การดำเนินการนี้จะเสร็จสมบูรณ์ และสามารถใช้ error หรือ response ได้

ช่องการรวม result ผลการดำเนินการ ซึ่งอาจเป็น error หรือ response ที่ถูกต้องก็ได้ หาก done == false จะไม่มีการตั้งค่าทั้ง error และ response หาก done == true จะสามารถตั้งค่า error หรือ response ได้ 1 รายการ บริการบางอย่างอาจแสดงผลลัพธ์ไม่ได้ result ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้
error object (Status)

ผลลัพธ์ข้อผิดพลาดของการดำเนินการในกรณีที่ดำเนินการไม่สำเร็จหรือถูกยกเลิก

response object

การตอบสนองการดำเนินการที่สำเร็จตามปกติ หากวิธีเดิมไม่แสดงข้อมูลเกี่ยวกับความสำเร็จ เช่น Delete ระบบจะตอบกลับเป็น google.protobuf.Empty หากเมธอดต้นฉบับคือ Get/Create/Update มาตรฐาน การตอบกลับควรเป็นแหล่งข้อมูล สำหรับวิธีการอื่นๆ การตอบกลับควรเป็นประเภท XxxResponse โดยที่ Xxx เป็นชื่อเมธอดเดิม เช่น หากชื่อเมธอดเดิมคือ TakeSnapshot() ประเภทการตอบกลับที่อนุมานจะเป็น TakeSnapshotResponse

ออบเจ็กต์ที่มีช่องประเภทที่กำหนดเอง ช่องเพิ่มเติม "@type" จะมี URI ที่ระบุประเภท ตัวอย่างเช่น { "id": 1234, "@type": "types.example.com/standard/id" }

การแสดง JSON
{
  "name": string,
  "metadata": {
    "@type": string,
    field1: ...,
    ...
  },
  "done": boolean,

  // Union field result can be only one of the following:
  "error": {
    object (Status)
  },
  "response": {
    "@type": string,
    field1: ...,
    ...
  }
  // End of list of possible types for union field result.
}

เมธอด: tuneModels.get

รับข้อมูลเกี่ยวกับ TunedModel ที่เฉพาะเจาะจง

ปลายทาง

ซื้อ https://generativelanguage.googleapis.com/v1beta/{name=tunedModels/*}

พารามิเตอร์เส้นทาง

name string

ต้องระบุ ชื่อทรัพยากรของโมเดล

รูปแบบ: tunedModels/my-model-id อยู่ในรูปแบบ tunedModels/{tunedmodel}

เนื้อหาของคำขอ

เนื้อหาของคำขอต้องว่างเปล่า

ตัวอย่างคำขอ

Python

model_info = genai.get_model("tunedModels/my-increment-model")
print(model_info)

เนื้อหาการตอบกลับ

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีอินสแตนซ์ TunedModel

เมธอด: tuneModels.list

แสดงรายการโมเดลที่ปรับแต่งที่ผู้ใช้เป็นเจ้าของ

ปลายทาง

ซื้อ https://generativelanguage.googleapis.com/v1beta/tunedModels

พารามิเตอร์การค้นหา

pageSize integer

ไม่บังคับ จำนวนสูงสุด TunedModels ที่จะแสดงผล (ต่อหน้า) บริการอาจแสดงโมเดลที่มีการปรับแต่งน้อยกว่า

หากไม่ระบุ ระบบจะแสดงผลโมเดลที่ปรับแต่งไม่เกิน 10 รายการ เมธอดนี้จะแสดงโมเดลสูงสุด 1, 000 รายการต่อหน้า แม้ว่าคุณจะส่ง pageSize ที่ใหญ่กว่าก็ตาม

pageToken string

ไม่บังคับ โทเค็นของหน้าเว็บที่ได้รับจากการโทร tunedModels.list ก่อนหน้า

ระบุ pageToken ที่ส่งคืนโดยคำขอ 1 รายการเป็นอาร์กิวเมนต์ของคำขอถัดไปเพื่อเรียกหน้าถัดไป

เมื่อใส่เลขหน้า พารามิเตอร์อื่นๆ ทั้งหมดที่ให้กับ tunedModels.list ต้องตรงกับการเรียกใช้ที่ระบุโทเค็นของหน้าเว็บ

filter string

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

โอเปอเรเตอร์เพิ่มเติม: - owner:me - writers:me -คุณลักษณะการอ่าน:ฉัน - ผู้อ่าน:ทุกคน

ตัวอย่าง: "owner:me" จะแสดงโมเดลที่ปรับแต่งทั้งหมดซึ่งผู้โทรมีบทบาทเจ้าของ "readers:me" จะแสดงโมเดลที่ปรับแต่งทั้งหมดซึ่งผู้โทรมีบทบาทผู้อ่าน "ผู้ใช้:ทุกคน" จะแสดงโมเดลที่ปรับแต่งทั้งหมดที่แชร์กับทุกคน

เนื้อหาของคำขอ

เนื้อหาของคำขอต้องว่างเปล่า

ตัวอย่างคำขอ

Python

for model_info in genai.list_tuned_models():
    print(model_info.name)

เนื้อหาการตอบกลับ

การตอบกลับจาก tunedModels.list ที่มีรายการโมเดลที่ใส่เลขหน้า

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีข้อมูลซึ่งมีโครงสร้างดังต่อไปนี้

ช่อง
tunedModels[] object (TunedModel)

โมเดลที่แสดงผล

nextPageToken string

โทเค็นซึ่งสามารถส่งเป็น pageToken เพื่อเรียกข้อมูลหน้าถัดไป

หากเว้นช่องนี้ไว้ จะไม่มีหน้าเพิ่มเติม

การแสดง JSON
{
  "tunedModels": [
    {
      object (TunedModel)
    }
  ],
  "nextPageToken": string
}

เมธอด: tuneModels.patch

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

ปลายทาง

แพตช์ https://generativelanguage.googleapis.com/v1beta/{tunedModel.name=tunedModels/*}

PATCH https://generativelanguage.googleapis.com/v1beta/{tunedModel.name=tunedModels/*}

พารามิเตอร์เส้นทาง

tunedModel.name string

เอาต์พุตเท่านั้น ชื่อโมเดลที่ปรับแต่ง ระบบจะสร้างชื่อที่ไม่ซ้ำกันขึ้นเมื่อสร้าง ตัวอย่าง: tunedModels/az2mb0bpw6i หากตั้งค่า displayName เมื่อสร้าง ส่วนรหัสของชื่อจะได้รับการตั้งค่าโดยการเชื่อมโยงคำของ displayName เข้ากับขีดกลาง และเพิ่มส่วนแบบสุ่มเพื่อความไม่ซ้ำกัน ตัวอย่าง: displayName = "คำแปลประโยค" name = "tunedModels/sentence-translator-u3b7m" โดยใช้รูปแบบ tunedModels/{tunedmodel}

พารามิเตอร์การค้นหา

updateMask string (FieldMask format)

ต้องระบุ รายการช่องที่จะอัปเดต

ซึ่งเป็นรายการชื่อของช่องที่มีคุณสมบัติครบถ้วนและคั่นด้วยคอมมา ตัวอย่าง: "user.displayName,photo"

เนื้อหาของคำขอ

เนื้อความของคำขอมีอินสแตนซ์ของ TunedModel

เนื้อหาการตอบกลับ

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีอินสแตนซ์ TunedModel

เมธอด: tuneModels.delete

ลบโมเดลที่ปรับแต่ง

ปลายทาง

ลบ https://generativelanguage.googleapis.com/v1beta/{name=tunedModels/*}

พารามิเตอร์เส้นทาง

name string

ต้องระบุ ชื่อทรัพยากรของโมเดล รูปแบบ: tunedModels/my-model-id อยู่ในรูปแบบ tunedModels/{tunedmodel}

เนื้อหาของคำขอ

เนื้อหาของคำขอต้องว่างเปล่า

เนื้อหาการตอบกลับ

หากสำเร็จ เนื้อหาการตอบกลับจะว่างเปล่า

ทรัพยากร REST: tuneModels

แหล่งข้อมูล: TunedModel

โมเดลที่ปรับแต่งแล้วซึ่งสร้างขึ้นโดยใช้ ModelService.CreateTunedModel

การแสดง JSON
{
  "name": string,
  "displayName": string,
  "description": string,
  "state": enum (State),
  "createTime": string,
  "updateTime": string,
  "tuningTask": {
    object (TuningTask)
  },

  // Union field source_model can be only one of the following:
  "tunedModelSource": {
    object (TunedModelSource)
  },
  "baseModel": string
  // End of list of possible types for union field source_model.
  "temperature": number,
  "topP": number,
  "topK": integer
}
ช่อง
name string

เอาต์พุตเท่านั้น ชื่อโมเดลที่ปรับแต่ง ระบบจะสร้างชื่อที่ไม่ซ้ำกันขึ้นเมื่อสร้าง ตัวอย่าง: tunedModels/az2mb0bpw6i หากตั้งค่า displayName เมื่อสร้าง ส่วนรหัสของชื่อจะมีการตั้งค่าโดยการเชื่อมโยงคำของ displayName เข้ากับขีดกลาง และเพิ่มส่วนแบบสุ่มเพื่อความไม่ซ้ำกัน ตัวอย่าง: displayName = "คำแปลประโยค" name = "tunedModels/sentence-translator-u3b7m"

displayName string

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

description string

ไม่บังคับ คำอธิบายสั้นๆ ของโมเดลนี้

state enum (State)

เอาต์พุตเท่านั้น สถานะของโมเดลที่ปรับแต่ง

createTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่อสร้างรูปแบบนี้

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

updateTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่ออัปเดตโมเดลนี้

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

tuningTask object (TuningTask)

ต้องระบุ งานการปรับแต่งที่จะสร้างโมเดลที่ปรับแต่ง

ช่องการรวม source_model โมเดลที่ใช้เป็นจุดเริ่มต้นของการปรับแต่ง source_model ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้
tunedModelSource object (TunedModelSource)

ไม่บังคับ TunedModel ใช้เป็นจุดเริ่มต้นสำหรับการฝึกโมเดลใหม่

baseModel string

เปลี่ยนแปลงไม่ได้ ชื่อของ Model ที่จะปรับแต่ง ตัวอย่าง: models/text-bison-001

temperature number

ไม่บังคับ ควบคุมการสุ่มของเอาต์พุต

ค่าในช่วงได้เกินกว่า [0.0,1.0] ค่าที่ใกล้กับ 1.0 จะทำให้ได้คำตอบที่หลากหลายมากขึ้น ส่วนค่าที่ใกล้กับ 0.0 มักจะทำให้ได้คำตอบจากโมเดลที่ไม่น่าประหลาดใจน้อยลง

ค่านี้ระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลฐานใช้ขณะสร้างโมเดล

topP number

ไม่บังคับ สำหรับการสุ่มตัวอย่างนิวเคลียส

การสุ่มตัวอย่างนิวเคลียสจะพิจารณาชุดโทเค็นที่น้อยที่สุดซึ่งมีผลรวมความน่าจะเป็นอย่างน้อย topP

ค่านี้ระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลฐานใช้ขณะสร้างโมเดล

topK integer

ไม่บังคับ สำหรับการสุ่มตัวอย่างแบบ Top-k

การสุ่มตัวอย่างแบบ Top-k จะพิจารณาชุดโทเค็นที่เป็นไปได้มากที่สุด topK รายการ ค่านี้จะระบุค่าเริ่มต้นที่จะใช้โดยแบ็กเอนด์ขณะทำการเรียกใช้โมเดล

ค่านี้ระบุค่าเริ่มต้นให้เป็นค่าที่โมเดลฐานใช้ขณะสร้างโมเดล

TunedModelSource

ปรับโมเดลเป็นแหล่งที่มาสำหรับการฝึกโมเดลใหม่

การแสดง JSON
{
  "tunedModel": string,
  "baseModel": string
}
ช่อง
tunedModel string

เปลี่ยนแปลงไม่ได้ ชื่อของ TunedModel ที่จะใช้เป็นจุดเริ่มต้นสำหรับการฝึกโมเดลใหม่ ตัวอย่าง: tunedModels/my-tuned-model

baseModel string

เอาต์พุตเท่านั้น ชื่อของฐาน Model ของ TunedModel นี้มาจากการปรับแต่ง ตัวอย่าง: models/text-bison-001

รัฐ

สถานะของโมเดลที่ปรับแต่ง

Enum
STATE_UNSPECIFIED ค่าเริ่มต้น ค่านี้ไม่ได้ใช้
CREATING กำลังสร้างโมเดล
ACTIVE โมเดลนี้พร้อมใช้งานแล้ว
FAILED สร้างโมเดลไม่สำเร็จ

TuningTask

งานการปรับแต่งที่สร้างโมเดลที่ปรับแต่ง

การแสดง JSON
{
  "startTime": string,
  "completeTime": string,
  "snapshots": [
    {
      object (TuningSnapshot)
    }
  ],
  "trainingData": {
    object (Dataset)
  },
  "hyperparameters": {
    object (Hyperparameters)
  }
}
ช่อง
startTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่อเริ่มต้นการปรับแต่งโมเดลนี้

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

completeTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาเมื่อปรับแต่งโมเดลนี้เสร็จสมบูรณ์

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

snapshots[] object (TuningSnapshot)

เอาต์พุตเท่านั้น เมตริกที่รวบรวมระหว่างการปรับแต่ง

trainingData object (Dataset)

ต้องระบุ อินพุตเท่านั้น เปลี่ยนแปลงไม่ได้ ข้อมูลการฝึกโมเดล

hyperparameters object (Hyperparameters)

เปลี่ยนแปลงไม่ได้ ไฮเปอร์พารามิเตอร์ที่ควบคุมกระบวนการปรับแต่ง หากไม่ระบุ ระบบจะใช้ค่าเริ่มต้น

TuningSnapshot

บันทึกสำหรับขั้นตอนการปรับแต่งเพียงขั้นตอนเดียว

การแสดง JSON
{
  "step": integer,
  "epoch": integer,
  "meanLoss": number,
  "computeTime": string
}
ช่อง
step integer

เอาต์พุตเท่านั้น ขั้นตอนการปรับแต่ง

epoch integer

เอาต์พุตเท่านั้น Epoch เป็นส่วนประกอบของขั้นตอนนี้

meanLoss number

เอาต์พุตเท่านั้น การสูญเสียเฉลี่ยของตัวอย่างการฝึกสำหรับขั้นตอนนี้

computeTime string (Timestamp format)

เอาต์พุตเท่านั้น การประทับเวลาที่มีการคำนวณเมตริกนี้

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

ชุดข้อมูล

ชุดข้อมูลสำหรับการฝึกหรือการตรวจสอบ

การแสดง JSON
{

  // Union field dataset can be only one of the following:
  "examples": {
    object (TuningExamples)
  }
  // End of list of possible types for union field dataset.
}
ช่อง ฟิลด์การรวม dataset ข้อมูลในบรรทัดหรือการอ้างอิงข้อมูล dataset ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้
examples object (TuningExamples)

ไม่บังคับ ตัวอย่างในหน้า

TuningExamples

ตัวอย่างการปรับแต่ง อาจเป็นข้อมูลการฝึกหรือการตรวจสอบ

การแสดง JSON
{
  "examples": [
    {
      object (TuningExample)
    }
  ]
}
ช่อง
examples[] object (TuningExample)

ต้องระบุ ตัวอย่าง ตัวอย่างอินพุตอาจเป็นข้อความหรือการสนทนาก็ได้ แต่ตัวอย่างทั้งหมดในชุดต้องเป็นประเภทเดียวกัน

TuningExample

ตัวอย่างเดียวสำหรับการปรับแต่ง

การแสดง JSON
{
  "output": string,

  // Union field model_input can be only one of the following:
  "textInput": string
  // End of list of possible types for union field model_input.
}
ช่อง
output string

ต้องระบุ เอาต์พุตโมเดลที่คาดไว้

ช่องการรวม model_input อินพุตของโมเดลสำหรับตัวอย่างนี้ model_input ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้
textInput string

ไม่บังคับ อินพุตรูปแบบข้อความ

ไฮเปอร์พารามิเตอร์

ไฮเปอร์พารามิเตอร์ที่ควบคุมกระบวนการปรับแต่ง อ่านเพิ่มเติมที่ https://ai.google.dev/docs/model_tuning_guidance

การแสดง JSON
{

  // Union field learning_rate_option can be only one of the following:
  "learningRate": number,
  "learningRateMultiplier": number
  // End of list of possible types for union field learning_rate_option.
  "epochCount": integer,
  "batchSize": integer
}
ช่อง ฟิลด์การรวม learning_rate_option ตัวเลือกสำหรับการระบุอัตราการเรียนรู้ระหว่างการปรับแต่ง learning_rate_option ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้
learningRate number

ไม่บังคับ เปลี่ยนแปลงไม่ได้ ไฮเปอร์พารามิเตอร์ของอัตราการเรียนรู้สำหรับการปรับแต่ง หากไม่ได้ตั้งค่า ระบบจะคำนวณค่าเริ่มต้น 0.001 หรือ 0.0002 ตามจำนวนตัวอย่างการฝึก

learningRateMultiplier number

ไม่บังคับ เปลี่ยนแปลงไม่ได้ ตัวคูณอัตราการเรียนรู้ใช้ในการคำนวณอัตราการเรียนรู้สุดท้ายโดยอิงตามค่าเริ่มต้น (แนะนำ) อัตราการเรียนรู้จริง := learningRateMultiplier * อัตราการเรียนรู้เริ่มต้น อัตราการเรียนรู้เริ่มต้นจะขึ้นอยู่กับโมเดลฐานและขนาดชุดข้อมูล หากไม่ได้ตั้งค่า ระบบจะใช้ค่าเริ่มต้น 1.0

epochCount integer

เปลี่ยนแปลงไม่ได้ จำนวน Epoch การฝึก Epoch คือการส่งผ่านข้อมูลการฝึก 1 ครั้ง หากไม่ได้ตั้งค่า ระบบจะใช้ค่าเริ่มต้นที่ 5

batchSize integer

เปลี่ยนแปลงไม่ได้ ไฮเปอร์พารามิเตอร์ของขนาดกลุ่มสำหรับการปรับแต่ง หากไม่ได้ตั้งค่า ระบบจะใช้ค่าเริ่มต้น 4 หรือ 16 ตามจำนวนตัวอย่างการฝึก