【ChatGPT】【Gemini】-用Python调用google的Gemini API

用Python调用google的Gemini API

以下是Gemini自己给出的具体步骤和代码,我直接参考一次测试通过,大家可以参考。

Goodmao:Python call gemini API

Gemini:

Absolutely, calling the Gemini API with Python involves a few steps:

Prerequisites:

  1. API Key: You'll need an API key to access Gemini. You can create one easily in Google AI Studio: [invalid URL removed].

  2. Python library: Install the google-generativeai library using pip:

    Bash

    复制代码
    pip install -U -q google-generativeai

    谨慎使用代码。

Calling the API:

Here's a basic structure for calling the Gemini API for text generation:

Python

复制代码
import googleapiclient.discovery as discovery

# Replace with your API key obtained from AI Studio
API_KEY = "YOUR_API_KEY"

# Define the project ID where your Gemini model resides
PROJECT_ID = "YOUR_PROJECT_ID"

# Discovery URL for the Gemini API
service = discovery.build(
    "generativeai", "v1beta1", developerKey=API_KEY
)

# Text prompt for the model
prompt = "Write a poem about nature."

# Define the model you want to use (replace with the actual model name)
model = "your_model_name"

# Send the request with prompt and model details
body = {"prompt": prompt, "model": model}
response = service.projects().locations().models().generateText(
    parent=f"projects/{PROJECT_ID}/locations/global/models/{model}", body=body
)

# Access the generated text from the response
generated_text = response["text"]
print(generated_text)

谨慎使用代码。

Additional functionalities:

  • List Models: Use the service.projects().locations().models().list()method to explore available models.
  • Chat Conversation: Initiate a chat session with chat = model.start_chat()and interact with the model turn-by-turn.
  • Function Calling: Enable function calling during chat by setting enable_automatic_function_calling=True in start_chat().

Resources:

= = =

相关推荐
智算菩萨3 小时前
Gemini 3 Flash深度解析:Google推出的最新一代快速高效AI模型详尽性能评测报告
人工智能·aigc·gemini
北冥有一鲲7 小时前
LangChain 框架前世今生:从“万能接口”到“AI 应用全家桶”
人工智能·chatgpt·langchain
小鱼小鱼干1 天前
【Gemini简直无敌了】掌间星河:通过MediaPipe实现手势控制粒子
react.js·gemini
rockingdingo1 天前
0-1教程 ChatGPT Apps Store应用提交教程——和MCP开发部署
人工智能·chatgpt·chatgpt-app
哪吒编程2 天前
炸场!谷歌深夜发布Gemini 3 Flash:速度与智商的完美“怪胎”,GPT-5的噩梦来了?
openai·gemini
idkmn_2 天前
Agentic AI 基础概念
人工智能·python·深度学习·chatgpt·langchain
视觉&物联智能3 天前
【杂谈】-边缘计算竞赛:人工智能硬件缘何超越云端
人工智能·ai·chatgpt·aigc·边缘计算·agi·deepseek
草帽lufei3 天前
用 Gemini3 Flash 做了多半天开发,我离下岗又近了一步
google·ai编程·gemini
不会计算机的g_c__b3 天前
HuggingGPT深度解析:当ChatGPT遇上HuggingFace,打造AI世界的“万能工具箱”
人工智能·chatgpt
梁辰兴3 天前
OpenAI更新ChatGPT Images:生成速度最高提升4倍,原生多模态模型
人工智能·科技·ai·chatgpt·大模型·openai·图像生成