mirror of
https://github.com/ollama/ollama-python.git
synced 2026-01-14 06:07:17 +08:00
* Examples and README updates --------- Co-authored-by: fujitatomoya <tomoya.fujita825@gmail.com> Co-authored-by: Michael Yang <mxyng@pm.me>
79 lines
1.8 KiB
Python
79 lines
1.8 KiB
Python
import asyncio
|
|
from ollama import ChatResponse
|
|
import ollama
|
|
|
|
|
|
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'},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
|
|
async def main():
|
|
client = ollama.AsyncClient()
|
|
|
|
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 = await client.chat(
|
|
'llama3.1',
|
|
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')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
asyncio.run(main())
|
|
except KeyboardInterrupt:
|
|
print('\nGoodbye!')
|