【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:

= = =

相关推荐
孤狼GPT8 小时前
Codex没有GPT-5.6 Sol选项怎么办?ChatGPT账号和API Key区别讲清楚
chatgpt·ai编程·codex·api key·gpt-5.6
中微极客9 小时前
从提示词到产品级视频:生成式AI的工程化实践与工具栈选型(LTX Studio实战)
人工智能·chatgpt·音视频
仙逆GPT9 小时前
Codex客户端找不到GPT-5.6模型怎么办?版本、配置和入口排查
chatgpt·ai编程·codex·sol·gpt-5.6
柳杉10 小时前
没写一行代码!我用 ChatGPT 5.6 (Sol) 做了一个智慧充电站 3D 大屏
前端·chatgpt·数据可视化
牧濑红莉1 天前
零基础认识大语言模型(LLM)工作原理(2.Token 到底是什么?)
人工智能·语言模型·chatgpt
her_heart1 天前
把 ChatGPT 5.6 放进需求评审和测试设计之后,我反而减少了“一次成稿”的期待
网络·人工智能·网络协议·chatgpt·测试用例
jianwuhuang821 天前
deepseek 生成的图表怎么导出?AI 导出鸭多方案详解
人工智能·ai·chatgpt·ai导出鸭
武子康1 天前
GPT-Live 全双工语音 Agent 深度拆解:连续交互 + 后台委托 + Voice Runtime 三层架构
人工智能·ai·chatgpt·架构·llm·交互
cocoafei1 天前
GPT-5.6 后,别再混淆 ChatGPT 和 Codex 额度了
前端·人工智能·chatgpt
Svan L1 天前
文献综述工具比较:沁言学术与 ChatGPT Plus 的可用性分析
人工智能·chatgpt