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

= = =

相关推荐
全栈弄潮儿1 天前
如何向 AI 清楚描述一个编程需求
chatgpt·openai·ai编程
xiongmaogeo1 天前
外贸企业如何利用GEO优化,抢占海外AI平台的搜索流量
人工智能·chatgpt·facebook
TunerT_TQ1 天前
Google|LangExtract 源码静态评测:从 90 个 Python 文件看大模型结构化信息抽取工程基础
google·开源·github
DS随心转APP1 天前
生成word文档的DeepSeek底层解码与“AI导出鸭”工程化方案:一份技术架构师的全维度测评
人工智能·ai·chatgpt·word·deepseek·ai导出鸭
DS随心转插件1 天前
ChatGPT星号怎么去除?AI 导出鸭从底层根治标记符号顽疾
人工智能·ai·chatgpt·word·deepseek·ai导出鸭
上玄code1 天前
【Agent精讲】调一个LLMAPI背后的工程问题
java·开发语言·python·chatgpt
无己心2 天前
基于 RAG 的 AI GEO 内容优化引擎架构
人工智能·ai·chatgpt
全栈弄潮儿2 天前
一周总结:AI 编程入门最重要的 3 个原则
chatgpt·openai·ai编程
DS随心转APP2 天前
deepseek生成的word怎么下载 AI导出鸭全平台方案技术深度测评
人工智能·ai·chatgpt·word·deepseek·ai导出鸭