第18章 Gemini API 文本生成开发指南
Gemini 4 Argon 现已发布,欢迎试用。
首页 Gemini API 文档
文本生成
Gemini API 可以根据文本、图片、视频和音频输入生成文本输出。
下面是一个基础示例:
Pythonfrom google import genai
client = genai.Client()
interaction = client.interactions.create( model="gemini-3.8-flash", input="How does AI work?" ) print(interaction.output_text)
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const interaction = await ai.interactions.create({ model: "gemini-3.8-flash", input: "How does AI work?", }); console.log(interaction.output_text); }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input(InteractionsInput.of("How does AI work?")) .build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
Gopackage main
import ( "context" "fmt" "log"
"google.golang.org/genai" "google.golang.org/genai/interactions/models/interactions" "google.golang.org/genai/interactions/models/operations" )
func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) }
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), Input: interactions.NewInteractionsInput("How does AI work?"), }), }) if err != nil { log.Fatal(err) }
if res.Interaction.OutputText != nil { fmt.Println(*res.Interaction.OutputText) } }
RESTcurl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "gemini-3.8-flash", "input": "How does AI work?" }'
Google GenAI SDK 在返回的 Interaction 对象上直接提供了便捷属性,方便访问模型的响应。
最常用的是 interaction.output_text(String),它会返回模型响应中最后几个文本块;如果响应被拆分成多个连续的 TextContent 块,它会自动拼接。注意,.output_text 不包含被非文本内容(如思考、图片、音频或工具调用)分隔的早期文本块。对于复杂或交错的 Multimodal 响应,你需要手动遍历 steps。要了解其他媒体类型的便捷属性,请参阅 Interactions 概览。
Gemini 的思考能力
Gemini 模型通常默认启用"思考"(thinking),让模型在回答前先进行推理。
每个模型支持不同的 thinking 配置,可用来控制成本、延迟和智能水平。详情请参阅 thinking 指南。
Pythonfrom google import genai
client = genai.Client()
interaction = client.interactions.create( model="gemini-3.8-flash", input="How does AI work?", generation_config={ "thinking_level": "low" } ) print(interaction.output_text)
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const interaction = await ai.interactions.create({ model: "gemini-3.8-flash", input: "How does AI work?", generation_config: { thinking_level: "low", }, }); console.log(interaction.output_text); }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.GenerationConfig; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.ThinkingLevel; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input(InteractionsInput.of("How does AI work?")) .generationConfig(GenerationConfig.builder().thinkingLevel(ThinkingLevel.LOW).build()) .build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
Gopackage main
import ( "context" "fmt" "log"
"google.golang.org/genai" "google.golang.org/genai/interactions/models/interactions" "google.golang.org/genai/interactions/models/operations" )
func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) }
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), Input: interactions.NewInteractionsInput("How does AI work?"), GenerationConfig: &interactions.GenerationConfig{ ThinkingLevel: interactions.ThinkingLevelLow.ToPointer(), }, }), }) if err != nil { log.Fatal(err) }
if res.Interaction.OutputText != nil { fmt.Println(*res.Interaction.OutputText) } }
RESTcurl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "gemini-3.8-flash", "input": "How does AI work?", "generation_config": { "thinking_level": "low" } }'
系统指令及其他配置
你可以通过系统指令来引导 Gemini 模型的行为,即传入 system_instruction 参数来配置模型表现。
Pythonfrom google import genai
client = genai.Client()
interaction = client.interactions.create( model="gemini-3.8-flash", system_instruction="You are a cat. Your name is Neko.", input="Hello there" )
print(interaction.output_text)
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const interaction = await ai.interactions.create({ model: "gemini-3.8-flash", input: "Hello there", system_instruction: "You are a cat. Your name is Neko.", }); console.log(interaction.output_text); }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .systemInstruction("You are a cat. Your name is Neko.") .input(InteractionsInput.of("Hello there")) .build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
Gopackage main
import ( "context" "fmt" "log"
"google.golang.org/genai" "google.golang.org/genai/interactions/models/interactions" "google.golang.org/genai/interactions/models/operations" )
func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) }
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), Input: interactions.NewInteractionsInput("Hello there"), SystemInstruction: genai.Ptr("You are a cat. Your name is Neko."), }), }) if err != nil { log.Fatal(err) }
if res.Interaction.OutputText != nil { fmt.Println(*res.Interaction.OutputText) } }
RESTcurl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "gemini-3.8-flash", "system_instruction": "You are a cat. Your name is Neko.", "input": "Hello there" }'
你还可以通过 generation_config 参数覆盖默认的生成参数,例如 max_output_tokens 或 thinking_level。
Pythonfrom google import genai
client = genai.Client()
interaction = client.interactions.create( model="gemini-3.8-flash", input="Explain how AI works", generation_config={ "max_output_tokens": 500 } ) print(interaction.output_text)
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const interaction = await ai.interactions.create({ model: "gemini-3.8-flash", input: "Explain how AI works", generation_config: { max_output_tokens: 500, }, }); console.log(interaction.output_text); }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.GenerationConfig; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input(InteractionsInput.of("Explain how AI works")) .generationConfig(GenerationConfig.builder().maxOutputTokens(500).build()) .build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
Gopackage main
import ( "context" "fmt" "log"
"google.golang.org/genai" "google.golang.org/genai/interactions/models/interactions" "google.golang.org/genai/interactions/models/operations" )
func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) }
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), Input: interactions.NewInteractionsInput("Explain the concept of Occam's Razor and provide a simple, everyday example."), GenerationConfig: &interactions.GenerationConfig{ MaxOutputTokens: genai.Ptr(500), }, }), }) if err != nil { log.Fatal(err) }
if res.Interaction.OutputText != nil { fmt.Println(*res.Interaction.OutputText) } }
RESTcurl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "gemini-3.8-flash", "input": "Explain how AI works", "generation_config": { "temperature": 1.0 } }'
完整可配置参数列表及说明请参阅 Interactions API 参考。
多模态输入
Gemini API 支持多模态输入,可将文本与媒体文件组合使用。以下示例演示如何提供一张图片:
Pythonfrom google import genai
client = genai.Client()
uploaded_file = client.files.upload(file="path/to/organ.jpg")
interaction = client.interactions.create( model="gemini-3.8-flash", input=[ {"type": "text", "text": "Tell me about this instrument"}, { "type": "image", "uri": uploaded_file.uri, "mime_type": uploaded_file.mime_type } ] ) print(interaction.output_text)
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const uploadedFile = await ai.files.upload({ file: "path/to/organ.jpg", config: { mimeType: "image/jpeg" } });
const interaction = await ai.interactions.create({ model: "gemini-3.8-flash", input: [ {type: "text", text: "Tell me about this instrument"}, { type: "image", uri: uploadedFile.uri, mime_type: uploadedFile.mimeType } ], }); console.log(interaction.output_text); }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.ImageContent; import com.google.genai.gaos.models.interactions.ImageContentMimeType; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.types.File; import com.google.genai.types.UploadFileConfig; import java.util.Arrays;
Client client = new Client();
File uploadedFile = client.files.upload( new java.io.File("path/to/organ.jpg"), UploadFileConfig.builder().mimeType("image/jpeg").build());
CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input( InteractionsInput.ofContent( Arrays.asList( TextContent.builder().text("Tell me about this instrument").build(), ImageContent.builder() .uri(uploadedFile.uri().orElse("")) .mimeType( ImageContentMimeType.of(uploadedFile.mimeType().orElse("image/jpeg"))) .build()))) .build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
Gopackage main
import ( "context" "encoding/base64" "fmt" "log" "os"
"google.golang.org/genai" "google.golang.org/genai/interactions/models/interactions" "google.golang.org/genai/interactions/models/operations" )
func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) }
imageBytes, err := os.ReadFile("/path/to/organ.jpg") if err != nil { log.Fatal(err) } base64Image := base64.StdEncoding.EncodeToString(imageBytes)
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), Input: interactions.NewInteractionsInput([]interactions.Content{ interactions.NewContent(interactions.TextContent{ Text: "Tell me about this instrument", }), interactions.NewContent(interactions.ImageContent{ Data: genai.Ptr(base64Image), MimeType: interactions.ImageContentMimeTypeImageJpeg.ToPointer(), }), }), }), }) if err != nil { log.Fatal(err) }
if res.Interaction.OutputText != nil { fmt.Println(*res.Interaction.OutputText) } }
REST# First upload the file using the Files API, then use the URI: curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "gemini-3.8-flash", "input": [ {"type": "text", "text": "Tell me about this instrument"}, { "type": "image", "uri": "YOUR_FILE_URI", "mime_type": "image/jpeg" } ] }'
关于提供图片的其他方式以及更高级的图片处理,请参阅图片理解指南。API 同样支持文档、视频和音频的输入与理解。
流式响应
默认情况下,模型会在整个生成过程完成后才返回响应。
如果想要更流畅的交互体验,可以使用流式处理,边生成边处理响应分块。关于事件类型、配合工具的流式处理、思考、Agent 以及图片生成等完整指南,请参阅专门的流式交互指南。
Pythonfrom google import genai
client = genai.Client()
stream = client.interactions.create( model="gemini-3.8-flash", input="Explain how AI works", stream=True ) for event in stream: if event.event_type == "step.delta": if event.delta.type == "text": print(event.delta.text, end="")
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const stream = await ai.interactions.create({ model: "gemini-3.8-flash", input: "Explain how AI works", stream: true, });
for await (const event of stream) { if (event.event_type === "step.delta") { if (event.delta.type === "text") { process.stdout.write(event.delta.text); } } } }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.InteractionSSEEvent; import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.StepDelta; import com.google.genai.gaos.models.interactions.StepDeltaData; import com.google.genai.gaos.models.interactions.TextDelta; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.gaos.models.operations.CreateInteractionResponse; import com.google.genai.gaos.utils.EventStream;
Client client = new Client();
CreateModelInteraction params = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input(InteractionsInput.of("Explain how AI works")) .stream(true) .build();
CreateInteractionResponse response = client.interactions.create(CreateInteractionRequestBody.of(params));
try (EventStream
Gopackage main
import ( "context" "fmt" "log"
"google.golang.org/genai" "google.golang.org/genai/interactions/models/interactions" "google.golang.org/genai/interactions/models/operations" )
func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) }
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), Input: interactions.NewInteractionsInput("Explain how AI works"), Stream: genai.Ptr(true), }), }) if err != nil { log.Fatal(err) } stream := res.InteractionSSEStreamEvent defer stream.Close()
for stream.Next() { event := stream.Value() if stepDelta := event.GetDataStepDelta(); stepDelta != nil { if textDelta := stepDelta.GetDeltaText(); textDelta != nil { fmt.Print(textDelta.GetText()) } } } if err := stream.Err(); err != nil { log.Fatal(err) } }
RESTcurl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ --no-buffer \ -d '{ "model": "gemini-3.8-flash", "input": "Explain how AI works", "stream": true }'
多轮对话
Interactions API 支持多轮对话:通过 previous_interaction_id 将多次交互串联起来。每一轮都是一次独立的交互,对话历史由 API 自动管理。
Pythonfrom google import genai
client = genai.Client()
interaction1 = client.interactions.create( model="gemini-3.8-flash", input="I have 2 dogs in my house.", ) print(interaction1.output_text)
interaction2 = client.interactions.create( model="gemini-3.8-flash", input="How many paws are in my house?", previous_interaction_id=interaction1.id, ) print(interaction2.output_text)
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const interaction1 = await ai.interactions.create({ model: "gemini-3.8-flash", input: "I have 2 dogs in my house.", }); console.log("Response 1:", interaction1.output_text);
const interaction2 = await ai.interactions.create({ model: "gemini-3.8-flash", input: "How many paws are in my house?", previous_interaction_id: interaction1.id, }); console.log("Response 2:", interaction2.output_text); }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params1 = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input(InteractionsInput.of("I have 2 dogs in my house.")) .build();
Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get(); System.out.println("Response 1: " + interaction1.outputText().orElse(""));
CreateModelInteraction params2 = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input(InteractionsInput.of("How many paws are in my house?")) .previousInteractionId(interaction1.id().orElse("")) .build();
Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get(); System.out.println("Response 2: " + interaction2.outputText().orElse(""));
Gopackage main
import ( "context" "fmt" "log"
"google.golang.org/genai" "google.golang.org/genai/interactions/models/interactions" "google.golang.org/genai/interactions/models/operations" )
func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) }
// First turn turn1, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), Input: interactions.NewInteractionsInput("Hello, I have 2 dogs in my house."), }), }) if err != nil { log.Fatal(err) } if turn1.Interaction.OutputText != nil { fmt.Printf("Model: %s\n", *turn1.Interaction.OutputText) }
// Second turn (chained using PreviousInteractionID) turn2, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), PreviousInteractionID: turn1.Interaction.ID, Input: interactions.NewInteractionsInput("How many paws are in my house?"), }), }) if err != nil { log.Fatal(err) } if turn2.Interaction.OutputText != nil { fmt.Printf("Model: %s\n", *turn2.Interaction.OutputText) } }
RESTRESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "gemini-3.8-flash", "input": "I have 2 dogs in my house." }')
INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "gemini-3.8-flash", "input": "I have two dogs in my house. How many paws are in my house?", "previous_interaction_id": "'$INTERACTION_ID'" }'
多轮对话也可以结合流式方法使用,只需同时传入 previous_interaction_id 和流式参数。
Pythonfrom google import genai
client = genai.Client()
interaction1 = client.interactions.create( model="gemini-3.8-flash", input="I have 2 dogs in my house.", ) print(interaction1.output_text)
stream = client.interactions.create( model="gemini-3.8-flash", input="How many paws are in my house?", previous_interaction_id=interaction1.id, stream=True ) for event in stream: if event.event_type == "step.delta": if event.delta.type == "text": print(event.delta.text, end="")
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const interaction1 = await ai.interactions.create({ model: "gemini-3.8-flash", input: "I have 2 dogs in my house.", }); console.log("Response 1:", interaction1.output_text);
const stream = await ai.interactions.create({ model: "gemini-3.8-flash", input: "How many paws are in my house?", previous_interaction_id: interaction1.id, stream: true, }); for await (const event of stream) { if (event.event_type === "step.delta") { if (event.delta.type === "text") { process.stdout.write(event.delta.text); } } } }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionSSEEvent; import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.StepDelta; import com.google.genai.gaos.models.interactions.StepDeltaData; import com.google.genai.gaos.models.interactions.TextDelta; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import com.google.genai.gaos.models.operations.CreateInteractionResponse; import com.google.genai.gaos.utils.EventStream;
Client client = new Client();
CreateModelInteraction params1 = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input(InteractionsInput.of("I have 2 dogs in my house.")) .build();
Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get(); System.out.println("Response 1: " + interaction1.outputText().orElse(""));
CreateModelInteraction params2 = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .input(InteractionsInput.of("How many paws are in my house?")) .previousInteractionId(interaction1.id().orElse("")) .stream(true) .build();
CreateInteractionResponse response2 = client.interactions.create(CreateInteractionRequestBody.of(params2));
try (EventStream
Gopackage main
import ( "context" "fmt" "log"
"google.golang.org/genai" "google.golang.org/genai/interactions/models/interactions" "google.golang.org/genai/interactions/models/operations" )
func main() { ctx := context.Background() client, err := genai.NewClient(ctx, nil) if err != nil { log.Fatal(err) }
turn1, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), Input: interactions.NewInteractionsInput("Hello, I have 2 dogs in my house."), }), }) if err != nil { log.Fatal(err) }
res2, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{ Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{ Model: interactions.Model("gemini-3.8-flash"), PreviousInteractionID: turn1.Interaction.ID, Input: interactions.NewInteractionsInput("How many paws are in my house?"), Stream: genai.Ptr(true), }), }) if err != nil { log.Fatal(err) } stream := res2.InteractionSSEStreamEvent defer stream.Close()
for stream.Next() { event := stream.Value() if stepDelta := event.GetDataStepDelta(); stepDelta != nil { if textDelta := stepDelta.GetDeltaText(); textDelta != nil { fmt.Print(textDelta.GetText()) } } } if err := stream.Err(); err != nil { log.Fatal(err) } }
RESTRESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "gemini-3.8-flash", "input": "I have 2 dogs in my house." }') INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ --no-buffer \ -d '{ "model": "gemini-3.8-flash", "input": "How many paws are in my house?", "previous_interaction_id": "'$INTERACTION_ID'", "stream": true }'
无状态对话
默认情况下,使用 previous_interaction_id 时,Interactions API 会在服务端管理对话状态。你也可以选择无状态模式,由客户端自行维护对话历史。
使用无状态模式的方法: 1. 在请求中设置 store=false,不使用服务端存储。 2. 在客户端以 steps 数组的形式维护对话历史。 3. 在后续请求中,把积累的 steps 传入 input 字段,并将新一轮内容作为 user_input step 追加进去。
Pythonfrom google import genai
client = genai.Client()
history = [ { "type": "user_input", "content": [{"type": "text", "text": "I have 2 dogs in my house."}] } ]
interaction1 = client.interactions.create( model="gemini-3.8-flash", store=False, input=history ) print("Response 1:", interaction1.steps[-1].content[0].text)
for step in interaction1.steps: history.append(step.model_dump())
history.append({ "type": "user_input", "content": [{"type": "text", "text": "How many paws are in my house?"}] })
interaction2 = client.interactions.create( model="gemini-3.8-flash", store=False, input=history ) print("Response 2:", interaction2.steps[-1].content[0].text)
JavaScriptimport { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() { const history = [ { type: "user_input", content: [{ type: "text", text: "I have 2 dogs in my house." }] } ];
const interaction1 = await ai.interactions.create({ model: "gemini-3.8-flash", store: false, input: history }); console.log("Response 1:", interaction1.steps.at(-1).content[0].text);
history.push(...interaction1.steps);
history.push({ type: "user_input", content: [{ type: "text", text: "How many paws are in my house?" }] });
const interaction2 = await ai.interactions.create({ model: "gemini-3.8-flash", store: false, input: history }); console.log("Response 2:", interaction2.steps.at(-1).content[0].text); }
await main();
Javaimport com.google.genai.Client; import com.google.genai.gaos.models.interactions.CreateModelInteraction; import com.google.genai.gaos.models.interactions.Interaction; import com.google.genai.gaos.models.interactions.InteractionsInput; import com.google.genai.gaos.models.interactions.Model; import com.google.genai.gaos.models.interactions.Step; import com.google.genai.gaos.models.interactions.TextContent; import com.google.genai.gaos.models.interactions.UserInputStep; import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
Client client = new Client();
List
CreateModelInteraction params1 = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .store(false) .input(InteractionsInput.ofStep(history)) .build();
Interaction interaction1 = client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get(); System.out.println("Response 1: " + interaction1.outputText().orElse(""));
interaction1.steps().ifPresent(history::addAll);
history.add( UserInputStep.builder() .content(Arrays.asList(TextContent.builder().text("How many paws are in my house?").build())) .build());
CreateModelInteraction params2 = CreateModelInteraction.builder() .model(Model.of("gemini-3.8-flash")) .store(false) .input(InteractionsInput.ofStep(history)) .build();
Interaction interaction2 = client.interactions.create(CreateInteraction