Author SHA1 Message Date
armistace e8040e2ba8 unleash client 2025-09-17 09:25:55 +10:00
armistace f2b95935bb Prompt enhancement to produce content
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Successful in 5m14s
2025-06-24 13:05:15 +10:00
armistace bce439921f Generate tags around context
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Successful in 22m46s
2025-06-16 10:35:21 +10:00
armistace 2de2d0fe3a Merge pull request 'prompt enhancement' (#16) from prompt_fix into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Successful in 11m44s
Reviewed-on: #16
2025-06-06 12:04:44 +10:00
armistace cf795bbc35 prompt enhancement 2025-06-06 12:04:19 +10:00
armistace a6ed20451a Merge pull request 'pipeline_creation' (#15) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Successful in 25m13s
Reviewed-on: #15
2025-06-05 09:22:50 +10:00
armistace 7fd32b3024 improve notification prompt 2025-06-05 09:22:28 +10:00
armistace a88d233c6b remove tail and improve notification prompt 2025-06-05 09:22:19 +10:00
armistace 2abc39e3ac Merge pull request 'pipeline_creation' (#14) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Successful in 30m33s
Reviewed-on: #14
2025-06-05 08:43:23 +10:00
armistace f430998137 typo 2025-06-05 08:42:45 +10:00
armistace 8dceb79d91 remove repo reference 2025-06-05 08:41:32 +10:00
armistace 6c5b0f778d remove trailing slash 2025-06-05 08:41:32 +10:00
armistace 37ed8fd0f9 fix git for pipeline" 2025-06-05 08:40:59 +10:00
armistace 0594ea54aa remove repo reference
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 27m5s
2025-06-05 01:02:42 +10:00
armistace 60f7473297 remove trailing slash
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Has been cancelled
2025-06-05 01:00:58 +10:00
armistace ec69e8e4f7 Merge pull request 'do it right' (#13) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 8m58s
Reviewed-on: #13
2025-06-05 00:47:05 +10:00
armistace 62b1175aeb do it right 2025-06-05 00:46:45 +10:00
armistace 41f804a1eb Merge pull request 'pipeline_creation' (#12) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Has been cancelled
Reviewed-on: #12
2025-06-05 00:45:53 +10:00
armistace f50d076164 cleanup 2025-06-05 00:45:39 +10:00
armistace fc4f9c5053 dealing with pipeline weirdness 2025-06-05 00:44:57 +10:00
armistace e3262cd366 Merge pull request 'weird trailing newline"' (#11) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 10m26s
Reviewed-on: #11
2025-06-05 00:12:04 +10:00
armistace 341f3d8623 weird trailing newline"
"
2025-06-05 00:11:44 +10:00
armistace e2c29204fa Merge pull request 'pipeline_creation' (#10) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Has been cancelled
Reviewed-on: #10
2025-06-04 23:48:10 +10:00
armistace f0e6a0cb52 load_dotenv work different? 2025-06-04 23:47:53 +10:00
armistace 7f0b0376d1 load_dotenv work different? 2025-06-04 23:47:05 +10:00
armistace 44b5ea6a68 Merge pull request 'load_dotenv work different?' (#9) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 9m17s
Reviewed-on: #9
2025-06-04 22:55:26 +10:00
armistace a49457094d load_dotenv work different? 2025-06-04 22:54:09 +10:00
armistace 9296fda390 Merge pull request 'tail the .env so we can see it in pipelin' (#8) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 9m5s
Reviewed-on: #8
2025-06-04 22:44:14 +10:00
armistace bb0d9090f3 tail the .env so we can see it in pipelin 2025-06-04 22:43:53 +10:00
armistace 703a2384e7 Merge pull request 'sigh stray U' (#7) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 9m2s
Reviewed-on: #7
2025-06-04 22:30:36 +10:00
armistace 4b3f00c325 Merge branch 'master' into pipeline_creation 2025-06-04 22:29:42 +10:00
armistace 38dfe404d1 sigh stray U 2025-06-04 22:29:12 +10:00
armistace 347ac63f86 Merge pull request 'helps to install virtualenv' (#6) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 8m59s
Reviewed-on: #6
2025-06-04 22:17:46 +10:00
armistace 506758f67d helps to install virtualenv 2025-06-04 22:17:11 +10:00
armistace f0572ba9fb Merge pull request 'pipeline_creation' (#5) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 7m5s
Reviewed-on: #5
2025-06-04 22:08:28 +10:00
armistace 4686f3fae0 y in right place 2025-06-04 22:07:47 +10:00
armistace ea1c8cfb13 add y to apt call 2025-06-04 22:07:15 +10:00
armistace 9ca7578d28 Merge pull request 'pipeline_creation' (#4) from pipeline_creation into master
Create Blog Article if new notes exist / prepare_blog_drafts_and_push (push) Failing after 4m28s
Reviewed-on: #4
2025-06-04 22:02:00 +10:00
armistace 64b466c4ac load dotenv in main.py 2025-06-04 22:01:15 +10:00
armistace 49174de9ff correct pipeline titles 2025-06-04 21:59:33 +10:00
armistace 59f9f01c69 first cut at pipeline 2025-06-04 21:48:59 +10:00
armistace a7eae4b09f Merge pull request 'matrix_notifications' (#3) from matrix_notifications into master
Reviewed-on: #3
2025-06-04 21:34:12 +10:00
armistace c466b04a25 matrix notifications and config driven chroma 2025-06-04 21:32:51 +10:00
armistace 431e5c63aa first pass at docker run 2025-06-04 16:56:08 +10:00
armistace 6e117e3ce9 language cleanup for integration testing 2025-06-02 12:32:21 +10:00
armistace 9a9228bc07 Merge pull request 'repo_work_fix' (#2) from repo_work_fix into master
Reviewed-on: #2
2025-05-30 17:47:31 +10:00
armistace 2dd371408f trying for the hard fix 2025-05-30 17:25:13 +10:00
armistace 0005ad1fd3 hard reset for the repo work 2025-05-30 17:20:58 +10:00
armistace 446978704d further directory cleanup 2025-01-24 04:51:50 +00:00
armistace f24bd5b361 cleanup directory 2025-01-24 04:44:23 +00:00
armistace 4d5c27cfaa clean up 2025-01-24 04:42:04 +00:00
armistace d45f0be314 env set up for remote 2025-01-24 04:41:14 +00:00
armistace e1a24aff20 get rid of think tags 2025-01-24 02:17:05 +00:00
18 changed files with 406 additions and 260 deletions
+56
View File
@@ -0,0 +1,56 @@
name: Create Blog Article if new notes exist
on:
schedule:
- cron: "15 3 * * *"
push:
branches:
- master
jobs:
prepare_blog_drafts_and_push:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies
shell: bash
run: |
apt update && apt upgrade -y
apt install rustc cargo python-is-python3 pip python3-venv python3-virtualenv libmagic-dev git -y
virtualenv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
git config --global user.name "Blog Creator"
git config --global user.email "ridgway.infrastructure@gmail.com"
git config --global push.autoSetupRemote true
- name: Create .env
shell: bash
run: |
echo "TRILIUM_HOST=${{ vars.TRILIUM_HOST }}" > .env
echo "TRILIUM_PORT='${{ vars.TRILIUM_PORT }}'" >> .env
echo "TRILIUM_PROTOCOL='${{ vars.TRILIUM_PROTOCOL }}'" >> .env
echo "TRILIUM_PASS='${{ secrets.TRILIUM_PASS }}'" >> .env
echo "TRILIUM_TOKEN='${{ secrets.TRILIUM_TOKEN }}'" >> .env
echo "OLLAMA_PROTOCOL='${{ vars.OLLAMA_PROTOCOL }}'" >> .env
echo "OLLAMA_HOST='${{ vars.OLLAMA_HOST }}'" >> .env
echo "OLLAMA_PORT='${{ vars.OLLAMA_PORT }}'" >> .env
echo "EMBEDDING_MODEL='${{ vars.EMBEDDING_MODEL }}'" >> .env
echo "EDITOR_MODEL='${{ vars.EDITOR_MODEL }}'" >> .env
export PURE='["${{ vars.CONTENT_CREATOR_MODELS_1 }}", "${{ vars.CONTENT_CREATOR_MODELS_2 }}", "${{ vars.CONTENT_CREATOR_MODELS_3 }}", "${{ vars.CONTENT_CREATOR_MODELS_4 }}"]'
echo "CONTENT_CREATOR_MODELS='$PURE'" >> .env
echo "GIT_PROTOCOL='${{ vars.GIT_PROTOCOL }}'" >> .env
echo "GIT_REMOTE='${{ vars.GIT_REMOTE }}'" >> .env
echo "GIT_USER='${{ vars.GIT_USER }}'" >> .env
echo "GIT_PASS='${{ secrets.GIT_PASS }}'" >> .env
echo "N8N_SECRET='${{ secrets.N8N_SECRET }}'" >> .env
echo "N8N_WEBHOOK_URL='${{ vars.N8N_WEBHOOK_URL }}'" >> .env
echo "CHROMA_HOST='${{ vars.CHROMA_HOST }}'" >> .env
echo "CHROMA_PORT='${{ vars.CHROMA_PORT }}'" >> .env
- name: Create Blogs
shell: bash
run: |
source .venv/bin/activate
python src/main.py
+5
View File
@@ -3,3 +3,8 @@ __pycache__
.venv .venv
.aider* .aider*
.vscode .vscode
.zed
pyproject.toml
.ropeproject
generated_files/*
pyright*
+6 -2
View File
@@ -7,8 +7,12 @@ ENV PYTHONUNBUFFERED 1
ADD src/ /blog_creator ADD src/ /blog_creator
RUN apt-get update && apt-get install -y rustc cargo python-is-python3 pip python3-venv libmagic-dev RUN apt-get update && apt-get install -y rustc cargo python-is-python3 pip python3-venv libmagic-dev git
# Need to set up git here or we get funky errors
RUN git config --global user.name "Blog Creator"
RUN git config --global user.email "ridgway.infrastructure@gmail.com"
RUN git config --global push.autoSetupRemote true
#Get a python venv going as well cause safety
RUN python -m venv /opt/venv RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" ENV PATH="/opt/venv/bin:$PATH"
+13 -4
View File
@@ -3,10 +3,19 @@
This creator requires you to use a working Trilium Instance and create a .env file with the following This creator requires you to use a working Trilium Instance and create a .env file with the following
``` ```
TRILIUM_HOST TRILIUM_HOST=
TRILIUM_PORT TRILIUM_PORT=
TRILIUM_PROTOCOL TRILIUM_PROTOCOL=
TRILIUM_PASS TRILIUM_PASS=
TRILIUM_TOKEN=
OLLAMA_PROTOCOL=
OLLAMA_HOST=
OLLAMA_PORT=11434
EMBEDDING_MODEL=
EDITOR_MODEL=
# This is expected in python list format example `[phi4-mini:latest, qwen3:1.7b, gemma3:latest]`
CONTENT_CREATOR_MODELS=
CHROMA_SERVER=<IP_ADDRESS>
``` ```
This container is going to be what I use to trigger a blog creation event This container is going to be what I use to trigger a blog creation event
+3 -12
View File
@@ -23,25 +23,16 @@ services:
# Default configuration for persist_directory in chromadb/config.py # Default configuration for persist_directory in chromadb/config.py
# Read more about deployments: https://docs.trychroma.com/deployment # Read more about deployments: https://docs.trychroma.com/deployment
- chroma-data:/chroma/chroma - chroma-data:/chroma/chroma
command: "--workers 1 --host 0.0.0.0 --port 8000 --proxy-headers --log-config chromadb/log_config.yml --timeout-keep-alive 30" #command: "--host 0.0.0.0 --port 8000 --proxy-headers --log-config chromadb/log_config.yml --timeout-keep-alive 30"
environment: environment:
- IS_PERSISTENT=TRUE - IS_PERSISTENT=TRUE
- CHROMA_SERVER_AUTHN_PROVIDER=${CHROMA_SERVER_AUTHN_PROVIDER}
- CHROMA_SERVER_AUTHN_CREDENTIALS_FILE=${CHROMA_SERVER_AUTHN_CREDENTIALS_FILE}
- CHROMA_SERVER_AUTHN_CREDENTIALS=${CHROMA_SERVER_AUTHN_CREDENTIALS}
- CHROMA_AUTH_TOKEN_TRANSPORT_HEADER=${CHROMA_AUTH_TOKEN_TRANSPORT_HEADER}
- PERSIST_DIRECTORY=${PERSIST_DIRECTORY:-/chroma/chroma}
- CHROMA_OTEL_EXPORTER_ENDPOINT=${CHROMA_OTEL_EXPORTER_ENDPOINT}
- CHROMA_OTEL_EXPORTER_HEADERS=${CHROMA_OTEL_EXPORTER_HEADERS}
- CHROMA_OTEL_SERVICE_NAME=${CHROMA_OTEL_SERVICE_NAME}
- CHROMA_OTEL_GRANULARITY=${CHROMA_OTEL_GRANULARITY}
- CHROMA_SERVER_NOFILE=${CHROMA_SERVER_NOFILE}
restart: unless-stopped # possible values are: "no", always", "on-failure", "unless-stopped" restart: unless-stopped # possible values are: "no", always", "on-failure", "unless-stopped"
ports: ports:
- "8000:8000" - "8000:8000"
healthcheck: healthcheck:
# Adjust below to match your container port # Adjust below to match your container port
test: [ "CMD", "curl", "-f", "http://localhost:8000/api/v2/heartbeat" ] test:
["CMD", "curl", "-f", "http://localhost:8000/api/v2/heartbeat"]
interval: 30s interval: 30s
timeout: 10s timeout: 10s
retries: 3 retries: 3
+2
View File
@@ -0,0 +1,2 @@
*
!.gitignore
@@ -1,29 +0,0 @@
```markdown
# Creating an Ollama Blog Writer: A Hilariously Tedious Adventure
Hey tech enthusiasts! 👋 I’m back with another installment of my tech journey, but this time it’s personal. I decided to create a Python script that not only writes blogs for me (please don’t tell my boss), but also uses Ollama for some AI-assisted content creation and connects with Trilium for structured note-taking. Let’s dive into the details!
### Step 1: Get Your Ollama On
First things first, I needed a Python file that could talk to my local Ollama instance. If you haven't heard of Ollama, it's like a tiny llama in your terminal that helps with text generation. It took me a while to figure out how to configure the `.env` file and set up the connection properly. But once I did, I was off to a running start!
### Step 2: Connecting Trilium for Structured Notes
For this part, I used a Python library called `trilium-py` (because why not?). It's like having a brain that can store and retrieve information in an organized way. To make sure my notes are super structured, I had to find the right prompts and ensure they were fed into Ollama correctly. This part was more about figuring out how to structure the data than actually coding—but hey, it’s all part of the fun!
### Step 3: Automating the Blog Creation
Now that I have my notes and AI-generated content sorted, it was time to automate the blog creation process. Here’s where things got a bit Git-y (yes, I made up that word). I wrote a script that would create a new branch in our company's blog repo, push the changes, and voilà—a PR! Just like that, my humble contributions were ready for review by the big boss.
### Step 4: Sending Notifications to Matrix
Finally, as any good DevRel should do, I sent out a notification to our internal Matrix channel. It’s like Slack but with more tech talk and less memes about dogs in hats. The message was short and sweet—just a summary of the blog changes and a request for feedback. Hey, if Elon can tweet at Tesla shareholders, why not send a quick matrix message?
### Wrapping Up
Creating this Ollama Blog Writer wasn’t just about writing better blogs (though that would be nice). It was about embracing the joy of automation and the occasional struggle to get things working right. I learned a lot about Python libraries, local server configurations, and how to communicate effectively with my team via Matrix.
So there you have it—a step-by-step guide on how not to write blogs but definitely how to automate the process. If you’re into tech, automation, or just want to laugh at someone else’s coding mishaps, this blog is for you!
Keep on hacking (and automating), [Your Name]
```
@@ -1,23 +0,0 @@
Title: When Data Visualization Meets Frustration: A Comic Take on PowerBI's API Woes
---
In the ever-evolving world of data and tech, few tools hold as much promise—or frustration—as Microsoft's PowerBI. Its sleek interface, intuitive visuals, and promise to simplify data into digestible insights have made it a favorite among many. But beneath its polished surface lies a storm of challenges that can leave even the most seasoned developers in its dust.
Imagine this: you've spent hours refining your data model, only to find that your team's hierarchy resists your attempt to share sensitive information without breaking hearts. "We're all on different tiers," you mutter, your frustration evident. But here's the kicker—PowerBI won't even let everyone in your company join the party if they're not up to tier 5. And guess what? Most companies operate in reality tier 3 at best. So, step one: API calls to PowerBI. You'd think pulling data would be straightforward, but oh, how it pulls you into a tailspin.
Here's where things get interesting: PowerBI APIs are mostly limited to small tables. It's like trying to fit furniture through a door that's slightly too narrow—it just doesn't work unless you have a magic wand (or in this case, an API upgrade). Imagine needing to fetch data from three different on-premises databases seamlessly; PowerBI might just give you the finger.
Now, if your company happens to be in the Microsoft ecosystem—like the Azure universe—then maybe things are a bit easier. But here's the kicker: it's not being top-to-bottom within that ecosystem that counts as success. If even one part is outside, you're facing performance issues akin to driving through a snowstorm without an umbrella. You get the picture.
So what does this mean for the average user? Unless you've got no choice but to use PowerBI... well, let's just say it might not be your friend in such scenarios. It's like having a GPS that only works if you're willing to drive on a dirt road and expect it to guide you through with zero warnings—sounds great until you end up stranded.
But wait, maybe there's silver lining. Other tools have learned the hard lessons PowerBI has taught us. They allow APIs beyond just small tables and handle ecosystems with ease, making them more versatile for real-world applications. It's like upgrading your car's GPS to one that not only knows all the roads but also can navigate through different weather conditions without complaints.
In conclusion, while PowerBI is undeniably a powerful tool when used correctly—like driving in calm weather on perfectly paved roads—it has its limitations. Its API restrictions and ecosystem integration issues make it less than ideal for many real-world scenarios. So unless you're in a controlled environment where these issues don't arise, maybe it's time to explore other options that can handle the data journey with more grace.
After all, Data Overload isn't just a Star Trek term—it could be your reality if you're not careful with PowerBI.
---
*So, is PowerBI still your best friend in this complex tech world? Or are there better tools out there waiting to be discovered? Share your thoughts and experiences below!*
@@ -1,35 +0,0 @@
# Wrangling Data: A Reality Check
Okay, let’s be honest. Data wrangling isn't glamorous. It’s not a sleek, automated process of magically transforming chaos into insights. It’s a messy, frustrating, and surprisingly human endeavor. Let’s break down the usual suspects – the steps we take to get even a vaguely useful dataset, and why they’re often a monumental task.
**Phase 1: The Hunt**
First, you’re handed a dataset. Let’s call it “Customer_Data_v2”. It’s… somewhere. Maybe a CSV file, maybe a database table, maybe a collection of spreadsheets that haven’t been updated since 2008. Finding it is half the battle. It's like searching for a decent cup of coffee in Melbourne – you know it’s out there, but it’s often hidden behind a wall of bureaucracy.
**Phase 2: Deciphering the Ancient Texts**
Once you *find* it, you start learning what it *means*. This is where things get… interesting. You’re trying to understand what fields represent, what units of measurement are used, and why certain columns have bizarre names (seriously, “Customer_ID_v3”?). It takes x amount of time (depends on the industry, right?). One week for a small bakery, six months for a multinational insurance company. It’s a wild ride.
You’ll spend a lot of time trying to understand the business context. "CRMs" for Customer Relationship Management? Seriously? It’s a constant stream of jargon and acronyms that make your head spin.
**Phase 3: The Schema Struggle**
Then there’s the schema. Oh, the schema. It takes a couple of weeks to learn the schema. It’s like deciphering ancient hieroglyphics, except instead of predicting the rise and fall of empires, you’re trying to understand why a field called “Customer_ID_v3” exists. It’s a puzzle, and a frustrating one at that.
**Phase 4: The Tooling Tango**
You’ll wrestle with the tools. SQL interpreters, data transformation software – they’re all there, but they’re often clunky, outdated, and require a surprising amount of manual effort. It's like finding a decent cup of coffee in Melbourne – you know it’s out there, but it’s often hidden behind a wall of bureaucracy.
**Phase 5: The Reporting Revelation (and Despair)**
Finally, you get to the reporting tool. And cry. Seriously, who actually *likes* this part? It’s a soul-crushing exercise in formatting and filtering, and the output is usually something that nobody actually reads.
**The AI Factor – A Realistic Perspective**
Now, everyone’s talking about AI. And, look, I’m not saying AI is a bad thing. It’s got potential. But let’s be realistic. This will for quite some time be the point where we need people. AI can automate the process of extracting data from a spreadsheet. But it can’t understand *why* that spreadsheet was created in the first place. It can’t understand the context, the assumptions, the biases. It can’t tell you if the data is actually useful.
We can use tools like datahub to capture some of this business knowledge but those tool are only as good as the people who use them. We need to make sure AI is used for those uniform parts – schema discovery, finding the tools, ugh reporting. But where the rubber hits the road… thats where we need people and that we are making sure that there is a person interpreting not only what goes out.. but what goes in.
**The Bottom Line**
It’s a bit like trying to build a great BBQ. You can buy the fanciest gadgets and the most expensive wood, but if you don’t know how to cook, you’re going to end up with a burnt mess. So, let’s not get carried away with the hype. Let’s focus on building a data culture that values human intelligence, critical thinking, and a good dose of common sense. And let’s keep wrangling. Because, let’s be honest, someone’s gotta do it.
+3
View File
@@ -4,3 +4,6 @@ gitpython
PyGithub PyGithub
chromadb chromadb
langchain-ollama langchain-ollama
PyJWT
dotenv
UnleashClient
+53 -21
View File
@@ -1,31 +1,39 @@
import os, re import os, re, json, random, time, string
from ollama import Client from ollama import Client
import chromadb, time import chromadb
from langchain_ollama import ChatOllama from langchain_ollama import ChatOllama
class OllamaGenerator: class OllamaGenerator:
def __init__(self, title: str, content: str, model: str, inner_title: str): def __init__(self, title: str, content: str, inner_title: str):
self.title = title self.title = title
self.inner_title = inner_title self.inner_title = inner_title
self.content = content self.content = content
self.chroma = chromadb.HttpClient(host="172.18.0.2", port=8000) self.response = None
print("In Class")
print(os.environ["CONTENT_CREATOR_MODELS"])
try:
chroma_port = int(os.environ['CHROMA_PORT'])
except ValueError as e:
raise Exception(f"CHROMA_PORT is not an integer: {e}")
self.chroma = chromadb.HttpClient(host=os.environ['CHROMA_HOST'], port=chroma_port)
ollama_url = f"{os.environ["OLLAMA_PROTOCOL"]}://{os.environ["OLLAMA_HOST"]}:{os.environ["OLLAMA_PORT"]}" ollama_url = f"{os.environ["OLLAMA_PROTOCOL"]}://{os.environ["OLLAMA_HOST"]}:{os.environ["OLLAMA_PORT"]}"
self.ollama_client = Client(host=ollama_url) self.ollama_client = Client(host=ollama_url)
self.ollama_model = model self.ollama_model = os.environ["EDITOR_MODEL"]
self.embed_model = "snowflake-arctic-embed2:latest" self.embed_model = os.environ["EMBEDDING_MODEL"]
self.agent_models = ["openthinker:7b", "deepseek-r1:7b", "qwen2.5:7b", "gemma3:latest"] self.agent_models = json.loads(os.environ["CONTENT_CREATOR_MODELS"])
self.llm = ChatOllama(model=self.ollama_model, temperature=0.7) self.llm = ChatOllama(model=self.ollama_model, temperature=0.6, top_p=0.5) #This is the level head in the room
self.prompt_inject = f""" self.prompt_inject = f"""
You are a journalist, Software Developer and DevOps expert You are a journalist, Software Developer and DevOps expert
writing a 1000 word draft blog for other tech enthusiasts. writing a 3000 word draft blog article for other tech enthusiasts.
You like to use almost no code examples and prefer to talk You like to use almost no code examples and prefer to talk
in a light comedic tone. You are also Australian in a light comedic tone. You are also Australian
As this person write this blog as a markdown document. As this person write this blog as a markdown document.
The title for the blog is {self.inner_title}. The title for the blog is {self.inner_title}.
Do not output the title in the markdown. Do not output the title in the markdown.
The basis for the content of the blog is: The basis for the content of the blog is:
{self.content} <blog>{self.content}</blog>
""" """
def split_into_chunks(self, text, chunk_size=100): def split_into_chunks(self, text, chunk_size=100):
@@ -53,12 +61,20 @@ class OllamaGenerator:
def generate_draft(self, model) -> str: def generate_draft(self, model) -> str:
'''Generate a draft blog post using the specified model''' '''Generate a draft blog post using the specified model'''
try: try:
agent_llm = ChatOllama(model=model, temperature=0.8) # the idea behind this is to make the "creativity" random amongst the content creators
# contorlling temperature will allow cause the output to allow more "random" connections in sentences
# Controlling top_p will tighten or loosen the embedding connections made
# The result should be varied levels of "creativity" in the writing of the drafts
# for more see https://python.langchain.com/v0.2/api_reference/ollama/chat_models/langchain_ollama.chat_models.ChatOllama.html
temp = random.uniform(0.5, 1.0)
top_p = random.uniform(0.4, 0.8)
top_k = int(random.uniform(30, 80))
agent_llm = ChatOllama(model=model, temperature=temp, top_p=top_p, top_k=top_k)
messages = [ messages = [
("system", self.prompt_inject), ("system", self.prompt_inject),
("human", "make the blog post in a format to be edited easily" ) ("human", "make the blog post in a format to be edited easily" )
] ]
self.response = agent_llm.invoke(messages) response = agent_llm.invoke(messages)
# self.response = self.ollama_client.chat(model=model, # self.response = self.ollama_client.chat(model=model,
# messages=[ # messages=[
# { # {
@@ -66,7 +82,9 @@ class OllamaGenerator:
# 'content': f'{self.prompt_inject}', # 'content': f'{self.prompt_inject}',
# }, # },
# ]) # ])
return self.response.text()#['message']['content'] #print ("draft")
#print (response)
return response.text()#['message']['content']
except Exception as e: except Exception as e:
raise Exception(f"Failed to generate blog draft: {e}") raise Exception(f"Failed to generate blog draft: {e}")
@@ -76,11 +94,13 @@ class OllamaGenerator:
embeds = self.ollama_client.embed(model=self.embed_model, input=draft_chunks) embeds = self.ollama_client.embed(model=self.embed_model, input=draft_chunks)
return embeds.get('embeddings', []) return embeds.get('embeddings', [])
def id_generator(self, size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def load_to_vector_db(self): def load_to_vector_db(self):
'''Load the generated blog drafts into a vector database''' '''Load the generated blog drafts into a vector database'''
collection_name = f"blog_{self.title.lower().replace(" ", "_")}" collection_name = f"blog_{self.title.lower().replace(" ", "_")}_{self.id_generator()}"
collection = self.chroma.get_or_create_collection(name=collection_name, metadata={"hnsw:space": "cosine"}) collection = self.chroma.get_or_create_collection(name=collection_name)#, metadata={"hnsw:space": "cosine"})
#if any(collection.name == collectionname for collectionname in self.chroma.list_collections()): #if any(collection.name == collectionname for collectionname in self.chroma.list_collections()):
# self.chroma.delete_collection("blog_creator") # self.chroma.delete_collection("blog_creator")
for model in self.agent_models: for model in self.agent_models:
@@ -102,14 +122,16 @@ class OllamaGenerator:
prompt_system = f""" prompt_system = f"""
You are an editor taking information from {len(self.agent_models)} Software You are an editor taking information from {len(self.agent_models)} Software
Developers and Data experts Developers and Data experts
writing a 3000 word blog for other tech enthusiasts. writing a 3000 word blog article. You like when they use almost no code examples.
You like when they use almost no code examples and the You are also Australian. The content may have light comedic elements,
voice is in a light comedic tone. You are also Australian you are more professional and will attempt to tone these down
As this person produce and an amalgamtion of this blog as a markdown document. As this person produce the final version of this blog as a markdown document
keeping in mind the context provided by the previous drafts.
You are to produce the content not placeholders for further editors
The title for the blog is {self.inner_title}. The title for the blog is {self.inner_title}.
Do not output the title in the markdown. Avoid repeated sentences Do not output the title in the markdown. Avoid repeated sentences
The basis for the content of the blog is: The basis for the content of the blog is:
{self.content} <blog>{self.content}</blog>
""" """
try: try:
query_embed = self.ollama_client.embed(model=self.embed_model, input=prompt_system)['embeddings'] query_embed = self.ollama_client.embed(model=self.embed_model, input=prompt_system)['embeddings']
@@ -117,7 +139,10 @@ class OllamaGenerator:
collection_query = collection.query(query_embeddings=query_embed, n_results=100) collection_query = collection.query(query_embeddings=query_embed, n_results=100)
print("Showing pertinent info from drafts used in final edited edition") print("Showing pertinent info from drafts used in final edited edition")
pertinent_draft_info = '\n\n'.join(collection.query(query_embeddings=query_embed, n_results=100)['documents'][0]) pertinent_draft_info = '\n\n'.join(collection.query(query_embeddings=query_embed, n_results=100)['documents'][0])
prompt_human = f"Generate the final document using this information from the drafts: {pertinent_draft_info} - ONLY OUTPUT THE MARKDOWN" #print(pertinent_draft_info)
prompt_human = f"""Generate the final, 3000 word, draft of the blog using this information from the drafts: <context>{pertinent_draft_info}</context>
- Only output in markdown, do not wrap in markdown tags, Only provide the draft not a commentary on the drafts in the context
"""
print("Generating final document") print("Generating final document")
messages = [("system", prompt_system), ("human", prompt_human),] messages = [("system", prompt_system), ("human", prompt_human),]
self.response = self.llm.invoke(messages).text() self.response = self.llm.invoke(messages).text()
@@ -128,6 +153,8 @@ class OllamaGenerator:
# 'content': f'{prompt_enhanced}', # 'content': f'{prompt_enhanced}',
# }, # },
# ]) # ])
#print ("Markdown Generated")
#print (self.response)
return self.response#['message']['content'] return self.response#['message']['content']
except Exception as e: except Exception as e:
@@ -136,3 +163,8 @@ class OllamaGenerator:
def save_to_file(self, filename: str) -> None: def save_to_file(self, filename: str) -> None:
with open(filename, "w") as f: with open(filename, "w") as f:
f.write(self.generate_markdown()) f.write(self.generate_markdown())
def generate_system_message(self, prompt_system, prompt_human):
messages = [("system", prompt_system), ("human", prompt_human),]
ai_message = self.llm.invoke(messages).text()
return ai_message
+56 -3
View File
@@ -1,6 +1,13 @@
import ai_generators.ollama_md_generator as omg import ai_generators.ollama_md_generator as omg
import trilium.notes as tn import trilium.notes as tn
import string import repo_management.repo_manager as git_repo
from notifications.n8n import N8NWebhookJwt
import string,os
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
print(os.environ["CONTENT_CREATOR_MODELS"])
tril = tn.TrilumNotes() tril = tn.TrilumNotes()
@@ -22,6 +29,52 @@ for note in tril_notes:
os_friendly_title = convert_to_lowercase_with_underscores(tril_notes[note]['title']) os_friendly_title = convert_to_lowercase_with_underscores(tril_notes[note]['title'])
ai_gen = omg.OllamaGenerator(os_friendly_title, ai_gen = omg.OllamaGenerator(os_friendly_title,
tril_notes[note]['content'], tril_notes[note]['content'],
"gemma3:latest",
tril_notes[note]['title']) tril_notes[note]['title'])
ai_gen.save_to_file(f"/blog_creator/generated_files/{os_friendly_title}.md") blog_path = f"generated_files/{os_friendly_title}.md"
ai_gen.save_to_file(blog_path)
# Generate commit messages and push to repo
print("Generating Commit Message")
git_sytem_prompt = "You are a blog creator commiting a piece of content to a central git repo"
git_human_prompt = f"Generate a 5 word git commit message describing {ai_gen.response}. ONLY OUTPUT THE RESPONSE"
commit_message = ai_gen.generate_system_message(git_sytem_prompt, git_human_prompt)
git_user = os.environ["GIT_USER"]
git_pass = os.environ["GIT_PASS"]
repo_manager = git_repo.GitRepository("blog/", git_user, git_pass)
print("Pushing to Repo")
repo_manager.create_copy_commit_push(blog_path, os_friendly_title, commit_message)
# Generate notification for Matrix
print("Generating Notification Message")
git_branch_url = f'https://git.aridgwayweb.com/armistace/blog/src/branch/{os_friendly_title}/src/content/{os_friendly_title}.md'
n8n_system_prompt = f"You are a blog creator notifiying the final editor of the final creation of blog available at {git_branch_url}"
n8n_prompt_human = f"""
Generate an informal 100 word
summary describing {ai_gen.response}.
Don't address it or use names. ONLY OUTPUT THE RESPONSE.
ONLY OUTPUT IN PLAINTEXT STRIP ALL MARKDOWN
"""
notification_message = ai_gen.generate_system_message(n8n_system_prompt, n8n_prompt_human)
secret_key = os.environ['N8N_SECRET']
webhook_url = os.environ['N8N_WEBHOOK_URL']
notification_string = f"""
<h2>{tril_notes[note]['title']}</h2>
<h3>Summary</h3>
<p>{notification_message}</p>
<h3>Branch</h3>
<p>{os_friendly_title}</p>
<p><a href="{git_branch_url}">Link to Branch</a></p>
"""
payload = {
"message": f"{notification_string}",
"timestamp": datetime.now().isoformat()
}
webhook_client = N8NWebhookJwt(secret_key, webhook_url)
print("Notifying")
n8n_result = webhook_client.send_webhook(payload)
print(f"N8N response: {n8n_result['status']}")
+45
View File
@@ -0,0 +1,45 @@
from datetime import datetime, timedelta
import jwt
import requests
from typing import Dict, Optional
class N8NWebhookJwt:
def __init__(self, secret_key: str, webhook_url: str):
self.secret_key = secret_key
self.webhook_url = webhook_url
self.token_expiration = datetime.now() + timedelta(hours=1)
def _generate_jwt_token(self, payload: Dict) -> str:
"""Generate JWT token with the given payload."""
# Include expiration time (optional)
payload["exp"] = self.token_expiration.timestamp()
encoded_jwt = jwt.encode(
payload,
self.secret_key,
algorithm="HS256",
)
return encoded_jwt #jwt.decode(encoded_jwt, self.secret_key, algorithms=['HS256'])
def send_webhook(self, payload: Dict) -> Dict:
"""Send a webhook request with JWT authentication."""
# Generate JWT token
token = self._generate_jwt_token(payload)
# Set headers with JWT token
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Send POST request
response = requests.post(
self.webhook_url,
json=payload,
headers=headers
)
# Handle response
if response.status_code == 200:
return {"status": "success", "response": response.json()}
else:
return {"status": "error", "response": response.status_code, "message": response.text}
-48
View File
@@ -1,48 +0,0 @@
import os
import sys
from git import Repo
# Set these variables accordingly
REPO_OWNER = "your_repo_owner"
REPO_NAME = "your_repo_name"
def clone_repo(repo_url, branch="main"):
Repo.clone_from(repo_url, ".", branch=branch)
def create_markdown_file(file_name, content):
with open(f"{file_name}.md", "w") as f:
f.write(content)
def commit_and_push(file_name, message):
repo = Repo(".")
repo.index.add([f"{file_name}.md"])
repo.index.commit(message)
repo.remote().push()
def create_new_branch(branch_name):
repo = Repo(".")
repo.create_head(branch_name).checkout()
repo.head.reference.set_tracking_url(f"https://your_git_server/{REPO_OWNER}/{REPO_NAME}.git/{branch_name}")
repo.remote().push()
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python push_markdown.py <repo_url> <markdown_file_name>")
sys.exit(1)
repo_url = sys.argv[1]
file_name = sys.argv[2]
# Clone the repository
clone_repo(repo_url)
# Create a new Markdown file with content
create_markdown_file(file_name, "Hello, World!\n")
# Commit and push changes to the main branch
commit_and_push(file_name, f"Add {file_name}.md")
# Create a new branch named after the Markdown file
create_new_branch(file_name)
print(f"Successfully created '{file_name}' branch with '{file_name}.md'.")
+95 -32
View File
@@ -1,39 +1,102 @@
import os import os, shutil
from git import Git from urllib.parse import quote
from git.repo import BaseRepository from git import Repo
from git.exc import InvalidGitRepositoryError from git.exc import GitCommandError
from git.remote import RemoteAction
class GitRepository:
# This is designed to be transitory it will desctruvtively create the repo at repo_path
# if you have uncommited changes you can kiss them goodbye!
# Don't use the repo created by this function for dev -> its a tool!
# It is expected that when used you will add, commit, push, delete
def __init__(self, repo_path, username=None, password=None):
git_protocol = os.environ["GIT_PROTOCOL"]
git_remote = os.environ["GIT_REMOTE"]
#if username is not set we don't need parse to the url
if username==None or password == None:
remote = f"{git_protocol}://{git_remote}"
else:
# of course if it is we need to parse and escape it so that it
# can generate a url
git_user = quote(username)
git_password = quote(password)
remote = f"{git_protocol}://{git_user}:{git_password}@{git_remote}"
if os.path.exists(repo_path):
shutil.rmtree(repo_path)
self.repo_path = repo_path
print("Cloning Repo")
Repo.clone_from(remote, repo_path)
self.repo = Repo(repo_path)
self.username = username
self.password = password
def clone(self, remote_url, destination_path):
"""Clone a Git repository with authentication"""
try:
self.repo.clone(remote_url, destination_path)
return True
except GitCommandError as e:
print(f"Cloning failed: {e}")
return False
def fetch(self, remote_name='origin', ref_name='main'):
"""Fetch updates from a remote repository with authentication"""
try:
self.repo.remotes[remote_name].fetch(ref_name=ref_name)
return True
except GitCommandError as e:
print(f"Fetching failed: {e}")
return False
def pull(self, remote_name='origin', ref_name='main'):
"""Pull updates from a remote repository with authentication"""
print("Pulling Latest Updates (if any)")
try:
self.repo.remotes[remote_name].pull(ref_name)
return True
except GitCommandError as e:
print(f"Pulling failed: {e}")
return False
def get_branches(self):
"""List all branches in the repository"""
return [branch.name for branch in self.repo.branches]
def try_something(test): def create_and_switch_branch(self, branch_name, remote_name='origin', ref_name='main'):
"""Create a new branch in the repository with authentication."""
try:
print(f"Creating Branch {branch_name}")
# Use the same remote and ref as before
self.repo.git.branch(branch_name)
except GitCommandError:
print("Branch already exists switching")
# ensure remote commits are pulled into local
self.repo.git.checkout(branch_name)
# Set the path to your blog repo here def add_and_commit(self, message=None):
blog_repo = "/path/to/your/blog/repo" """Add and commit changes to the repository."""
try:
print("Commiting latest draft")
# Add all changes
self.repo.git.add(all=True)
# Commit with the provided message or a default
if message is None:
commit_message = "Added and committed new content"
else:
commit_message = message
self.repo.git.commit(message=commit_message)
return True
except GitCommandError as e:
print(f"Commit failed: {e}")
return False
def create_copy_commit_push(self, file_path, title, commit_messge):
self.create_and_switch_branch(title)
# Checkout a new branch and create a new file for our blog post self.pull(ref_name=title)
branch_name = "new-post" shutil.copy(f"{file_path}", f"{self.repo_path}src/content/")
try:
repo = Git(blog_repo)
repo.checkout("-b", branch_name, "origin/main")
with open("my-blog-post.md", "w") as f:
f.write(content)
except InvalidGitRepositoryError:
# Handle repository errors gracefully
pass
# Add and commit the changes to Git self.add_and_commit(f"'{commit_messge}'")
repo.add("my-blog-post.md")
repo.commit("-m", "Added new blog post about DevOps best practices.")
# Push the changes to Git and create a PR
repo.remote().push("refs/heads/{0}:refs/for/main".format(branch_name), "--set-upstream")
base_branch = "origin/main"
target_branch = "main"
pr_title = "DevOps best practices"
try:
repo.create_head("{0}-{1}", base=base_branch, message="{}".format(pr_title))
except RemoteAction.GitExitStatus as e:
# Handle Git exit status errors gracefully
pass
self.repo.git.push()
+6 -1
View File
@@ -18,9 +18,13 @@ class TrilumNotes:
print("Please run get_token and set your token") print("Please run get_token and set your token")
else: else:
self.ea = ETAPI(self.server_url, self.token) self.ea = ETAPI(self.server_url, self.token)
self.new_notes = None
self.note_content = None
def get_token(self): def get_token(self):
ea = ETAPI(self.server_url) ea = ETAPI(self.server_url)
if self.tril_pass == None:
raise ValueError("Trillium password can not be none")
token = ea.login(self.tril_pass) token = ea.login(self.tril_pass)
print(token) print(token)
print("I would recomend you update the env file with this tootsweet!") print("I would recomend you update the env file with this tootsweet!")
@@ -40,10 +44,11 @@ class TrilumNotes:
def get_notes_content(self): def get_notes_content(self):
content_dict = {} content_dict = {}
if self.new_notes is None:
raise ValueError("How did you do this? new_notes is None!")
for note in self.new_notes['results']: for note in self.new_notes['results']:
content_dict[note['noteId']] = {"title" : f"{note['title']}", content_dict[note['noteId']] = {"title" : f"{note['title']}",
"content" : f"{self._get_content(note['noteId'])}" "content" : f"{self._get_content(note['noteId'])}"
} }
self.note_content = content_dict self.note_content = content_dict
return content_dict return content_dict
+13
View File
@@ -0,0 +1,13 @@
from UnleashClient import UnleashClient
import asyncio
client = UnleashClient(
url="http://192.168.178.160:30007/api/",
app_name="unleash-onboarding-python",
custom_headers={'Authorization': 'default:development.6uQIie4GdslTxgYAWVu35sRBjjBMPRRKw6vBj6mFsgFfvdXuy73GgLQg'}) # in production use environment variable
client.initialize_client()
while True:
print(client.is_enabled("crew_ai_integration"))
asyncio.run(asyncio.sleep(1))