Skip to content

Gemini Client使用

2024-08-30

安装依赖

bash
pip install google-generativeai

根据纯文本输入生成文本

python
import google.generativeai as genai

genai.configure(api_key="替换成你的apikey")

model = genai.GenerativeModel("替换成具体的模型名,例如:gemini-1.5-flash")
response = model.generate_content("Write a story about an AI and magic")
print(response.text)

根据文本和图片输入生成文本

python
import pathlib
import google.generativeai as genai

# Access your API key as an environment variable.
genai.configure(api_key="替换成你的apikey")
# Choose a model that's appropriate for your use case.
model = genai.GenerativeModel("替换成具体的模型名,例如:gemini-1.5-flash")

image1 = {
    "mime_type": "image/jpeg",
    "data": pathlib.Path("../../assets/image1.jpg").read_bytes(),
}

image2 = {
    "mime_type": "image/jpeg",
    "data": pathlib.Path("../../assets/image2.jpg").read_bytes(),
}

prompt = "What's different between these pictures?"

response = model.generate_content([prompt, image1, image2])
print(response.text)

生成文本流

python
import google.generativeai as genai

# Access your API key as an environment variable.
genai.configure(api_key="替换成你的apikey")
# Choose a model that's appropriate for your use case.
model = genai.GenerativeModel("替换成具体的模型名,例如:gemini-1.5-flash")

prompt = "Write a story about a magic backpack."

response = model.generate_content(prompt, stream=True)

for chunk in response:
    print(chunk.text)
    print("_" * 80)

构建互动式聊天

python
import google.generativeai as genai

genai.configure(api_key="替换成你的apikey")

model = genai.GenerativeModel("替换成具体的模型名,例如:gemini-1.5-flash")
chat = model.start_chat(history=[])

response = chat.send_message(
    "In one sentence, explain how a computer works to a young child."
)

print(response.text)

response = chat.send_message(
    "Okay, how about a more detailed explanation to a high schooler?"
)

print(response.text)