The Gemini API can generate text output from various types of input, including text, images, video, and audio. You can use text generation for various applications, including:
- Creative writing
- Describing or interpreting media assets
- Text completion
- Summarizing free-form text
- Translating between languages
- Chatbots
- Your own novel use cases
This guide shows you how to generate text using the
generateContent
and
streamGenerateContent
APIs. The focus is on text output from text-only and text-and-image input. To
learn more about multimodal prompting with video and audio files, see
File prompting strategies.
Before you begin: Set up your project and API key
Before calling the Gemini API, you need to set up your project and configure your API key.
Get and secure your API key
You need an API key to call the Gemini API. If you don't already have one, create a key in Google AI Studio.
It's strongly recommended that you do not check an API key into your version control system.
This tutorial assumes that you're accessing your API key as an environment variable.
Generate text from text-only input
The simplest way to generate text using the Gemini API is to provide the model with a single text-only input, as shown in this example:
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."}]
}]
}' 2> /dev/null
In this case, the prompt ("Write a story about a magic backpack") doesn't include any output examples, system instructions, or formatting information. It's a zero-shot approach. For some use cases, a one-shot or few-shot prompt might produce output that's more aligned with user expectations. In some cases, you might also want to provide system instructions to help the model understand the task or follow specific guidelines.
Generate text from text-and-image input
The Gemini API supports multimodal inputs that combine text with media files. The following example shows how to generate text from text-and-image input:
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": "Tell me about this instrument"},
{
"inline_data": {
"mime_type":"image/jpeg",
"data": "'$(base64 $B64FLAGS $IMG_PATH)'"
}
}
]
}]
}' 2> /dev/null
As with text-only prompting, multimodal prompting can involve various approaches and refinements. Depending on the output from this example, you might want to add steps to the prompt or be more specific in your instructions. To learn more, see File prompting strategies.
Generate a text stream
By default, the model returns a response after completing the entire text generation process. You can achieve faster interactions by not waiting for the entire result, and instead use streaming to handle partial results.
The following example shows how to implement streaming using the
streamGenerateContent
method to
generate text from a text-only input prompt.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:streamGenerateContent?alt=sse&key=${GOOGLE_API_KEY}" \
-H 'Content-Type: application/json' \
--no-buffer \
-d '{ "contents":[{"parts":[{"text": "Write a story about a magic backpack."}]}]}'
Build an interactive chat
You can use the Gemini API to build interactive chat experiences for your users. Using the chat feature of the API lets you collect multiple rounds of questions and responses, allowing users to step incrementally toward answers or get help with multipart problems. This feature is ideal for applications that require ongoing communication, such as chatbots, interactive tutors, or customer support assistants.
The following code example shows a basic chat implementation:
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"
Configure text generation
Every prompt you send to the model includes
parameters that
control how the model generates responses. You can use
GenerationConfig
to
configure these parameters. If you don't configure the parameters, the model
uses default options, which can vary by model.
The following example shows how to configure several of the available options.
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"
stopSequences
specifies the set of character sequences (up to 5) that will
stop output generation. If specified, the API will stop at the first appearance
of a stop_sequence
. The stop sequence won't be included as part of the
response.
temperature
controls the randomness of the output. Use higher values for more
creative responses, and lower values for more deterministic responses. Values
can range from [0.0, 2.0].
maxOutputTokens
sets the maximum number of tokens to include in a candidate.
topP
changes how the model selects tokens for output. Tokens are selected from
the most to least probable until the sum of their probabilities equals the
topP
value. The default topP
value is 0.95.
topK
changes how the model selects tokens for output. A topK
of 1 means the
selected token is the most probable among all the tokens in the model's
vocabulary, while a topK
of 3 means that the next token is selected from among
the 3 most probable using the temperature. Tokens are
further filtered based on topP
with the final token selected using temperature
sampling.
What's next
This guide shows how to use
generateContent
and
streamGenerateContent
to generate text outputs from text-only and text-and-image inputs. To learn more
about generating text using the Gemini API, see the following resources:
- File prompting strategies: The Gemini API supports prompting with text, image, audio, and video data, also known as multimodal prompting.
- System instructions: System instructions let you steer the behavior of the model based on your specific needs and use cases.
- Safety guidance: Sometimes generative AI models produce unexpected outputs, such as outputs that are inaccurate, biased, or offensive. Post-processing and human evaluation are essential to limit the risk of harm from such outputs.