很多OneAPI类的平台,提供了免费的API-KEY,不会使用怎么办?
在线等吗。。。
不!
看下面的方法
-
【方法1】通过
REST
接口进行服务调用。如果你只需要直接对话/一次问话的功能。
这篇教程里写是REST
接口方法 【1024送福利】硅基流动送2000万token啦!撒花✿✿ 附使用教程
像下面这样调用request
的就叫REST
接口方法
-
【方法2】通过
OpenAI
接口调用。 如果你想要封装为一个大模型/对话模型,体验更高级功能,比如跟LangChain
框架结合。
像下面这样调用openai
的就叫OpenAI
接口方法
1. LangChain自定义大模型
安装 Python3.7.1 或更高版本并设置虚拟环境后,即可安装 OpenAI Python 库
pip install --upgrade openai
以智谱zhipu
的glm-3
为例,下面是LangChain自定义大模型的代码
from openai import OpenAI
from langchain.prompts import ChatPromptTemplate
# API密钥
API_KEY = "sk-sxhxxxoyw"
# 自定义硅基流动大模型类
class CustomLLM_Siliconflow:
def __call__(self, prompt: str) -> str:
# 初始化OpenAI客户端(base_url是硅基流动网站的地址)
client = OpenAI(api_key=API_KEY, base_url="https://api.siliconflow.cn/v1")
# 发送请求到模型
response = client.chat.completions.create(
model='THUDM/glm-4-9b-chat',
messages=[
{
'role': 'user',
'content': f"{
prompt}"} # 用户输入的提示
],
)
# 打印响应结构,以便调试
# print("Response structure:", response)
# 收集所有响应内容
content = ""
if hasattr(response, 'choices') and response.choices:
for choice in response.choices: