ollama实现function calling
时间: 2025-01-11 10:22:44 浏览: 720
### 如何在 Ollama 中实现 Function Calling
为了实现在 Ollama 中的函数调用功能,需先理解并配置 `OllamaFunctions` 和相应的工具集。这涉及到几个关键步骤。
#### 设置 Ollama Functions
首先,确保已安装最新版本的 LangChain 库以及 Ollama SDK。接着,在项目中引入必要的模块:
```python
from langchain.chains import LLMChain
from ollama.functions import OllamaFunctions
```
定义模板时要特别注意加入对 `Tools` 的支持。这意味着当创建用于处理输入输出逻辑的链(chain)时,应该指定哪些外部能力是可以被访问到的[^2]。
#### 实现具体的功能调用
下面是一个简单的例子来说明如何执行这一过程:
假设有一个名为 `get_height_difference` 的 Python 函数用来计算两个人之间的身高差异,并希望让 AI 模型能够调用这个方法作为其解决问题的一部分,则可以在初始化阶段像这样注册该服务:
```python
def get_height_difference(name1, name2):
heights = {"Brian": 66, "Suzy": 71}
diff = abs(heights[name1] - heights[name2])
return f"{name1} is {diff} inches {'shorter' if heights[name1]<heights[name2] else 'taller'} than {name2}"
functions = [
{
"name": "get_height_difference",
"description": "Calculate the difference of two people's height.",
"parameters": {
"type": "object",
"properties": {
"personA": {"title":"Person A", "type": "string"},
"personB":{"title":"Person B","type":"string"}
}
},
}
]
ollama_functions = OllamaFunctions(functions=functions)
```
之后,构建一个基于上述自定义行为的语言模型链条,并传入准备好的 `ollama_functions` 对象以便于后续操作中启用这些特性:
```python
chain = LLMChain(llm=..., prompt=prompt_template, functions=ollama_functions)
response = chain.run({"input_variables": ...,})
print(response)
```
这里省略了一些细节性的参数设定工作,比如具体的提示词设计等;但是核心思路就是如此 —— 将想要暴露给大模型使用的业务逻辑封装成标准接口形式,再经由专门适配器传递进去即可完成集成[^1]。
对于返回的结果解析部分,可以通过如下方式获取 JSON 格式的响应数据中的特定字段值[^3]:
```python
import json
# 假设 response 是来自上一步得到的消息对象
json_string = response.to_json()['kwargs']['additional_kwargs']['function_call']['arguments']
parsed_data = json.loads(json_string)
result_text = parsed_data.get('return')
print(result_text)
```
阅读全文
相关推荐















