首页 > 其他分享 >google gemini api使用

google gemini api使用

时间:2023-12-14 23:22:05浏览次数:26  
标签:google text content api model gemini response

title: google gemini api使用
banner_img: https://cdn.studyinglover.com/pic/2023/12/334c0c129076533308cbc7e03f8c55be.png
date: 2023-12-14 23:15:00
tags:
- google gemini

google gemini api使用

google最近发布了gemini api,我之前在我的博客 介绍了如何申请,这篇文章来介绍如何使用

首先下载google的库

pip install -q -U google-generativeai

引入必要的包

import pathlib
import textwrap

import google.generativeai as genai

from IPython.display import display
from IPython.display import Markdown


def to_markdown(text):
  text = text.replace('•', '  *')
  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))

先将api添加到环境变量

export GOOGLE_API_KEY=你的密钥

接下来获取密钥

GOOGLE_API_KEY=os.getenv('GOOGLE_API_KEY')
genai.configure(api_key=GOOGLE_API_KEY)

可以通过下面命令获取所有模型

for m in genai.list_models():
  if 'generateContent' in m.supported_generation_methods:
    print(m.name)

文本输入

接下来创建一个模型,并输入一个prompt,获取输出并转换成markdown格式

model = genai.GenerativeModel('gemini-pro')
response = model.generate_content("What is the meaning of life?")
to_markdown(response.text)

如果你的prompt比较奇奇怪怪,那么可能会不能正常获取到返回,你可以查看response.prompt_feedback获取原因。

还有一个有趣的事情,gemini可能会生成多个输出(candidates),通过response.candidates获取。

流式传输也是可以的

response = model.generate_content("What is the meaning of life?", stream=True)
for chunk in response:
  print(chunk.text)
  print("_"*80)

图片输入

下载官方的示例图片

curl -o image.jpg https://t0.gstatic.com/licensed-image?q=tbn:ANd9GcQ_Kevbk21QBRy-PgB4kQpS79brbmmEG7m3VOTShAn4PecDU5H5UxrJxE3Dw1JiaG17V88QIol19-3TM2wCHw

通过下面的代码可以查看图片

import PIL.Image

img = PIL.Image.open('image.jpg')
img

image.png

接下来创建模型,并获取输出

model = genai.GenerativeModel('gemini-pro-vision')
response = model.generate_content(img)

to_markdown(response.text)

也可以同时提供文本和图像

response = model.generate_content(["Write a short, engaging blog post based on this picture. It should include a description of the meal in the photo and talk about my journey meal prepping.", img], stream=True)
response.resolve()
to_markdown(response.text)

聊天

初始化聊天:

model = genai.GenerativeModel('gemini-pro')
chat = model.start_chat(history=[])
chat

开始聊天

response = chat.send_message("In one sentence, explain how a computer works to a young child.")
to_markdown(response.text)

你一定想在这里使用图片聊天,请注意,gemini-pro-vision未针对多轮聊天进行优化

可以通过chat.history 获取聊天历史

for message in chat.history:
  display(to_markdown(f'**{message.role}**: {message.parts[0].text}'))

流式传输也可以使用

response = chat.send_message("Okay, how about a more detailed explanation to a high schooler?", stream=True)

for chunk in response:
  print(chunk.text)
  print("_"*80)

嵌入

使用起来没啥可说的

result = genai.embed_content(
    model="models/embedding-001",
    content="What is the meaning of life?",
    task_type="retrieval_document",
    title="Embedding of single string")

# 1 input > 1 vector output
print(str(result['embedding'])[:50], '... TRIMMED]')

当然,批量处理也可以

result = genai.embed_content(
    model="models/embedding-001",
    content=[
      'What is the meaning of life?',
      'How much wood would a woodchuck chuck?',
      'How does the brain work?'],
    task_type="retrieval_document",
    title="Embedding of list of strings")

# A list of inputs > A list of vectors output
for v in result['embedding']:
  print(str(v)[:50], '... TRIMMED ...')

你甚至可以传递一个chat.history

result = genai.embed_content(
    model = 'models/embedding-001',
    content = chat.history)

# 1 input > 1 vector output
for i,v in enumerate(result['embedding']):
  print(str(v)[:50], '... TRIMMED...')

标签:google,text,content,api,model,gemini,response
From: https://www.cnblogs.com/studyinglover/p/17902449.html

相关文章

  • google gemini api申请
    title:googlegeminiapi申请banner_img:https://cdn.studyinglover.com/pic/2023/12/334c0c129076533308cbc7e03f8c55be.pngdate:2023-12-1422:40:00tags:-踩坑googlegeminiapi申请首先登陆https://ai.google.dev/pricing往下滑,看一看到免费选项,每分钟60词请求......
  • fastapi-cdn-host发布了 -- FastAPI接口文档/docs页面空白的问题,现在很好解决了~
    代码地址:https://github.com/waketzheng/fastapi-cdn-host如何安装:pipinstallfastapi-cdn-host使用方法:fromfastapiimportFastAPIfromfastapi_cdn_hostimportmonkey_patch_for_docs_uiapp=FastAPI()monkey_patch_for_docs_ui(app)#增加这行就能解决/docs页面空......
  • Google Bard背单词
    promptActasifyouareanexpertonwritingpromptsthathelpuserstolearnvocabulary.Youwillexaminethispromptanduseyourexpertisetotaketheseinstructionsandusethemtoallowuserstolearnvocabulary.Youwillnevertestusers'know......
  • FastAPI: OpenAPI
     [email protected]('/items',operation_id='a',openapi_extra={"x-aperture-labs-portal":"blue",'requestBody':{'content':{'application/json':{'......
  • Postman/apifox pre-request script
    Postman/apifoxpre-requestscriptconstUUID=require('uuid');//HelperfunctiontogeneratethesignaturefunctionmakeSign(md5Key,params){constpreStr=buildSignString(params);consttext=preStr+md5Key;console.log("signS......
  • C++ 快速加载 Dll 里的 API
    最近项目里要重新编写程序加载器,也就是编译出一个可执行文件,在Windows上是.exe为什么要程序加载器?个人理解是,可执行文件大小最好是越小越好,功能都可以由dll文件执行而程序加载器里最重要的是两个win32函数,分别是LoadLibrary和GetProcAddress前者是加载dll并返回i......
  • ASP.NET WebApi(.Net Framework) 应用CacheManager
    ASP.NETWebApi(.NetFramework)应用CacheManager,内存+Redis1,WebApi版本选.net4.6.2以上版本2,nuget包Unity(4.0.0.1)Unity.AspNet.WebApi(4.0.0.1)CacheManager.CoreCacheManager.Microsoft.Extensions.Caching.MemoryCacheManager.Microsoft.Extensions.ConfigurationCacheMa......
  • 如何在 Eolink Apikit 中发起 TCP/UDP 文档测试
    TCP/UDP是两种常用的网络传输协议。TCP协议提供可靠的连接,而UDP协议提供不可靠的连接。TCP协议是面向连接的协议,在建立连接之前,客户端和服务器需要先握手。握手完成后,客户端和服务器之间就会建立一个可靠的连接。在连接建立之后,客户端和服务器可以通过该连接进行数据传输。T......
  • API 设计错误
    缺乏一致性:API设计中的一个常见错误是缺乏连贯的结构。命名约定、数据格式和错误处理方面的不一致可能会导致尝试集成API的开发人员感到困惑。要解决此问题,请为命名、格式设置和响应错误建立清晰且一致的准则。一致性不仅简化了使用,还改善了整体用户体验。文档不充分:文档不......
  • BAPI
    FICO模块:FB01创建会计凭证:BAPI_ACC_DOCUMENT_POST检查会计凭证:BAPI_ACC_DOCUMENT_CHECKFB02修改会计凭证:FI_ITEMS_MASS_CHANGEFB08过账冲销会计凭证:BAPI_ACC_DOCUMENT_REV_POST会计:冲销凭证:BAPI_ACC_ACT_POSTINGS_REVERSE会计:过帐票据凭证冲销:BAPI_ACC_BILLIN......