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

= = =

相关推荐
YH55269848 小时前
如何减少大模型的token消耗?日常使用,可以通过什么方式减少大模型 token 的消耗
gpt·chatgpt·github
richard_first10 小时前
从 ChatGPT 到机器人:NVIDIA Jetson Orin Nano 2 背后的 Physical AI 浪潮
人工智能·chatgpt·机器人
江畔柳前堤10 小时前
字节跳动产品全景图:从应用表象到技术深海的七层解剖
人工智能·chatgpt·架构·json·batch
DeepIntelli11 小时前
企业独立站内容怎么改,才更容易被大模型引用:从语义化 HTML 到可抽取结构的工程化调整
人工智能·chatgpt
云卷云舒___________1 天前
谷歌内测Gemini 3.8 Flash,智谱开源GLM-5.3权重,腾讯亮剑Hy4,开源大模型神仙打架 | 8月29日 AI日报
谷歌·腾讯·glm·gemini·混元·智谱·ai日报
精彩AI说1 天前
ChatGPT合并多份资料总是内容重复?去重、分类与统一结构整理方法
chatgpt·提示词·ai工具·办公效率·资料整理·chatgpt教程
DeepIntelli2 天前
GEO 团队选型
人工智能·chatgpt
小满zs2 天前
Go语言第十章(指针)
后端·google·go
精彩AI说2 天前
ChatGPT写段落总是太散?主题句、层次结构与段落衔接优化方法
chatgpt·ai写作·提示词·文章结构·chatgpt教程