How to Automate Your Own Workflows with Python and Ollama
In today’s fast-paced technical environment, it is worthwhile seeking ways to enhance efficiency and reduce time spent on repetitive tasks…
AI-POWERED PRODUCTIVITY
How to Automate Your Own Workflows with Python and Ollama
In today’s fast-paced technical environment, it is worthwhile seeking ways to enhance efficiency and reduce time spent on repetitive tasks. The integration of artificial intelligence into everyday workflows presents a compelling option, allowing for a scale of automation that was previously unimaginable. This article explores how Python combined with open-source AI framework — Ollama, can revolutionise your productivity.
Photo by Danielle Barnes on Unsplash
Before We Start
I am going to assume here you are:
- OK with using command line on the OS of your choice
- comfortable with and can make sense of Python code.
- up to speed with basic concepts of AI - specifically LLMs.
You will also need to do the following:
- Download and install Ollama (it’s available for Windows, Mac and Linux)
- Look through and familiarise yourself with the Ollama Docs. It should give you a sense of what it can do, how it works, etc.
- If not already, download and install Python.
- Create a local folder to house all the Python scripts we are going to put together. Don’t forget to create a virtual environment to isolate your package installs from the global environment. And activate your virtual environment — I’ve made that mistake far too often!
Oh and do look out for a link to the Github repo with all the code featured in this article — and some more, at the end of this article.
So What Exactly is Ollama?
Ollama is a lightweight framework that allows you to run various large language models (LLMs) locally — on your laptop/ desktop. Unlike cloud-based solutions, it gives you complete control over your data while providing powerful AI capabilities right there on your machine.

partial screenshot of the ollama.com website
This makes it ideal for anyone who needs to maintain data privacy or work in environments with limited internet connectivity. And it’s dead useful to trialling out various AI models — or even write code to use them.
Selecting the Right Model to Use with Ollama
Ollama supports various models, each with different strenghts. For example, I will be using these in this article:
- CodeLlama — good at code-related tasks like code generation and debugging
- Llama 3 — good for general text processing
The process of installing a model in Ollama is simple:
# ask ollama to run the model of your choice (see model-specific page on ollama.com)
% ollama run codellama
# if this is the first time - ollama will download it. Might take a while
pulling 3a43f93b78ec... 100% ▕███████████████████████████████████████████████████████████████████████▏ 3.8 GB
pulling 8c17c2ebb0ea... 100% ▕███████████████████████████████████████████████████████████████████████▏ 7.0 KB
pulling 590d74a5569b... 100% ▕███████████████████████████████████████████████████████████████████████▏ 4.8 KB
pulling 2e0493f67d0c... 100% ▕███████████████████████████████████████████████████████████████████████▏ 59 B
pulling 7f6a57943a88... 100% ▕███████████████████████████████████████████████████████████████████████▏ 120 B
pulling 316526ac7323... 100% ▕███████████████████████████████████████████████████████████████████████▏ 529 B
verifying sha256 digest
writing manifest
success
# if it is already deployed - you should come straight here
>>> _
# all looks good - exit
>>> /bye
Setting Up Your Environment
Before diving into automation examples, let’s prep our python environment:
# Create and activate a python virtual env
# The commands below are for the mac (pls substitute with ones for your own OS)
python -m venv .venv
source ./.venv/bin/activate
# Install required packages if not already installed
pip install requests pandas
Let’s start with a script that confirms that Ollama is installed, shows us the models it is hosting and a holds a helper function which other scripts will use to communicate with the model of their choice:
# ollama_env_setup.py
import requests
from typing import List, Optional
# Define Ollama API endpoint (default local installation)
OLLAMA_API_URL = "http://localhost:11434/api"
def check_ollama_status() -> bool:
"""Check if Ollama is running locally."""
try:
response = requests.get(f"{OLLAMA_API_URL}/tags")
return response.status_code == 200
except requests.exceptions.ConnectionError:
return False
def list_available_models() -> List[str]:
"""List all available models in the local Ollama installation."""
if not check_ollama_status():
print("Error: Ollama is not running. Please start Ollama service first.")
return []
response = requests.get(f"{OLLAMA_API_URL}/tags")
models = [model['name'] for model in response.json()['models']]
return models
def query_ollama(prompt: str, model: str = "llama3", system_prompt: Optional[str] = None) -> str:
"""Send a query to the Ollama API and return the response."""
payload = {
"model": model,
"prompt": prompt,
"stream": False
}
if system_prompt:
payload["system"] = system_prompt
response = requests.post(f"{OLLAMA_API_URL}/generate", json=payload)
if response.status_code == 200:
return response.json()["response"]
else:
return f"Error: {response.status_code}, {response.text}"
# Test the setup
if __name__ == "__main__":
if check_ollama_status():
print("Ollama service is running.")
models = list_available_models()
print(f"Available models: {', '.join(models)}")
else:
print("Ollama service is not running. Please start it with 'ollama serve'.")
The Automation Examples
Here are a few practical applications where I’ve used Ollama and Python to help enhance my productivity.
1. Automated Code Documentation
Like most people who write code, I find the task of writing and maintaining code documentation very tedious. I created a script that uses the codellama model to automatically generate comprehensive docstrings and comments for my Python code:
# ollama_document_python_code.py
from ollama_env_setup import query_ollama
def document_code(code_snippet: str, model: str = "codellama") -> str:
"""
Generate comprehensive documentation for the given code snippet.
Args:
code_snippet: The code to document
model: The Ollama model to use (preferably a code-specialized model)
Returns:
Documented code with added comments and docstrings
"""
prompt = f"""
Add comprehensive documentation to the following Python code.
Include:
- Detailed docstrings in Google format
- In-line comments for complex logic
- Type hints
- Brief explanation of the purpose of each function/class
Here's the code:
```python
{code_snippet}
Return only the documented code without any additional explanations.
"""
system_prompt = "You are an expert Python developer skilled in writing clear, comprehensive documentation."
documented_code = query_ollama(prompt, model, system_prompt)
return documented_code
Example usage
def example_documentation(): undocumented_code = """ def process_data(data, columns, filter_condition=None): df = pd.DataFrame(data) if filter_condition: df = df[df.apply(filter_condition, axis=1)] result = df[columns].to_dict('records') return result
class DataProcessor:
def __init__(self, source):
self.source = source
self.data = None
def load(self):
if self.source.endswith('.csv'):
self.data = pd.read_csv(self.source)
elif self.source.endswith('.json'):
self.data = pd.read_json(self.source)
return self
def transform(self, operations):
for op in operations:
self.data = op(self.data)
return self
"""
documented = document_code(undocumented_code)
print(documented)
Execute the example
if name == "main": example_documentation()
If you code in other languages, tweak the script and prompts accordingly. With some trials, it should be possible to create the perfect prompt for your needs.
While we are on the topic of code documentation, please also check out my article [Documentation as code: Bringing Code Documentation into the Modern Software Ecosystem](https://mskadu.medium.com/documentation-as-code-bringing-code-documentation-into-the-modern-software-ecosystem-1fa37bd4ad4b)
## 2. Email and Message Summarisation
I often receive emails, documentation, or messages that take considerable time to process. I use the `llama3` to automate summarisation. This has saved me many hours each week:
ollama_summarise_text.py
import json from typing import Any, Dict
from ollama_env_setup import query_ollama
def summarise_text(text: str, max_length: int = 150, model: str = "llama3") -> str: """ Generate a concise summary of the provided text.
Args:
text: The text to summarise
max_length: The approximate maximum length of the summary in words
model: The Ollama model to use
Returns:
A concise summary of the input text
"""
prompt = f"""
Summarise the following text in a clear, concise manner. The summary should:
- Be approximately {max_length} words or less
- Capture all key points and essential information
- Prioritise technical details and action items if present
Text to summarise:
{text}
"""
system_prompt = "You are a professional assistant who excels at extracting and condensing essential information."
summary = query_ollama(prompt, model, system_prompt)
return summary
Extended functionality to handle email summarisation specifically
def summarise_email_thread(email_thread: str) -> Dict[str, Any]: """ Analyse and summarise an email thread, extracting key information.
Args:
email_thread: The full email thread text
Returns:
Dictionary containing summary, action items, deadlines, and key points
"""
prompt = f"""
Analyse the following email thread and extract:
1. A brief summary (3-5 sentences)
2. Any action items or tasks mentioned
3. Mentioned deadlines or important dates
4. Key decisions or conclusions
Format the output as a JSON object with these keys: summary, action_items, deadlines, key_points.
Email thread:
{email_thread}
"""
system_prompt = "You are a professional email analyst. Extract only the most essential information and format exactly as requested."
result = query_ollama(prompt, "llama3", system_prompt)
# Sometimes the model might not return proper JSON, so we need to handle that
try:
return json.loads(result)
except json.JSONDecodeError:
# If JSON parsing fails, return a basic dictionary with just the summary
return {
"summary": summarise_text(email_thread),
"action_items": [],
"deadlines": [],
"key_points": []
}
## 3. Meeting Notes and Action Items Extractor
I often need to capture meeting notes and action items — in addition to the ones I record manually. This is particularly handy in making sure I’ve not missed anything important. I use `llama3` model for this:
ollama_summarise_meetings.py
import json from typing import Any, Dict
from ollama_env_setup import query_ollama from ollama_summarise_text import summarise_text
def process_meeting_transcript(transcript: str, model: str = "llama3") -> Dict[str, Any]: """ Process a meeting transcript to extract key information.
Args:
transcript: The text transcript of the meeting
model: The Ollama model to use
Returns:
Dictionary containing structured meeting information
"""
prompt = f"""
Analyse the following meeting transcript and extract:
1. A concise summary (5-7 sentences)
2. All action items with assigned owners and deadlines if specified
3. Key decisions made
4. Important discussion points
5. Follow-up questions or unresolved issues
Format the output as a JSON object with these keys: summary, action_items, decisions, discussion_points, follow_ups.
For action items, include 'task', 'owner', and 'deadline' fields for each item.
Meeting transcript:
{transcript}
"""
system_prompt = """You are an expert meeting analyst skilled at identifying and structuring key information from technical discussions.
Focus on technical details, project milestones, and specific commitments made by participants."""
result = query_ollama(prompt, model, system_prompt)
try:
return json.loads(result)
except json.JSONDecodeError:
# If JSON parsing fails, return a basic structure
return {
"summary": summarise_text(transcript, 250),
"action_items": [],
"decisions": [],
"discussion_points": [],
"follow_ups": []
}
def generate_meeting_minutes(meeting_data: Dict[str, Any]) -> str: """ Generate formatted meeting minutes from structured meeting data.
Args:
meeting_data: Dictionary containing meeting information
Returns:
Formatted meeting minutes as markdown text
"""
minutes = "# Meeting Minutes\n\n"
minutes += "## Summary\n"
minutes += meeting_data.get("summary", "No summary available") + "\n\n"
minutes += "## Key Decisions\n"
for decision in meeting_data.get("decisions", []):
minutes += f"- {decision}\n"
minutes += "\n## Action Items\n"
for item in meeting_data.get("action_items", []):
owner = item.get("owner", "Unassigned")
deadline = item.get("deadline", "No deadline")
minutes += f"- {item.get('task', 'Unnamed task')} [Owner: {owner}, Due: {deadline}]\n"
minutes += "\n## Discussion Points\n"
for point in meeting_data.get("discussion_points", []):
minutes += f"- {point}\n"
minutes += "\n## Follow-up Items\n"
for item in meeting_data.get("follow_ups", []):
minutes += f"- {item}\n"
return minutes
# Fine-tuning Your AI Assistant
While the basic integration with Ollama is powerful, I’ve found you can enhance your productivity system even further by customising the prompts, system messages, and models used.
## Select the Right Model
In addition to the models used in the above scripts, I’ve also been toying about with the following to explore their strengths and compare them against the ones I already use:
1. [Mistral](https://ollama.com/library/mistral) — useful for many tasks with low resource requirements
2. [Vicuna](https://ollama.com/library/vicuna) — ideal when you have finely detailed requirements
Review available models carefully. Evaluate their documented features, parameters, sizes and any alternatives — this is the hard bit which requires a fair bit of research and trial efforts.
I also suggest keeping an eye on [models supported by Ollama](https://ollama.com/search) and narrowing down on ones that fits your use case. A key consideration is the balance between performance and resource usage.
## Creating Role-Specific System Prompts
For more specialised tasks, I’ve crafted system prompts that provide domain (or *Role*) context:
For software development
DEV_PROMPT = """You are an expert software engineer who follows best practices in code organisation, documentation, and testing. Focus on maintainability, performance, and security."""
Meeting notes taker
MEETING_ANALYST_PROMPT = """You are an expert meeting analyst skilled at identifying and structuring key information from technical discussions. Focus on technical details, project milestones, and specific commitments made by participants."""
# Ethical Considerations and Best Practices
When implementing AI-powered automation, I’ve found it important to consider the folllowing factors:
1. **Data Privacy**: Though Ollama runs locally, *be mindful of sensitive data in prompts*
2. **AI Limitations**: Verify critical outputs, especially for complex analysis
3. **Continuous Learning**: Regularly update your models and approaches
# Summary
The combination of Python and Ollama has offered me a powerful combination for automating my workflows and enhancing productivity. By using these tools strategically, I’ve managed to free myself from repetitive tasks and focus on high-value work.
It is important to note that the scripts in this article are illustrative and are best used as starting points. As you become more comfortable with these techniques, you can extend and customise them to fit your specific needs. This is the best way to go about creating a personalised AI-powered productivity system that evolves with your needs.
# Next Steps
If I have managed to get you excited and itching to get started, feel free to use [this Github repo](https://github.com/mskadu/ollama-proof-of-concepts) with a copy of all of the code discussed above as a starting point. And tinker away!
See something missing, mistakes or an improvement? Drop a comment and let me know.
# Thank you for being a part of the community
*Before you go:*
- Be sure to **clap** and **follow** the writer ️👏**️️**
- Follow us: [**X](https://x.com/inPlainEngHQ)** | [**LinkedIn](https://www.linkedin.com/company/inplainenglish/)** | [**YouTube](https://www.youtube.com/@InPlainEnglish)** | [**Newsletter](https://newsletter.plainenglish.io/)** | [**Podcast](https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0)** | [**Twitch](https://twitch.tv/inplainenglish)**
- [**Start your own free AI-powered blog on Differ](https://differ.blog/)** 🚀
- [**Join our content creators community on Discord](https://discord.gg/in-plain-english-709094664682340443)** 🧑🏻💻
- For more content, visit [**plainenglish.io](https://plainenglish.io/)** + [**stackademic.com](https://stackademic.com/)** 메타데이터
- post_id
- 1e0ddda08fa3
- slug
- how-to-automate-your-workflows-with-python-and-ollama-1e0ddda08fa3
- url
- https://python.plainenglish.io/how-to-automate-your-workflows-with-python-and-ollama-1e0ddda08fa3
- canonical_url
- https://python.plainenglish.io/how-to-automate-your-workflows-with-python-and-ollama-1e0ddda08fa3
- author_url
- https://medium.com/@mskadu
- status
- ok
- fetched_at
- 2026-06-24 11:06:28