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

= = =

相关推荐
小白说大模型7 小时前
Spring AI 框架中集成 MCP 的完整指南:从服务端到客户端的全流程实践
大数据·数据库·人工智能·安全·spring·chatgpt·开源
精彩AI说7 小时前
ChatGPT总是答非所问怎么办?提示词歧义、上下文干扰与提问方式排查
chatgpt·prompt·提示词·ai工具·chatgpt教程
YH55269847 小时前
ChatGPT Plus 与 OpenAI API 的区别:API Key、Token 和计费机制详解
人工智能·chatgpt
精彩AI说9 小时前
ChatGPT回答内容总是漏重点怎么办?需求拆分、检查清单与二次补充方法
人工智能·chatgpt
wujian831113 小时前
【腾讯元宝手机版生成的表格怎么复制下来】?试试 [ AI 导出鸭 ] 的“格式网关”
人工智能·ai·chatgpt·智能手机·ai导出鸭
AI导出鸭13 小时前
怎么让腾讯元宝做表格?AI导出鸭苹果版通过解析引擎将元宝表格HTML转为结构化数据,一键导出标准Excel或Word
人工智能·chatgpt·html·excel·ai导出鸭
程序员爱钓鱼13 小时前
Go 编程实战:闭包 Closure——函数如何记住外部变量
后端·google·go
wujian831114 小时前
豆包导出word手机,就用AI导出鸭:一站式批量导出方案深度解析
人工智能·ai·chatgpt·智能手机·word·ai导出鸭
YH55269841 天前
GPT‑5.6 Sol 原本支持 1M 上下文,Codex 现已放开此前限制,如何看待这次调整?
java·jvm·人工智能·gpt·算法·chatgpt
“初生”1 天前
用 Codex 做一致性 AI 动画:5 步工作流,角色不再漂移
人工智能·ai·chatgpt