Ollama教程——使用Ollama与LangChain实现Function Calling(函数调用)的详细教程(一)

本教程详细介绍了如何利用Ollama和LangChain实现函数调用,提高AI模型在特定任务的性能。内容包括OllamaFunctions的简介、环境设置、函数绑定、调用及结构化输出的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

### 如何在 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) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

walkskyer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值