在 LlamaIndex 中使用 BigModel.io
用 Python 的 OpenAILike 或 TypeScript 的 OpenAI 类把 LlamaIndex 接入 BigModel.io(https://bigmodel.io/v1),讲清 is_chat_model、上下文窗口、流式和工具调用。
LlamaIndex 通过 OpenAI 兼容的 LLM 类调用 BigModel.io:Python 用 OpenAILike,TypeScript 用 @llamaindex/openai 的 OpenAI。
| 配置项 | Python(OpenAILike) |
TypeScript(OpenAI) |
|---|---|---|
| Base URL | api_base="https://bigmodel.io/v1" |
baseURL: "https://bigmodel.io/v1" |
| API Key | api_key=... |
apiKey: ... |
| 模型 | model="glm-5.3" |
model: "glm-5.3" |
| 聊天接口 | is_chat_model=True(必填) |
默认即可 |
模型 ID 从模型目录复制,能否调用取决于 Key 所在分组。
export BIGMODEL_API_KEY="sk-..."#安装
pip install llama-index-llms-openai-likenpm install llamaindex @llamaindex/openai#最小调用
import os
from llama_index.llms.openai_like import OpenAILike
llm = OpenAILike(
model="glm-5.3",
api_base="https://bigmodel.io/v1",
api_key=os.environ["BIGMODEL_API_KEY"],
is_chat_model=True,
is_function_calling_model=True,
context_window=128000, # 按模型页面上的上下文窗口填写
)
print(llm.complete("用三句话解释什么是向量数据库。"))import { OpenAI } from "@llamaindex/openai";
const llm = new OpenAI({
model: "glm-5.3",
apiKey: process.env.BIGMODEL_API_KEY,
baseURL: "https://bigmodel.io/v1",
});
const res = await llm.chat({
messages: [{ role: "user", content: "用三句话解释什么是向量数据库。" }],
});
console.log(res.message.content);is_chat_model 默认是 False,此时 OpenAILike 会调用旧的 /v1/completions 接口,所以一定要设为 True。context_window 填模型的真实上下文窗口,LlamaIndex 才能正确拼装提示。
想让查询引擎、Agent 等都使用这个模型,可以全局设置:
from llama_index.core import Settings
Settings.llm = llm#流式输出
for chunk in llm.stream_complete("写一首关于延迟的俳句。"):
print(chunk.delta, end="", flush=True)const stream = await llm.chat({
messages: [{ role: "user", content: "写一首关于延迟的俳句。" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}#工具调用(Python)
设置 is_function_calling_model=True 后,LlamaIndex 会发送 OpenAI tools。模型是否调用工具取决于模型本身。
from llama_index.core.tools import FunctionTool
def get_weather(city: str) -> str:
"""查询城市当前天气。"""
return f"{city}晴"
tool = FunctionTool.from_defaults(fn=get_weather)
print(llm.predict_and_call([tool], "杭州现在天气怎么样?"))#验证配置
运行最小调用。能返回回答就说明 Base URL 和 Key 正确,用量页面应出现一条端点为 /v1/chat/completions 的记录。如果返回 404 且用量里没有记录,多半是没设 is_chat_model。
#常见问题排查
所有请求都 404(Python)。 is_chat_model 为 False,请求发到了 /v1/completions。设为 is_chat_model=True。
所有请求都 404。 Base URL 少了 /v1,改成 https://bigmodel.io/v1。
提示被截断或报上下文窗口错误。 context_window 还是很小的默认值,按模型页面填写。
401 INVALID_API_KEY 或 API_KEY_REQUIRED。 当前进程里 Key 为空,或者环境中的 OPENAI_API_KEY 被优先使用了。显式传入 Key。
503 No available accounts: no available accounts supporting model: ...。 模型 ID 写错或不在 Key 的分组里。从模型目录复制 ID。
403 INSUFFICIENT_BALANCE 或 429。 到充值页面充值;429 见限额与速率。
#相关文档
更新于 · 以 Markdown 查看