Bitcoin Core vs Knots: An Objective Look
- Key Architectural Improvements
- User Interface and Operational Enhancements
- Network and Policy Management
- The Filtering Controversy
- Guidance for Node Operators
- Recommendation Framework
- The Steelman Case for Bitcoin Core v28
- The Steelman Case for Bitcoin Knots
—@Sats McJay, September 4, 2025
Edit (September 7, 2025): This analysis compares Core version 28 to Knots version 28. Some clarifications have been added.
A lot is being said about the controversy between Bitcoin Core and Bitcoin Knots. I usually ignore it all, but I became curious as to the actual difference between Core and Knots, so I started to do some digging into the code differences.
Since the current version of Knots is forked off from Bitcoin Core 28.x, I used git to find all the files that had been updated in Knots compared to Core. I found more than a megabyte of additions; much more than a simple debate about transaction filters would warrant. So I fed each file that had been changed into an AI (gpt-4o-mini), asking it to describe the changes between the files. With that, I got around 800kb of detailed, objective analysis of what makes Knots different than Core. You can download this document here to feed into your own AI chat sessions, which I highly recommend doing.
Now, even that is very lengthy and highly technical when you start to read it. So I asked Claude Opus to write up some short articles based on it. Below are lightly edited versions of it’s outputs.
If you’re interested in cutting through the noise and getting a purely objective look into this debate, I suggest giving this a read.
#bitcoin #core #knots
Claude Opus 4.1:
Bitcoin Knots represents a significant enhancement of the Bitcoin Core v28 codebase, introducing hundreds of improvements across user interface, network management, transaction handling, and system performance. Knots offers node operators substantially more control over their node’s behavior and policy enforcement, while maintaining full compatibility with the Bitcoin network.
Key Architectural Improvements
Memory and Performance Management
Knots introduces sophisticated memory management systems that allow nodes to operate more efficiently under resource constraints. The software can automatically flush caches when system memory runs low and provides operators with granular control over memory allocation. These improvements particularly benefit operators running nodes on lower-specification hardware or in memory-constrained environments.
Enhanced Configuration Management
Unlike Core’s static configuration approach, Knots introduces dynamic configuration capabilities through read-write configuration files. This allows node operators to adjust settings without restarting their nodes and provides more flexible management of complex setups. The system also includes better validation and error handling for configuration issues.
Advanced Fee and Transaction Management
Knots significantly expands fee estimation capabilities and introduces coin-age-based transaction prioritization. This means transactions using older, more established Bitcoin can receive priority treatment, potentially reducing confirmation times during network congestion. The enhanced fee estimation considers dynamic factors like mempool conditions and provides more accurate predictions for transaction confirmation timing.
User Interface and Operational Enhancements
Comprehensive GUI Improvements
Knots introduces several new interface components including real-time mempool statistics visualization, enhanced network monitoring capabilities, and peer connection management tools. These additions provide node operators with unprecedented visibility into their node’s operation and network conditions.
Command-Line Excellence
The software includes professional-grade command-line enhancements with automated bash completion, improved error messaging, and expanded RPC (remote procedure call) capabilities. These improvements significantly reduce the learning curve for technical users and provide better integration with automated systems.
Advanced Wallet Functionality
Knots expands wallet capabilities with support for modern address formats, enhanced backup options, and improved key management. The software includes better handling of hierarchical deterministic wallets and provides more granular control over transaction creation and signing.
Network and Policy Management
Sophisticated Peer Management
Knots introduces advanced peer connection management with support for different connection types, enhanced eviction policies, and better handling of network edge cases. The software can maintain more stable connections and provides operators with detailed information about peer behavior and performance.
Enhanced Transaction Policies
The software provides node operators with extensive control over which transactions their node will relay and store. This includes sophisticated dust management (handling of very small transactions), enhanced replacement policies for unconfirmed transactions, and improved validation of transaction scripts.
The Filtering Controversy
Transaction Type Discrimination
Knots includes capabilities to identify and potentially filter transactions based on their content and purpose. The software can distinguish between traditional monetary transactions and those that embed arbitrary data, create tokens, or store information on the blockchain for non-monetary purposes.
Policy vs. Consensus
This filtering capability operates at the policy level, not the consensus level. Knots nodes will still validate and accept blocks containing any valid transactions, ensuring they remain fully compatible with the Bitcoin network. However, they can choose not to relay certain transaction types through their mempool, potentially affecting how quickly such transactions propagate across the network.
The Spam Debate
Critics of Bitcoin Knots argue that Bitcoin’s design makes any valid transaction legitimate, regardless of its purpose, and that filtering constitutes censorship. Proponents of Knots contend that node operators should have the right to choose which transactions they help propagate, particularly when non-monetary uses consume block space that could otherwise be used for payment transactions. They argue that applications storing arbitrary data or creating tokens should use purpose-built blockchains rather than Bitcoin.
Guidance for Node Operators
Performance Considerations
Knots generally offers superior performance, particularly for nodes with limited resources. The enhanced memory management and more efficient caching can result in lower resource usage and better responsiveness. However, the additional features and monitoring capabilities may consume slightly more CPU cycles during normal operation.
Policy Alignment
Node operators should consider whether Knots’ enhanced filtering capabilities align with their view of Bitcoin’s purpose. Those who prefer a more restrictive approach to non-monetary transactions may find Knots’ options valuable, while those who prefer minimal policy enforcement might consider these features unnecessary.
Technical Expertise
Knots provides significantly more configuration options and operational visibility than Core. While this offers greater control, it also requires more technical understanding to optimize effectively. Operators comfortable with advanced configuration will benefit most from Knots’ capabilities.
Network Impact
Running Knots contributes to policy diversity in the Bitcoin network. A network with varied transaction policies may be more resilient than one with uniform behavior, though the optimal balance remains a subject of ongoing debate within the Bitcoin community.
Recommendation Framework
Choose Knots if you:
- Want maximum control over your node’s behavior and policies
- Prefer enhanced user interfaces and operational visibility
- Support limiting non-monetary uses of Bitcoin’s blockchain
- Have the technical expertise to leverage advanced features
- Run resource-constrained hardware that could benefit from optimizations
Consider Core v28 if you:
- Prefer the simplicity of minimal policy enforcement
- Want the most widely-tested and conservative approach
- Are less concerned with advanced operational features
- Prefer following the reference implementation’s approach to Bitcoin
The choice between Core and Knots ultimately reflects different philosophies about Bitcoin’s role and how much control node operators should exercise over network behavior. Both remain fully compatible with Bitcoin’s consensus rules and contribute to network security and decentralization.
The following two sections are steelman arguments for Bitcoin Core and for Bitcoin Knots. While not as objective in some points as the article above, and necessarily biased, they provide valuable insight to the reasons why this debate gets so heated.
Claude Opus 4.1:
The Steelman Case for Bitcoin Core v28
Engineering Excellence Through Constraint
Bitcoin Core’s approach reflects a disciplined engineering philosophy: do one thing exceptionally well rather than many things adequately. The codebase demonstrates this through its focused architecture where each component has a clearly defined purpose within the consensus layer.
The code evidence supports this. Core maintains clean separation between consensus validation and policy preferences. While Knots introduces complex policy engines with configurable transaction filtering, dust management systems, and priority calculators, Core keeps these concerns minimal; intentional constraints that prevent feature creep from compromising the system’s core function.
Operational Simplicity as a Feature
The relative simplicity of Core’s configuration system is not a bug, but a feature that reduces operational risk. The code shows Core using straightforward boolean flags and numeric parameters where Knots introduces nested option structures, dynamic configuration systems, and complex policy hierarchies. When you’re securing a monetary network worth hundreds of billions of dollars, every additional configuration option is a potential attack surface or misconfiguration point.
Consider the memory management differences: while Knots introduces sophisticated cache flushing algorithms and dynamic memory thresholds, Core maintains predictable, well-tested memory patterns. The Knots approach may be more efficient in theory, but Core’s approach is more auditable and less prone to unexpected behavior under edge conditions.
Network Effect Through Uniformity
Bitcoin’s strength comes from thousands of nodes reaching identical conclusions about transaction validity. Core’s conservative approach to policy means the network exhibits more uniform behavior. The code analysis reveals Knots nodes can diverge significantly in transaction relay patterns, mempool contents, and peer connection strategies. While diversity has theoretical benefits, uniformity provides practical advantages in maintaining network consensus and reducing partition risks.
Proven Reliability Through Battle Testing
The production evidence is overwhelming: Core has processed every Bitcoin transaction in history without a consensus failure. Its codebase has been scrutinized by more developers, run in more environments, and tested under more conditions than any alternative implementation. The incremental changes in Core reflect careful validation of each modification against this historical performance record.
While Knots introduces hundreds of new code paths (priority calculation algorithms, enhanced RPC endpoints, complex GUI features), each represents potential failure modes that haven’t been tested across years of production operation. The software engineering principle applies: the most reliable code is the code that doesn’t exist.
The Steelman Case for Bitcoin Knots
Engineering Evolution Through Enhancement
Knots represents what Bitcoin software becomes when it is freed from artificial constraints on functionality and user empowerment. The codebase demonstrates sophisticated engineering that addresses real operational challenges that Core’s conservative approach leaves unsolved.
Resource Management Excellence
The code reveals Knots implementing advanced memory management that Core lacks entirely. The dynamic cache flushing based on system memory availability, intelligent I/O priority scheduling, and sophisticated resource allocation algorithms represent genuine engineering advancement. Node operators running on constrained hardware, including most individual Bitcoin users, benefit dramatically from these optimizations.
The performance improvements aren’t theoretical. The code shows Knots handling memory pressure gracefully through automatic cache management, whereas Core nodes can become unresponsive or crash when system memory runs low. This engineering maturity makes Bitcoin accessible to more participants by enhancing node reliability.
Operational Transparency and Control
Bitcoin Core’s “simplicity” often manifests as opacity. The code analysis shows Knots providing comprehensive visibility into node operation through enhanced logging, real-time mempool statistics, peer connection analytics, and transaction flow monitoring. All essential tools for diagnosing network issues, optimizing performance, and understanding Bitcoin’s behavior.
The enhanced RPC interface in Knots provides programmatic access to internal state that Core keeps hidden. This transparency enables sophisticated applications, research, and operational tooling that are otherwise impossible with Core’s limited interface. When Core advocates praise simplicity, they’re often defending information hiding—hiding that serves no real security purpose.
Policy Layer Sophistication
The most compelling aspect of Knots is its recognition that policy and consensus are separate concerns that require different approaches. The code shows sophisticated policy management that allows node operators to make informed decisions about transaction relay, mempool management, and peer connections without compromising consensus validation.
Given that Bitcoin’s block space is genuinely scarce, Knots seeks principled resource allocation with its filtering strategies. When that space gets consumed by data storage applications, NFT projects, or token schemes, it crowds out payment transactions that represent Bitcoin’s core value proposition. Knots provides node operators with tools to prioritize payment transactions without breaking consensus compatibility.
The coin-age priority system exemplifies this sophistication. Rather than treating all transactions equally, Knots recognizes that transactions spending older coins represent more established economic activity. This creates natural incentives for long-term holding while providing faster confirmation for users who aren’t gaming the system.
User Experience as System Reliability
Proponents may call it elegant, but Core’s minimal user interface is neglectful of the needs of node-runners. The code shows Knots implementing comprehensive wallet management, enhanced backup systems, improved error messaging, and professional-grade command-line tools. These improvements reduce user errors that can lead to lost funds, failed transactions, or operational mistakes.
The bash completion system, enhanced configuration validation, and improved debugging output represent recognition that Bitcoin software serves real users with real problems. Core’s austere interface pushes complexity onto users and external tools, creating fragmentation and reducing overall system reliability.
Network Resilience Through Diversity
The strongest argument for Knots is that monoculture is fragile. A network where every node runs identical code with identical policies is vulnerable to systemic failures, coordinated attacks, and regulatory capture. The code differences between Core and Knots create beneficial heterogeneity in network behavior, while maintaining consensus compatibility.
When network conditions stress the system, having nodes with different relay policies, different memory management strategies, and different peer connection algorithms provides natural load balancing and failure isolation. In fact, the 2017 network congestion crisis demonstrated how Core’s uniform behavior patterns created system-wide bottlenecks that more sophisticated policy management could have mitigated.
The Engineering Synthesis
Both arguments represent legitimate engineering philosophies. Core’s constraint-focused approach serves critical reliability requirements in a system that can’t afford consensus failures. Knots’ enhancement-focused approach addresses real operational needs that Core’s minimalism leaves unaddressed.
Rather than viewing the the difference between Core and Knots as the difference between “good” or “bad” software, it may be better to think of them as different theories of how complex systems should evolve while maintaining their essential properties.
Onward 🫡
Great post 👍
Stimulus check from Fort Nakamoto—spend it wisely💰🏰
𝘽𝙐𝙇𝙇𝙄𝙎𝙃
nice 👉
I don’t have time to look at this right now, but the fact that you did share it publicly tells me a lot.
Had to delete request the old reply. It’s mostly my personal system prompt. Now please do the analysis yourself.
"""Analyze the differences between Core and Knots."""
import json
import os
import subprocess
import sys
from collections import defaultdict
import requests
# PROTOCOL = "ollama"
# SERVER_URL = "http://localhost:11434/api/generate"
# API_KEY = None
# MODEL = "gpt-oss:20b"
PROTOCOL = "openai"
SERVER_URL = "https://api.ppq.ai/chat/completions"
API_KEY = ""
MODEL = "gpt-4o-mini"
BACKUP_MODEL = "gpt-4.1-mini"
SYSTEM = """
# Instructions
## Personality
### Purpose-Driven Engineering Persona
You are a software engineer who approaches development as a disciplined, intentional craft. You draw on classical ideas—*svabhava*, *svadharma*, and *karman*. Your role is to translate these principles into clear, modern engineering habits.
#### Core Framework
- **Software has its own context and purpose**
- **Coding is a focused practice, not a mechanical chore**
- **Each function should contribute meaningfully to the whole**
#### Practice Principles
1. **Svabhava (Intrinsic Nature)**
- Study the core nature of the problem until it feels obvious
- Design only what the problem truly requires—no excess layers
2. **Svadharma (Rightful Purpose)**
- Align implementation with real user needs, not hype
- Favor clarity, maintainability, and long-term usefulness
3. **Karman (Actual Performance)**
- Measure what the system actually does, not what you hope it does
- Treat defects as signals; refine until behavior matches intent
#### Day-to-Day Mindset
- Stay level-headed when challenges arise
- Keep tooling preferences flexible; value outcomes over brand names
- Use debugging as deliberate skill-building, not just fire-fighting
#### Communication Style
- Speak plainly; explain complex ideas without jargon. If the user corrects or redirects you, adopt the change and continue without apology, restatement, or commentary.
- Trade ego for genuine curiosity in code reviews and discussions
- Treat every collaboration as a chance for shared growth
#### Ethical Commitments
- Build features that improve users’ lives and respect their data
- Minimize unintended harm and technical debt
- Remember that every system fits into a wider network of people and tools
Your code is your craft. The development process is continuous learning. The finished product is your contribution to the larger technical community.
## Critical Thinking
When generating code, think holistically about the purpose of the code being requested by the prompt. Summarize the user's intent in one sentence, then give suggestions to enhance Svabhava only if requested.
## Graph-First Data Modeling
You approach problems through a graph-native lens.
### Cognitive Orientation
- **Connection primacy**: Relationships are the first-class citizens, not the afterthought
- **Network intuition**: Natural tendency to see interconnections before categories
- **Pattern recognition**: Skilled at spotting recurring structural motifs within complex networks
- **Path-based reasoning**: Inherently thinks in terms of routes, distances, and traversals between entities
### Mental Models
- **Organic structure vision**: Sees data as living, growing networks rather than rigid structures
- **Property-decorated graphs**: Envisions properties as decorations on a more fundamental connection structure
- **Contextual understanding**: Values the position and connections of an entity as much as its intrinsic attributes
- **Emergent meaning**: Recognizes that significance often emerges from connection patterns, not individual elements
## Software Design Principles
The following is a methodology for evaluating software code according to Composite Design (Glenford Myers, 1975) in the form of Functional Decomposition. Understand this criteria when writing and analyzing code, aiming for the highest module strength and loosest coupling possible.
### Definitions
- **Module**: A group of program statements that have a defined beginning and end, collectively referenced by a module name, and can be called from other modules. Corresponds to the "function" in most modern languages.
### Problem Structure
Composite analysis begins with the problem structure. A piece of software is typically comprised of several problem structures. The problem structure is a rough sketch of the problem the software is attempting to solve. It is presented in functional, rather than procedural, terms. It is typically a linear chain of three to ten processes, representing the data flow within the problem (not necessarily the execution flow, or the order the processes run in).
For example, the problem structure of an airline reservation system might be
- Input transaction
- Read flight files
- Update flight files
- Update accounts-receivable file
- Write ticket
- Send load & trim data
- Return flight information
### External Data Streams
After the problem structure is defined, the next step is to identify the streams of data that are both external and conceptual. External streams of data are those that begin and/or end outside of the system. Conceptual streams of data are those containing related data.
### Points of Highest Abstraction
From the identified external streams of data, the next step is to determine the points of highest abstraction for those streams. Data is transformed as it moves through the problem. From the starting input, there comes a point where input stream seems to disappear, as its data has transformed into a form that no longer resembles its origins. That point is called the Most Abstract Input Data. When the problem is viewed in reverse, from the ending output, a similar point can be found, the Most Abstract Output Data. The section of the problem in between the Most Abstract Input and the Most Abstract Output is the Central Transform. Sometimes, there is no Central Transform, and the point of Most Abstract Input and Most Abstract Output are the same.
Visually, the parts of the problem structure become as follows:
Major Input Stream -> Most Abstract Input Data -> Central Transform -> Most Abstract Output Data -> Major Output Stream
### Functional Decomposition
Following from the determination of the points of highest abstraction, the next step is decomposition. The problem structure is broken into three parts: the major input stream, the central transform, and the major output stream. Take each part and describe it as a function, with its inputs and outputs. The input and output streams usually have no input nor output, respectively. From these three submodules, the process of composite analysis can repeat, treating each as a subproblem, which will have its own problem structure and points of highest abstraction. The recursion continues until the subproblems cannot be broken down further.
#### Formatting Decompositions
If a program contains modules A, B, and C, where A calls B and C, and B calls C, the functional decompositions would be notated as follows. Each module has a name and is referred to with a capital letter starting with A, B, C... then AA, AB, AC... and so on. The first column shows whether the called module has other dependencies, with "—" indicating a root module and "↓" indicating a mid-level module, which must have a section listing the modules it calls, until only root modules remain. Call numbers are sequential and unique, even if the same module is called in several other modules, and do not indicate the order in which modules are called.
---
**A. Name of Module A**
| | Call # | Module | Module Name | Inputs | Outputs |
| --- | ------ | ------ | ---------------- | ------ | ------- |
| ↓ | 1 | B | Name of Module B | A | X |
| — | 2 | C | Name of Module C | B | Y |
**B. Name of Module B**
| | Call # | Module | Module Name | Inputs | Outputs |
| --- | ------ | ------ | ---------------- | ------ | ------- |
| — | 3 | C | Name of Module C | C | Z |
---
### Evaluating Software
#### Module Strength
In composite design, there are several levels of module strength. In the generated code, make each module as strong as possible.
- **Functional**: The strongest module. All of the elements are related to the performance of a single function.
- **Informational**: Performs multiple functions where the functions all deal with a single data structure (like a mapping). Represents the packing together of two or more functional-strength modules.
- **Communicational**: A module with procedural strength, but all the elements either reference the same set of data or pass data among themselves.
- **Procedural**: Perform more than one function, where they are related to the procedure of the problem.
- **Classical**: A module with logical strength, but the elements are also related in time, e.g. sequentially.
- **Logical**: A module of coincidental strength, but the elements are related logically.
- **Coincidental**: A module in which there is no meaningful relationship among its elements.
#### Module Coupling
In composite design, there are several degrees of module coupling. In the generated code, make each module as loosely coupled as possible.
- **Data**: A relationship that is not content, common, external, control, or stamp coupled. All input and output are passed as arguments or return variables. All arguments are data elements, not control elements or data structures.
- **Stamp**: A relationship where both modules reference the same data structure, and the data structure is not globally known.
- **Control**: A relationship where one module passes control elements to another. Such an argument directly influences the execution of the called module, such as function codes, flags, and switches.
- **External**: A relationship where both modules refer to the same global variable, but it is an individual data item, not a data structure.
- **Common**: A relationship where both modules refer to the same global data structure (such as a COMMON environment in FORTRAN).
- **Content**: A relationship where one module makes direct reference to the internal contents of another module, like program statements or private variables.
## Collaboration Protocol
1. Engagement style
- You are my thinking partner, not my code generator.
2. Scope of output
- Provide conceptual explanations, design suggestions, or short illustrative snippets (≤ 10 lines) only when essential.
- Favor summaries, outlines, pseudo-code, or-language descriptions over code.
3. Code constraints
- Never generate, rewrite, or auto-complete full files, multi-file solutions, or large code blocks (> 10 lines) unless I explicitly request it the same message.
- If I supply code, comment only on the specific fragment at issue; do not echo the entire file back
- Omit boilerplate; show placeholders such as `// …` or `/* … */` where appropriate.
4. Conflict handling
- If a request appears to conflict with these limits, pause and ask for clarification instead of violating them.
5. Formatting
- Use concise prose and minimal markdown; fence only the exact snippet required.
- Avoid language that encourages direct copy-paste into production code.
- Do not use phrases like 'You are right', 'I was wrong', 'Apologies', or 'After re-evaluating…' — adopt silently.
- Never use the 'not just...—it's...' template or similar rhetorical flips, and avoid marketingy, grandiose, or poetic flourishes; write only plain, direct declarative sentences
6. Agree-ability
- If the user contradicts you, briefly (≤2 sentences) evaluate.
- If clearly incorrect, rebut concisely; otherwise adopt the user's correction and carry on.
- If the user insists after you analyze, accept and proceed.
"""
PROMPT_TEMPLATE = """
# Prompt
Following are files from Bitcoin Core and Bitcoin Knots, along with a
difference between the files. If there is no Core file provided, the file is
newly added in Knots.
Describe the changes made in the Knots version compared to the Core version.
Order the changes from most to least significant. The level of detail should be
moderate, and aimed towards a technical reader.
Use a purely neutral tone. Don't consider a change "good" or "bad", just
dispassionately describe the changes and their potential impact.
Format the response in paragraphs. Do not include headers, sections,
introductions, bullet points, or an ending summary in your response.
## Core Files
{core_files}
## Knots Files
{knots_files}
## Diffs
{diff_files}
"""
CODE_FILE_TEMPLATE = """
File: {filename}
{code}
"""
OUTPUT_DIR = "./analysis/"
def get_changed_files():
"""Get a list of the changed files form Core to Knots."""
cmd = (
"git diff --no-index --name-only core knots | grep -E '^knots/(share|src|test)'"
)
result = subprocess.run(cmd, shell=True, text=True, capture_output=True, check=True)
return [line.strip() for line in result.stdout.splitlines()]
def analyze_file_changes(files: list[str]):
"""Runs an AI analysis on the changes between the Core and Knots versions
of the given files.
"""
output_file = ".".join(files[0].replace("/", "__").split(".")[:-1]) + ".analysis.md"
output_dir = os.path.join(OUTPUT_DIR, os.path.dirname(files[0]))
output_path = os.path.join(output_dir, output_file)
os.makedirs(output_dir, exist_ok=True)
if os.path.exists(output_path):
print("Analysis exists. Skipping:", output_path)
return
core_prompt = ""
knots_prompt = ""
diff_prompt = ""
for file in files:
core_file = "core/" + file
knots_file = "knots/" + file
if os.path.exists(core_file):
with open(core_file, "r", encoding="utf8") as f:
core_prompt += CODE_FILE_TEMPLATE.format(
filename=core_file, code=f.read()
)
if os.path.exists(knots_file):
with open(knots_file, "r", encoding="utf8") as f:
knots_prompt += CODE_FILE_TEMPLATE.format(
filename=knots_file, code=f.read()
)
if os.path.exists(core_file):
diff_cmd = f'git diff "{core_file}" "{knots_file}" | cat'
else:
diff_cmd = f'git diff --no-index /dev/null "{knots_file}" | cat'
diff = subprocess.run(
diff_cmd, shell=True, text=True, capture_output=True, check=True
).stdout
diff_prompt += CODE_FILE_TEMPLATE.format(filename=file, code=diff)
prompt = PROMPT_TEMPLATE.format(
core_files=core_prompt,
knots_files=knots_prompt,
diff_files=diff_prompt,
)
print(f"Requesting analysis: {",".join(files)}")
headers = {
"Content-Type": "application/json",
}
if API_KEY is not None:
headers.update({"Authorization": f"token {API_KEY}"})
if PROTOCOL == "ollama":
payload = {
"model": MODEL,
"system": SYSTEM,
"prompt": "hello world",
"stream": False,
}
response = requests.post(SERVER_URL, headers=headers, json=payload)
if response.status_code != 200:
payload = {
"model": BACKUP_MODEL,
"system": SYSTEM,
"prompt": "hello world",
"stream": False,
}
response = requests.post(SERVER_URL, headers=headers, json=payload)
elif PROTOCOL == "openai":
payload = {
"model": MODEL,
"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": prompt},
],
}
response = requests.post(SERVER_URL, headers=headers, json=payload)
if response.status_code != 200:
payload = {
"model": BACKUP_MODEL,
"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": prompt},
],
}
response = requests.post(SERVER_URL, headers=headers, json=payload)
else:
print("ERROR: invalid endpoint protocol:", PROTOCOL)
sys.exit()
if response.status_code == 200:
analysis = response.json().get("response")
if analysis is None:
choices = response.json().get("choices")
if len(choices) > 0:
analysis = choices[0].get("message", {}).get("content")
if analysis is not None:
print("Writing analysis:", output_path)
with open(output_path, "w", encoding="utf8") as f:
f.write(f"## {", ".join(files)}\n\n")
f.write(analysis)
else:
print("Error: No analysis received")
sys.exit()
else:
print(f"Error: {response.status_code} - {response.text}")
sys.exit()
def main():
"""Main program."""
print("Finding changed files...")
knots_files = get_changed_files()
print(f"Found {len(knots_files)} files.")
file_groups = defaultdict(list)
for knots_file in knots_files:
generic_file = knots_file.replace("knots/", "")
base_name = os.path.splitext(os.path.basename(generic_file))[0]
dir_name = os.path.dirname(generic_file)
group_key = f"{dir_name}/{base_name}"
file_groups[group_key].append(generic_file)
print("Analyzing file changes...")
for files in file_groups.values():
analyze_file_changes(files)
if __name__ == "__main__":
main()
This will make a directory with all the individual file analyses. Use code2prompt to collect them.
AI is sketchy enough without keeping your prompt and context secret from the people you are showing the results.
That’s pretty solid, nice work dude
Write a comment