This is a simple, beginner-friendly example showing how to use function calling with Ollama.
This project demonstrates the complete workflow for function calling with Ollama:
- Create a custom function (
get_stock_price) that fetches real stock prices - Register the function with Ollama so the LLM knows it exists
- Handle tool calls when the LLM decides it needs to use your function
- Feed results back to the LLM so it can generate a natural, coherent response
- Avoid raw output – the LLM explains the results instead of just dumping numbers
Instead of getting a raw response like 175.42, you get a helpful answer like "Apple's current stock price is $175.42 per share."
- Python 3.8+
- Ollama installed and running
- The
qwen3:4b-instructmodel (or modify the code for your preferred model)
git clone https://github.com/kirillsaidov/ollama-function-calling.git
cd ollama-function-callingpython3 -m venv venv
./venv/bin/pip install -r requirements.txt./venv/bin/python main.py>> What's Apple's stock price?
Apple's current stock price is $252.13 per share.
>> How much is Google trading for?
Alphabet Inc. (GOOGL) is currently trading at 247.14 per share.- User asks a question
- LLM analyzes if it needs external data
- If yes, LLM returns a tool call instead of a final answer
- Your code receives the tool call
- Executes your custom function (
get_stock_price) - Captures the real-world result
- Tool result is added to the conversation history
- LLM gets the complete context (original question + tool result)
- LLM generates a natural, coherent response using the data
This ensures users get helpful explanations, not just raw data dumps!
ollama-function-calling/
├── main.py # Main example code
├── README.md # This file
└── requirements.txt # DependenciesWant to add your own functions? Follow this procedure:
- Create your function:
def get_weather(city: str) -> str:
# Your implementation here
return f"Sunny, 75°F in {city}"- Add it to the TOOLS dictionary:
TOOLS_LIST = {
'get_stock_price': get_stock_price,
'get_weather': get_weather, # Add your function
}- Define the tool schema:
TOOL_SCHEMA = [
# ... existing stock price schema
{
'type': 'function',
'function': {
'name': 'get_weather',
'description': 'Get current weather for a city',
'parameters': {
'type': 'object',
'properties': {
'city': {'type': 'string', 'description': 'City name'}
},
'required': ['city'],
},
},
}
]Now you can test it by running the script.
Unlicense.