Tuning

Phương thức: TuningModels.generateContent

Tạo phản hồi từ mô hình khi có dữ liệu đầu vào GenerateContentRequest.

Khả năng đầu vào khác nhau giữa các mô hình, bao gồm cả các mô hình đã được điều chỉnh. Xem hướng dẫn về mẫu thiết bịhướng dẫn điều chỉnh để biết thông tin chi tiết.

Điểm cuối

bài đăng https://generativelanguage.googleapis.com/v1beta/{model=tunedModels/*}:generateContent

Tham số đường dẫn

model string

Bắt buộc. Tên của Model được dùng để tạo hoàn thành.

Định dạng: name=models/{model}. Mã này có dạng tunedModels/{tunedmodel}.

Nội dung yêu cầu

Nội dung yêu cầu chứa dữ liệu có cấu trúc sau:

Số trường
contents[] object (Content)

Bắt buộc. Nội dung của cuộc trò chuyện hiện tại với mô hình.

Đối với truy vấn một lượt, đây chỉ là một phiên bản. Đối với truy vấn nhiều lượt, đây là trường lặp lại chứa nhật ký trò chuyện và yêu cầu mới nhất.

tools[] object (Tool)

Không bắt buộc. Danh sách Tools mà mô hình có thể dùng để tạo phản hồi tiếp theo.

Tool là một đoạn mã cho phép hệ thống tương tác với các hệ thống bên ngoài để thực hiện một hành động hoặc một tập hợp hành động, nằm ngoài phạm vi kiến thức và phạm vi của mô hình. Công cụ duy nhất được hỗ trợ hiện tại là Function.

toolConfig object (ToolConfig)

Không bắt buộc. Cấu hình công cụ cho mọi Tool được chỉ định trong yêu cầu.

safetySettings[] object (SafetySetting)

Không bắt buộc. Danh sách các thực thể SafetySetting riêng biệt dùng để chặn nội dung không an toàn.

Thay đổi này sẽ được thực thi trên GenerateContentRequest.contentsGenerateContentResponse.candidates. Không được có nhiều hơn một chế độ cài đặt cho mỗi loại SafetyCategory. API này sẽ chặn mọi nội dung và phản hồi không đáp ứng ngưỡng do các chế độ cài đặt này đặt ra. Danh sách này ghi đè các chế độ cài đặt mặc định cho từng SafetyCategory được chỉ định trong phần safetySettings. Nếu không có SafetySetting cho một SafetyCategory nhất định được cung cấp trong danh sách, API sẽ sử dụng chế độ cài đặt an toàn mặc định cho danh mục đó. Các danh mục gây hại HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT được hỗ trợ.

systemInstruction object (Content)

Không bắt buộc. Hướng dẫn hệ thống thiết lập dành cho nhà phát triển. Hiện tại, chỉ có văn bản.

generationConfig object (GenerationConfig)

Không bắt buộc. Các tuỳ chọn cấu hình để tạo mô hình và đầu ra.

cachedContent string

Không bắt buộc. Tên của nội dung được lưu trong bộ nhớ đệm được dùng làm ngữ cảnh để cung cấp thông tin dự đoán. Lưu ý: Chỉ sử dụng trong bộ nhớ đệm rõ ràng, trong đó người dùng có thể kiểm soát việc lưu vào bộ nhớ đệm (ví dụ: nội dung nào cần lưu vào bộ nhớ đệm) và được đảm bảo tiết kiệm chi phí. Định dạng cachedContents/{cachedContent}

Yêu cầu mẫu

Văn bản

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);

Bài đăng có hình ảnh

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);

Âm thanh

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());

Video

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());

Chat (Trò chuyện)

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());

Vỏ

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);

Bộ nhớ đệm

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());

Mô hình điều chỉnh

Python

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

Chế độ 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);

Thực thi mã

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);

Gọi hàm

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);

Cấu hình tạo

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());

Vỏ

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);

Cài đặt an toàn

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);
}

Vỏ

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);

Hướng dẫn hệ thống

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());

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ chứa một phiên bản của GenerateContentResponse.

Phương thức: AdjustModels.create

Tạo mô hình được điều chỉnh. Bạn có thể truy cập vào tiến trình điều chỉnh trung gian (nếu có) thông qua dịch vụ google.longrunning.Operations.

Bạn có thể xem trạng thái và kết quả thông qua dịch vụ Vận hành. Ví dụ: GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222

Điểm cuối

bài đăng https://generativelanguage.googleapis.com/v1beta/tunedModels

Tham số truy vấn

tunedModelId string

Không bắt buộc. Mã nhận dạng duy nhất cho mô hình được điều chỉnh nếu được chỉ định. Giá trị này phải có tối đa 40 ký tự, ký tự đầu tiên phải là một chữ cái, cuối cùng có thể là một chữ cái hoặc một số. Mã nhận dạng phải khớp với biểu thức chính quy: a-z?.

Nội dung yêu cầu

Nội dung yêu cầu chứa một bản sao của TunedModel.

Yêu cầu mẫu

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

Nội dung phản hồi

Tài nguyên này biểu thị một hoạt động chạy trong thời gian dài là kết quả của lệnh gọi API mạng.

Nếu thành công, phần nội dung phản hồi sẽ chứa dữ liệu có cấu trúc sau:

Số trường
name string

Tên do máy chủ chỉ định. Tên này chỉ là duy nhất trong cùng một dịch vụ ban đầu trả về tên đó. Nếu bạn sử dụng mục ánh xạ HTTP mặc định, name phải là tên tài nguyên kết thúc bằng operations/{unique_id}.

metadata object

Siêu dữ liệu dành riêng cho dịch vụ được liên kết với thao tác. Tệp này thường chứa thông tin về tiến trình và siêu dữ liệu phổ biến như thời gian tạo. Một số dịch vụ có thể không cung cấp siêu dữ liệu như vậy. Mọi phương thức trả về một tác vụ chạy trong thời gian dài đều phải ghi nhận loại siêu dữ liệu, nếu có.

Một đối tượng có chứa các trường thuộc loại tuỳ ý. Trường bổ sung "@type" chứa URI xác định kiểu. Ví dụ: { "id": 1234, "@type": "types.example.com/standard/id" }.

done boolean

Nếu giá trị là false, điều đó có nghĩa là thao tác vẫn đang diễn ra. Nếu là true, thao tác này sẽ hoàn tất và có thể dùng được error hoặc response.

Trường kết hợp result. Kết quả của thao tác, có thể là error hoặc response hợp lệ. Nếu done == false, thì cả errorresponse đều không được đặt. Nếu done == true, bạn có thể đặt chính xác một trong hai giá trị error hoặc response. Một số dịch vụ có thể không cung cấp kết quả. result chỉ có thể là một trong những trạng thái sau đây:
error object (Status)

Kết quả lỗi của thao tác trong trường hợp không thành công hoặc huỷ.

response object

Phản hồi thành công, bình thường của thao tác. Nếu phương thức ban đầu không trả về dữ liệu nào khi thành công, chẳng hạn như Delete, thì phản hồi sẽ là google.protobuf.Empty. Nếu phương thức gốc là phương thức chuẩn Get/Create/Update, thì phản hồi phải là tài nguyên. Đối với các phương thức khác, phản hồi phải có kiểu XxxResponse, trong đó Xxx là tên phương thức ban đầu. Ví dụ: nếu tên phương thức ban đầu là TakeSnapshot(), thì loại phản hồi được dự đoán sẽ là TakeSnapshotResponse.

Một đối tượng có chứa các trường thuộc loại tuỳ ý. Trường bổ sung "@type" chứa URI xác định kiểu. Ví dụ: { "id": 1234, "@type": "types.example.com/standard/id" }.

Biểu diễn dưới dạng 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.
}

Phương thức: navigationModels.get

Nhận thông tin về một TunedModel cụ thể.

Điểm cuối

nhận https://generativelanguage.googleapis.com/v1beta/{name=tunedModels/*}

Tham số đường dẫn

name string

Bắt buộc. Tên tài nguyên của mô hình.

Định dạng: tunedModels/my-model-id. Định dạng này có dạng tunedModels/{tunedmodel}.

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Yêu cầu mẫu

Python

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

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ chứa một phiên bản của TunedModel.

Phương thức: TuningModels.list

Liệt kê các mô hình được điều chỉnh do người dùng sở hữu.

Điểm cuối

nhận https://generativelanguage.googleapis.com/v1beta/tunedModels

Tham số truy vấn

pageSize integer

Không bắt buộc. Số lượng TunedModels tối đa cần trả về (trên mỗi trang). Dịch vụ có thể trả về ít mô hình được điều chỉnh hơn.

Nếu bạn không chỉ định, hệ thống sẽ trả về tối đa 10 mô hình đã được điều chỉnh. Phương thức này trả về tối đa 1.000 mẫu trên mỗi trang, ngay cả khi bạn chuyển pageSize lớn hơn.

pageToken string

Không bắt buộc. Mã thông báo trang, nhận được từ lệnh gọi tunedModels.list trước đó.

Cung cấp pageToken do một yêu cầu trả về làm đối số cho yêu cầu tiếp theo để truy xuất trang tiếp theo.

Khi phân trang, tất cả các tham số khác được cung cấp cho tunedModels.list phải khớp với lệnh gọi đã cung cấp mã thông báo trang.

filter string

Không bắt buộc. Bộ lọc là tìm kiếm văn bản đầy đủ trên mô tả và tên hiển thị của mô hình được điều chỉnh. Theo mặc định, kết quả sẽ không bao gồm các mô hình được điều chỉnh và chia sẻ với mọi người.

Các toán tử bổ sung: – owner:me –Nhà văn:me – độc giả:me – độc giả:mọi người

Ví dụ: "owner:me" trả về tất cả mô hình được điều chỉnh mà người gọi có vai trò chủ sở hữu "readers:me" trả về tất cả mô hình được điều chỉnh mà phương thức gọi có vai trò người đọc "readers:people" trả về tất cả các mô hình được điều chỉnh được chia sẻ với mọi người

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Yêu cầu mẫu

Python

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

Nội dung phản hồi

Phản hồi của tunedModels.list chứa danh sách Mô hình được phân trang.

Nếu thành công, phần nội dung phản hồi sẽ chứa dữ liệu có cấu trúc sau:

Số trường
tunedModels[] object (TunedModel)

Mô hình được trả về.

nextPageToken string

Mã thông báo có thể được gửi dưới dạng pageToken để truy xuất trang tiếp theo.

Nếu trường này bị bỏ qua, thì sẽ không có trang nào khác.

Biểu diễn dưới dạng JSON
{
  "tunedModels": [
    {
      object (TunedModel)
    }
  ],
  "nextPageToken": string
}

Phương thức: TuningModels.patch

Cập nhật mô hình đã được điều chỉnh.

Điểm cuối

bản vá https://generativelanguage.googleapis.com/v1beta/{tunedModel.name=tunedModels/*}

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

Tham số đường dẫn

tunedModel.name string

Chỉ có đầu ra. Tên mô hình được điều chỉnh. Một tên duy nhất sẽ được tạo khi tạo. Ví dụ: tunedModels/az2mb0bpw6i Nếu bạn đặt displayName khi tạo, thì phần mã nhận dạng của tên sẽ được đặt bằng cách nối các từ của displayName với dấu gạch nối và thêm một phần ngẫu nhiên để xác định tính duy nhất. Ví dụ: displayName = "Trình dịch câu" tên = "tunedModels/sentence-translator-u3b7m" Mã này có dạng tunedModels/{tunedmodel}.

Tham số truy vấn

updateMask string (FieldMask format)

Bắt buộc. Danh sách các trường cần cập nhật.

Đây là danh sách các tên trường đủ điều kiện được phân tách bằng dấu phẩy. Ví dụ: "user.displayName,photo"

Nội dung yêu cầu

Nội dung yêu cầu chứa một bản sao của TunedModel.

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ chứa một phiên bản của TunedModel.

Phương thức: TuningModels.delete

Xoá mô hình được điều chỉnh.

Điểm cuối

xoá https://generativelanguage.googleapis.com/v1beta/{name=tunedModels/*}

Tham số đường dẫn

name string

Bắt buộc. Tên tài nguyên của mô hình. Định dạng: tunedModels/my-model-id. Định dạng này có dạng tunedModels/{tunedmodel}.

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ trống.

Tài nguyên REST: TuningModels

Tài nguyên: TunedModel

Một mô hình được tinh chỉnh được tạo bằng ModelService.CreateTunedModel.

Biểu diễn dưới dạng 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
}
Số trường
name string

Chỉ có đầu ra. Tên mô hình được điều chỉnh. Một tên duy nhất sẽ được tạo khi tạo. Ví dụ: tunedModels/az2mb0bpw6i Nếu bạn đặt displayName khi tạo, thì phần mã nhận dạng của tên sẽ được đặt bằng cách nối các từ của displayName với dấu gạch nối và thêm một phần ngẫu nhiên để xác định tính duy nhất. Ví dụ: displayName = "Trình dịch câu" tên = "tunedModels/sentence-translator-u3b7m"

displayName string

Không bắt buộc. Tên hiển thị cho mô hình này trong giao diện người dùng. Tên hiển thị phải có tối đa 40 ký tự (bao gồm cả dấu cách).

description string

Không bắt buộc. Mô tả ngắn về mô hình này.

state enum (State)

Chỉ có đầu ra. Trạng thái của mô hình được điều chỉnh.

createTime string (Timestamp format)

Chỉ có đầu ra. Dấu thời gian khi mô hình này được tạo.

Dấu thời gian theo múi giờ "Zulu" RFC3339 (giờ UTC) với độ phân giải nano giây và lên đến 9 chữ số phân số. Ví dụ: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z".

updateTime string (Timestamp format)

Chỉ có đầu ra. Dấu thời gian khi mô hình này được cập nhật.

Dấu thời gian theo múi giờ "Zulu" RFC3339 (giờ UTC) với độ phân giải nano giây và lên đến 9 chữ số phân số. Ví dụ: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z".

tuningTask object (TuningTask)

Bắt buộc. Tác vụ điều chỉnh sẽ tạo ra mô hình được điều chỉnh.

Trường kết hợp source_model. Mô hình được dùng làm điểm bắt đầu cho quá trình điều chỉnh. source_model chỉ có thể là một trong những trạng thái sau đây:
tunedModelSource object (TunedModelSource)

Không bắt buộc. TunedModel để sử dụng làm điểm bắt đầu cho việc huấn luyện mô hình mới.

baseModel string

Bất biến. Tên của Model cần chỉnh. Ví dụ: models/text-bison-001

temperature number

Không bắt buộc. Kiểm soát độ ngẫu nhiên của dữ liệu đầu ra.

Các giá trị có thể dao động trên [0.0,1.0], tính cả hai giá trị đó. Giá trị gần 1.0 sẽ tạo ra các câu trả lời đa dạng hơn, trong khi giá trị gần 0.0 hơn thường sẽ mang lại các câu trả lời ít gây bất ngờ hơn từ mô hình.

Giá trị này chỉ định giá trị mặc định là giá trị mà mô hình cơ sở sử dụng khi tạo mô hình.

topP number

Không bắt buộc. Đối với việc lấy mẫu Hạt nhân.

Phương pháp lấy mẫu hạt nhân sẽ xem xét tập hợp mã thông báo nhỏ nhất có tổng xác suất ít nhất là topP.

Giá trị này chỉ định giá trị mặc định là giá trị mà mô hình cơ sở sử dụng khi tạo mô hình.

topK integer

Không bắt buộc. Đối với việc lấy mẫu Top-k.

Tính năng lấy mẫu hàng đầu sẽ xem xét tập hợp topK mã thông báo có khả năng xuất hiện nhiều nhất. Giá trị này chỉ định giá trị mặc định mà phần phụ trợ sẽ sử dụng khi thực hiện lệnh gọi đến mô hình.

Giá trị này chỉ định giá trị mặc định là giá trị mà mô hình cơ sở sử dụng khi tạo mô hình.

TunedModelSource

Mô hình được điều chỉnh làm nguồn để huấn luyện mô hình mới.

Biểu diễn dưới dạng JSON
{
  "tunedModel": string,
  "baseModel": string
}
Số trường
tunedModel string

Bất biến. Tên của TunedModel để dùng làm điểm bắt đầu cho việc huấn luyện mô hình mới. Ví dụ: tunedModels/my-tuned-model

baseModel string

Chỉ có đầu ra. Tên của cơ sở ModelTunedModel này được điều chỉnh. Ví dụ: models/text-bison-001

Tiểu bang

Trạng thái của mô hình được điều chỉnh.

Enum
STATE_UNSPECIFIED Giá trị mặc định. Giá trị này chưa được sử dụng.
CREATING Mô hình đang được tạo.
ACTIVE Mô hình đã sẵn sàng để sử dụng.
FAILED Không tạo được mô hình.

TuningTask

Điều chỉnh các công việc để tạo ra mô hình được điều chỉnh.

Biểu diễn dưới dạng JSON
{
  "startTime": string,
  "completeTime": string,
  "snapshots": [
    {
      object (TuningSnapshot)
    }
  ],
  "trainingData": {
    object (Dataset)
  },
  "hyperparameters": {
    object (Hyperparameters)
  }
}
Số trường
startTime string (Timestamp format)

Chỉ có đầu ra. Dấu thời gian khi điều chỉnh mô hình này đã bắt đầu.

Dấu thời gian theo múi giờ "Zulu" RFC3339 (giờ UTC) với độ phân giải nano giây và lên đến 9 chữ số phân số. Ví dụ: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z".

completeTime string (Timestamp format)

Chỉ có đầu ra. Dấu thời gian khi tinh chỉnh mô hình này đã hoàn tất.

Dấu thời gian theo múi giờ "Zulu" RFC3339 (giờ UTC) với độ phân giải nano giây và lên đến 9 chữ số phân số. Ví dụ: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z".

snapshots[] object (TuningSnapshot)

Chỉ có đầu ra. Các chỉ số được thu thập trong quá trình điều chỉnh.

trainingData object (Dataset)

Bắt buộc. Chỉ nhập. Bất biến. Dữ liệu huấn luyện mô hình.

hyperparameters object (Hyperparameters)

Bất biến. Siêu tham số kiểm soát quá trình điều chỉnh. Nếu không được cung cấp, hệ thống sẽ sử dụng các giá trị mặc định.

TuningSnapshot

Ghi lại một bước điều chỉnh.

Biểu diễn dưới dạng JSON
{
  "step": integer,
  "epoch": integer,
  "meanLoss": number,
  "computeTime": string
}
Số trường
step integer

Chỉ có đầu ra. Bước điều chỉnh.

epoch integer

Chỉ có đầu ra. Bước này nằm trong thời gian bắt đầu của hệ thống.

meanLoss number

Chỉ có đầu ra. Mức mất trung bình của các ví dụ huấn luyện cho bước này.

computeTime string (Timestamp format)

Chỉ có đầu ra. Dấu thời gian khi tính toán chỉ số này.

Dấu thời gian theo múi giờ "Zulu" RFC3339 (giờ UTC) với độ phân giải nano giây và lên đến 9 chữ số phân số. Ví dụ: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z".

Tập dữ liệu

Tập dữ liệu để huấn luyện hoặc xác thực.

Biểu diễn dưới dạng JSON
{

  // Union field dataset can be only one of the following:
  "examples": {
    object (TuningExamples)
  }
  // End of list of possible types for union field dataset.
}
Số trường Trường kết hợp dataset. Dữ liệu cùng dòng hoặc tham chiếu đến dữ liệu. dataset chỉ có thể là một trong những trạng thái sau đây:
examples object (TuningExamples)

Không bắt buộc. Ví dụ cùng dòng.

TuningExamples

Một số ví dụ về cách điều chỉnh. Có thể là dữ liệu huấn luyện hoặc dữ liệu xác thực.

Biểu diễn dưới dạng JSON
{
  "examples": [
    {
      object (TuningExample)
    }
  ]
}
Số trường
examples[] object (TuningExample)

Bắt buộc. Ví dụ. Ví dụ có thể là văn bản hoặc cuộc thảo luận, nhưng tất cả ví dụ trong một tập hợp phải thuộc cùng một loại.

TuningExample

Một ví dụ về cách điều chỉnh.

Biểu diễn dưới dạng 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.
}
Số trường
output string

Bắt buộc. Kết quả đầu ra dự kiến của mô hình.

Trường kết hợp model_input. Giá trị đầu vào cho mô hình của ví dụ này. model_input chỉ có thể là một trong những trạng thái sau đây:
textInput string

Không bắt buộc. Nhập mô hình văn bản.

Siêu tham số

Siêu tham số kiểm soát quá trình điều chỉnh. Tìm hiểu thêm tại https://ai.google.dev/docs/model_tuning_guidance

Biểu diễn dưới dạng 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
}
Số trường Trường kết hợp learning_rate_option. Các tuỳ chọn để chỉ định tốc độ học trong khi điều chỉnh. learning_rate_option chỉ có thể là một trong những trạng thái sau đây:
learningRate number

Không bắt buộc. Bất biến. Siêu tham số tốc độ học tập để điều chỉnh. Nếu bạn không đặt chính sách này, giá trị mặc định là 0,001 hoặc 0,0002 sẽ được tính toán dựa trên số lượng ví dụ huấn luyện.

learningRateMultiplier number

Không bắt buộc. Bất biến. Hệ số tốc độ học được dùng để tính toán Tỷ lệ học tập cuối cùng dựa trên giá trị mặc định (nên dùng). Tốc độ học thực tế := LearningRateMultiplier * tốc độ học mặc định Tốc độ học mặc định phụ thuộc vào mô hình cơ sở và kích thước tập dữ liệu. Nếu bạn không đặt chính sách này, giá trị mặc định là 1.0 sẽ được sử dụng.

epochCount integer

Bất biến. Số khoảng thời gian bắt đầu của huấn luyện. Thời gian bắt đầu của hệ thống là một lần truyền qua dữ liệu huấn luyện. Nếu bạn không đặt chính sách này, giá trị mặc định là 5 sẽ được sử dụng.

batchSize integer

Bất biến. Siêu tham số kích thước lô để điều chỉnh. Nếu bạn không đặt chính sách này, hệ thống sẽ sử dụng giá trị mặc định là 4 hoặc 16 dựa trên số lượng ví dụ huấn luyện.