四个步骤搞定Google PaLM2 API的调用
Bard虽然不像Chatgpt那么火,但Google仍然是人工智能的泰斗,未来谁会笑到最后还未可知。
而且Google的PalM2的API还是免费可以使用,而ChatGPT的API调用你还得付钱。多一条路总比啥都不做强,那么如何访问谷歌的PaLM2 API?
四个步骤可以快速搞定:
- 前提是需要有个 Google账号 ,如果你要访问谷歌,需要科学上网(梯子或者机场,搜以下)
- 访问Google的MakerSuite网站 申请API Key ,可以:点击如下链接:
你可以试用Text Prompt,Data Prompt或者Chat Prompt的效果,当然我们本次的核心是访问API,所以点击右下角的”Create an API Key“:
点击“Create API Key in new project”,那么Google会帮你生成相应的API Key,把这个key拷贝下来放在一个私密地方以待后用。
3. 安装相关的工具包 ,包括generativeai和dotenv
pip install google.generativeai
pip install dotenv
创建环境变量文件.env ,把刚才申请的key写入到.env文件,具体如下:
GOOGLE_PALM_API_KEY = "AI****************************"
4.编写代码:从环境变量读取API_Key,调用Google PaLM2的文本生成模型(默认调用)
import google.generativeai as palm
from dotenv import find_dotenv,load_dotenv
import os
env = load_dotenv(find_dotenv())
api_key = os.environ['GOOGLE_PALM_API_KEY']
palm.configure(api_key=api_key)
# Generate text from a prompt:
prompt = "write a poem about rainbow."
response = palm.generate_text(prompt=prompt)
# Print the generated text:
print(response.result)
返回结果如下:
I've seen the rainbow touch the ground,
Its feet in clover, its head in clouds.
I've seen it span a valley wide,
Announcing joy on every side.
I've seen it arch above a hill,
A promise that the storm is past.
I've seen it shimmer in the mist,
A reminder that God's love is vast.
I've seen the rainbow in the dark,
A beacon of hope, a guiding spark.
I've seen it in the light of day,