如何调用google api 进行开发(使用免费版本)

如何调用google api 进行开发(使用免费版本)

1.前置条件:

  • 有一个你自己的谷歌账户
  • 打开这个网页:https://aistudio.google.com/projects
  • step up:
    1. Project/ Create a new project
    2. set your Project name / ensure your name and "create Project"
    3. API key -> Create a new key-> set your project
    4. success

PS:官方文档详见:https://ai.google.dev/gemini-api/docs/quickstart

2. 环境安装

  1. 安装conda环境,可以参考:Anaconda超详细安装教程(Windows环境下)

  2. (cmd)创建虚拟环境并进入对应的虚拟环境

    conda create -n google python==3.10

    然后全部回车就行

    conda activate google

    1. 安装依赖:

      bash 复制代码
      pip install -q -U google-genai
    2. 安装依赖完毕

3.设置api

  1. 打开环境变量设置:

    如果找不到搜索框可以从控制面板进入,同样搜索环境变量即可
    2. 复制你的api-key

    1. 构造环境变量:

    变量名:GEMINI_API_KEY

    Linux系统自己搜一下修改环境变量吧

4. 调用google服务(文本输入输出)

python 复制代码
from google import genai

# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()

#这里的model需要google ai stdio上看看有没有额度,有额度就可以用,但是不能直接复制,找到免费的模型后,在https://ai.google.dev/gemini-api/docs/models?hl=zh-cn 找到他的模型代码【Model code】,复制这个才有用
response = client.models.generate_content(
    model="gemini-3-flash-preview", contents="Explain how AI works in a few words"
)
print(response.text)

如果顺利的话应该已经出来结果了

error1:大概率是环境变量没更新,可以重启一下,不行就再看看有没有设置api

error2:大概率是你所在地区的网络问题,这个你要到网络支持的地区才行。

成功的情况

5.图片调用

PS:主要你使用的模型额度,还有是否支持图片,有一些模型并非多模态模型,有可能会不支持图片,这里使用 gemini-3-flash-preview 作为示例

code:

python 复制代码
import json,os,re
from google import genai
from google.genai import types
from pathlib import Path

import typing_extensions as typing

#https://docs.cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.cachedContents#Schema
promote_default = '''	#自行根据修改提示词,这里仅作演示
plz explain this img by json:
{
    'img_name':str,
    'info': str
}
'''

def json_load(input_str: str):
    try:
        json_str = re.sub(r'^```(?:json)?\s*', '', input_str.strip())
        json_str = re.sub(r'\s*```$', '', json_str)
        json_data = json.loads(json_str)
        return json_data
    except Exception as e:
        print(e)
        return None


def det_example_outputJson(file_path:str,save_path:str, promote:str=promote_default):
    '''
    通过指定json结构输出【适用于 gemini2.5+ 】
    Args:
        file_path:
        promote:

    Returns:

    '''
    file_path = file_path

    with open(file_path, 'rb') as f:
        image_bytes = f.read()

    client = genai.Client()
    response = client.models.generate_content(
        model='gemini-3-flash-preview',              #这个自己根据需求设置,也需要看你自己的额度
        contents=[
            types.Part.from_bytes(
                data=image_bytes,
                mime_type='image/jpeg',
            ),
            str(promote)
        ],#还支持其他参数的json格式输出,这里只是用promote让他json输出,并非完全格式正确。

    )
    try:
        # response_json = json.loads(response.text)
        response_json = json_load(response.text)
        if response_json is None:
            print(response.text)
            return
        # build save path
        save_path: Path = Path(save_path)
        save_path.mkdir(parents=True, exist_ok=True)
        save_path = save_path / f'{Path(file_path).stem}.json'#输出的json和你的图片同名,可以根据需要自己修改

        with open(save_path, 'w', encoding='utf-8') as f:
            json.dump(response_json, fp=f, indent=4,ensure_ascii=False)
        # print(json.dumps(response_json, indent=4))
        print(f'save result to {save_path}')
    except Exception as e:
        print(e)
        print(response.text)
        return

if __name__ == '__main__':
    file_path = r'apple.jpg'					#自行选择图片,我这里选择了https://pixabay.com/photos/apple-red-red-apple-2788616/的苹果图片
    save_path = r'path_to_save_dir'				#填写文件保存路径【具体到文件夹就行】
    det_example_outputJson(file_path,save_path)

修改图片地址和保存路径应该就可以输出了【建议jpg图片,其他图片可能会存在兼容性问题】

输出json如上所示

6.尾声

基础入门就大概是这样,感兴趣可以看下限制json的输出和其他调用方式,这里仅作为简单的调用教程。

有多余资金的话可以赞助一下gemingpt,毕竟能免费给你调用的厂家不多了,也不要那么暴力调用,过河拆桥。【不过google也是缩次数了#0#,之前好像蛮多次数的给你,只能说用户与厂家之间还是会有各自的盘算吧】

相关推荐
广师大-Wzx3 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
hef2883 小时前
golang如何使用range over func_golang range over func迭代器使用方法
jvm·数据库·python
qq_380619165 小时前
html如何查看windows
jvm·数据库·python
henrylin99995 小时前
Hermes Agent 核心运行系统调用流程--源码分析
开发语言·人工智能·python·机器学习·hermesagent
wgzrmlrm745 小时前
如何加固SQL环境部署_删除默认安装的示例数据库
jvm·数据库·python
珎珎啊5 小时前
Python3 字符串核心知识点
开发语言·python
lbb 小魔仙5 小时前
Python_多模态大模型实战指南
开发语言·python
XDHCOM6 小时前
Python os.system() 和 subprocess 怎么选?运行系统命令哪个更好用?
开发语言·网络·python
雨墨✘6 小时前
golang如何实现设备指纹识别_golang设备指纹识别实现详解
jvm·数据库·python