How to get text from Gemini API response
Quick answer
Use the OpenAI SDK v1 pattern to call the Gemini API and access the generated text from the response's
choices[0].message.content field. This field contains the text output from the model after a chat completion request.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official OpenAI Python SDK and set your API key as an environment variable to authenticate requests to the Gemini API.
pip install openai>=1.0 Step by step
Use the OpenAI client to create a chat completion request with a Gemini model. Extract the generated text from the choices[0].message.content field in the response.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gemini-1.5-pro",
messages=[{"role": "user", "content": "Hello, Gemini!"}]
)
text = response.choices[0].message.content
print(text) output
Hello, Gemini! How can I assist you today?
Common variations
You can use different Gemini models like gemini-1.5-flash or gemini-2.0-flash by changing the model parameter. For asynchronous calls, use async client methods if supported. Streaming responses require handling partial data chunks.
import asyncio
import os
from openai import OpenAI
async def main():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = await client.chat.completions.acreate(
model="gemini-1.5-flash",
messages=[{"role": "user", "content": "Hello asynchronously!"}]
)
print(response.choices[0].message.content)
asyncio.run(main()) output
Hello asynchronously! How can I help you today?
Troubleshooting
- If you get an authentication error, verify your
OPENAI_API_KEYenvironment variable is set correctly. - If the response has no
choicesormessage, check that the model name is valid and the request format matches the SDK requirements. - For network errors, ensure your internet connection is stable and the OpenAI endpoint is reachable.
Key Takeaways
- Use the OpenAI Python SDK v1 pattern to call Gemini models for chat completions.
- Extract generated text from the response's choices[0].message.content field.
- Set your API key in the environment variable OPENAI_API_KEY for authentication.