通过llama-cpp-python web server 实现函数调用
ollama 在最新的版本中实现了函数调用,但是处理上还是有一些bug 的,llama-cpp-python web server 是利用了llama.cpp web server 同时进行了一些request 的处理,可以更好的兼容openai 支持了tools 函数调用,以下是基于llama-cpp-python web server 的
一个示例(注意需要模型支持函数调用,比如qwen2 就支持)
安装依赖
- llama-cpp-python 包含web server
CMAKE_ARGS="-DLLAVA_BUILD=OFF" pip install llama-cpp-python[server]
启动服务
- 下载 qwen2:7b的gguf 格式模型
可以直接通过huggingface_hub 工具下载gguf 格式的模型
huggingface-cli download Qwen/Qwen2-7B-Instruct-GGUF qwen2-7b-instruct-q4_0.gguf --local-dir .
- 启动web server
python3 -m llama_cpp.server --model ./Qwen2-7B-Instruct-GGUF Qwen2-7B-Instruct.Q4_K_M.gguf --model_alias qwen2:7b --host 0.0.0.0
- 代码访问
一个简单示例,强制使用了一个function, 使用auto 模式的暂时不是很稳定
import openai
import json
def add(a, b):
return a + b
def sub(a, b):
return a - b
openai.api_key = "demo"
openai.base_url = "http://localhost:8000/v1/"
funcs = {
"add": add,
"sub": sub
}
tools = [{
"type": "function",
"function": {
"name": "add",
"description": "Add two numbers together",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "number", "description": "First number"},
"b": {"type": "number", "description": "Second number"}
},
"required": ["a", "b"]
}
}
},
{
"type": "function",
"function": {
"name": "sub",
"description": "计算两个数的差",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "number", "description": "First number"},
"b": {"type": "number", "description": "Second number"}
},
"required": ["a", "b"]
}
}
}
]
response = openai.chat.completions.create(
stream=False,
model="qwen2:7b",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Calculate the subtraction of 500 and 70 using the sub function."}
],
tools=tools,
tool_choice={"type": "function", "function": {
"name": "sub"}},
)
message = response.choices[0].message
print(message)
if message.function_call:
result = response.choices[0].message.function_call
print(result)
func = funcs.get(result.name)
params = json.loads(result.arguments)
print(func(**params))
else:
print(message.content)
- 效果
说明
一个稳定的函数调用还是比较重要的,目前auto测试基本不成功,通过tool_choice 明确指定一个很稳定,同时对于函数调用必须有支持的模型这个比较重要,当前已经有不少开源模型都支持函数调用了,llama-cpp-python web server 还是很值得使用的,而且比较稳定,相比ollama 的稳定不少
参考资料
https://llama-cpp-python.readthedocs.io/en/latest/server/#function-calling
https://github.com/abetlen/llama-cpp-python/issues/1573
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2022-08-25 dremio 22.1.1 发布
2020-08-25 falcon 可靠高性能的构建大规模应用以及微服务的 python web 框架
2020-08-25 Understanding CPU Steal Time - when should you be worried?
2019-08-25 几个java proxy servlet 工具
2019-08-25 Presto Infrastructure at Lyft