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

= = =

相关推荐
DS随心转小程序13 小时前
ChatGPT和Gemini公式
人工智能·chatgpt·aigc·word·豆包·deepseek·ds随心转
DS随心转APP15 小时前
ChatGPT和Gemini做表格
人工智能·ai·chatgpt·deepseek·ds随心转
橘子师兄18 小时前
C++AI大模型接入SDK—deepseek接入封装
c++·人工智能·chatgpt
TOPGUS1 天前
谷歌发布三大AI购物新功能:从对话式搜索到AI代你下单
大数据·人工智能·搜索引擎·chatgpt·谷歌·seo·数字营销
飞鹰511 天前
CUDA高级优化实战:Stream、特殊内存与卷积优化—Week3学习总结
c++·gpt·chatgpt·gpu算力
TOPGUS2 天前
解析200万次对话数据:ChatGPT引用内容的核心特征与优化策略
前端·人工智能·搜索引擎·chatgpt·seo·数字营销
DS随心转APP2 天前
豆包输出word指令
人工智能·ai·chatgpt·deepseek·ds随心转
juhanishen2 天前
Agent skill 大白话,从零到1,范例解析
chatgpt·llm·agent·deepseek·agent skill
Hcoco_me2 天前
大模型面试题88:cuda core的数量 与 开发算子中实际使用的线程 关系是什么?过量线程会发生什么情况?
人工智能·深度学习·机器学习·chatgpt·职场和发展·机器人
KevinShi_BJ2 天前
读李宁老师的《AIGC 自动化编程 -- 基于 ChatGPT和 GitHub Copilot》
chatgpt·自动化·aigc