How to use system instruction in Gemini API
system parameter in the client.chat.completions.create method to provide system instructions in the Gemini API. This parameter sets the assistant's behavior context separate from user messages.PREREQUISITES
Python 3.8+OpenAI API keypip install openai>=1.0
Setup
Install the official OpenAI Python SDK and set your API key as an environment variable.
- Run
pip install openaito install the SDK. - Set your API key in your environment:
export OPENAI_API_KEY='your_api_key_here'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key_here"(Windows).
pip install openai Step by step
Use the system parameter to specify system instructions that guide the assistant's behavior, distinct from user messages. Below is a complete example using the Gemini model gemini-1.5-pro with the OpenAI SDK v1 pattern.
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",
system="You are a helpful assistant that responds concisely.",
messages=[
{"role": "user", "content": "Explain the benefits of using system instructions."}
]
)
print(response.choices[0].message.content) System instructions help set the assistant's behavior and tone, ensuring responses are concise and relevant.
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 additional handling with the SDK's streaming interface.
Troubleshooting
If you receive errors about missing system parameter, ensure you are using the latest OpenAI SDK v1 and that the parameter is correctly named. If the assistant ignores system instructions, verify the model supports system prompts and that your API key has access.
Key Takeaways
- Use the
systemparameter to set assistant behavior in Gemini API calls. - Always use the OpenAI SDK v1 pattern with
client.chat.completions.createfor Gemini models. - Set your API key securely via environment variables to avoid exposure.
- Different Gemini models support system instructions similarly; adjust
modelas needed. - Check SDK version and model access if system instructions are not applied.