ollama python 新版本支持传递python 函数
在ollama python sdk 的最近更新中,支持传递python 函数到chat 调用中,以下是一个简单示例
参考使用
- app.py
from ollama import chat
from ollama import ChatResponse
def add_two_numbers(a: int, b: int) -> int:
"""
Add two numbers
Args:
a (int): The first number
b (int): The second number
Returns:
int: The sum of the two numbers
"""
return a + b
def subtract_two_numbers(a: int, b: int) -> int:
"""
Subtract two numbers
"""
return a - b
# Tools can still be manually defined and passed into chat
subtract_two_numbers_tool = {
'type': 'function',
'function': {
'name': 'subtract_two_numbers',
'description': 'Subtract two numbers',
'parameters': {
'type': 'object',
'required': ['a', 'b'],
'properties': {
'a': {'type': 'integer', 'description': 'The first number'},
'b': {'type': 'integer', 'description': 'The second number'},
},
},
},
}
prompt = 'What is three plus one?'
print('Prompt:', prompt)
available_functions = {
'add_two_numbers': add_two_numbers,
'subtract_two_numbers': subtract_two_numbers,
}
response: ChatResponse = chat(
'qwen2.5:1.5b',
messages=[{'role': 'user', 'content': prompt}],
tools=[add_two_numbers, subtract_two_numbers_tool],
)
if response.message.tool_calls:
# There may be multiple tool calls in the response
for tool in response.message.tool_calls:
# Ensure the function is available, and then call it
if function_to_call := available_functions.get(tool.function.name):
print('Calling function:', tool.function.name)
print('Arguments:', tool.function.arguments)
print('Function output:', function_to_call(**tool.function.arguments))
else:
print('Function', tool.function.name, 'not found')
- 效果
说明
尽管支持传递函数,但是格式是有一些要求的,需要添加函数docs 说明
参考资料
https://github.com/ollama/ollama-python/blob/main/examples/tools.py
https://google.github.io/styleguide/pyguide.html#doc-function-raises
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2023-11-27 mupdf webassembly 试用
2023-11-27 一些基于webassembly 的serverless 框架
2021-11-27 meow 辅助开发cli 应用的工具
2021-11-27 使用remix 进行web开发
2021-11-27 oceanbase 最好使用obproxy 进行访问
2021-11-27 oceanbase 扩容缩容处理
2020-11-27 扩展gobackup支持minio以及定时配置