Skip to content

Instantly share code, notes, and snippets.

@serg-yalosovetsky
Last active May 4, 2025 14:01
Show Gist options
  • Save serg-yalosovetsky/12b76b41382535e706ea34a88eea9738 to your computer and use it in GitHub Desktop.
Save serg-yalosovetsky/12b76b41382535e706ea34a88eea9738 to your computer and use it in GitHub Desktop.
function_calling.py
import asyncio
import math
import ollama
def calc_hypotenuse(a: float, b: float) -> float:
"""
Calculate the hypotenuse of a right triangle
Args:
a: The first leg of the triangle
b: The second leg of the triangle
Returns:
float: The hypotenuse of the triangle
"""
hypotenuse = math.sqrt(a**2 + b**2)
print(f"The hypotenuse of the triangle is {hypotenuse}")
return hypotenuse
def main():
response = ollama.chat(
'qwen3',
messages=[{'role': 'user', 'content': 'What is the hypotenuse of a right triangle with legs 3758 and 4321?'}],
tools=[calc_hypotenuse], # Actual function reference
)
print(response)
# Check if the response contains a tool call
if response['message']['tool_calls']:
tool_call = response['message']['tool_calls'][0] # Assuming one tool call
function_name = tool_call['function']['name']
arguments = tool_call['function']['arguments']
# Get the function from globals based on the function name
if function_name in globals() and callable(globals()[function_name]):
# Call the function with the arguments provided by the model
result = globals()[function_name](**arguments)
print(f"Result from tool call: {result}")
else:
print(f"Unknown or non-callable tool: {function_name}")
else:
# Handle responses without tool calls (e.g., direct text answers)
print(f"Assistant message: {response['message']['content']}")
# Run the agent
if __name__ == "__main__":
import time
start_time = time.time()
result = main()
end_time = time.time()
print(f"Time spent: {end_time - start_time:.2f} seconds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment