LLM的API KEY获取和测试

openai

openai国内不能访问,只能通过第三方渠道访问,以F2API为例

获取API KEY地址:https://f2api.com/login

测试API KEY是否可用

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    openai_api_base="https://api.f2gpt.com", openai_api_key="******"
)
res = llm.invoke("1+2等于多少")
print(res.content)

百度千帆

直接访问百度千帆平台获取AK和SK:https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Hlwerugt8

测试AK和SK是否可用

import os
import qianfan
 # 使用AK和SK 设置环境变量
os.environ["QIANFAN_ACCESS_KEY"]="******"
os.environ["QIANFAN_SECRET_KEY"]="******"

chat_comp = qianfan.ChatCompletion(model="ERNIE-Speed-128K")
resp = chat_comp.do(messages=[{
    "role": "user",
    "content": "你好,千帆"
}], top_p=0.8, temperature=0.9, penalty_score=1.0)

print(resp["result"])

通义千问

直接访问通义千问平台获取API KEY:https://help.aliyun.com/zh/dashscope/developer-reference/acquisition-and-configuration-of-api-key?spm=a2c4g.11186623.0.0.24635120c6myVu

测试API KEY是否可用

import random
from http import HTTPStatus
import dashscope
from dashscope import Generation  # 建议dashscope SDK 的版本 >= 1.14.0
# 设置api key
dashscope.api_key = '******'
def call_with_messages():
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '如何做西红柿炒鸡蛋?'}]
    response = Generation.call(model="qwen-turbo",
                               messages=messages,
                               # 设置随机数种子seed,如果没有设置,则随机数种子默认为1234
                               seed=random.randint(1, 10000),
                               # 将输出设置为"message"格式
                               result_format='message')
    if response.status_code == HTTPStatus.OK:
        print(response)
    else:
        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        ))


if __name__ == '__main__':
    call_with_message
posted @ 2024-08-20 20:20  hjy1995  阅读(102)  评论(0编辑  收藏  举报