flowsmith 0.6.0__tar.gz → 0.7.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {flowsmith-0.6.0 → flowsmith-0.7.0}/PKG-INFO +1 -1
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/__init__.py +1 -1
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/__main__.py +22 -2
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/config.py +7 -2
- flowsmith-0.7.0/flowsmith/migrations/mysql/001_create_flows.sql +38 -0
- flowsmith-0.7.0/flowsmith/migrations/mysql/002_create_nodes.sql +46 -0
- flowsmith-0.7.0/flowsmith/migrations/postgres/001_create_flows.sql +13 -0
- flowsmith-0.7.0/flowsmith/migrations/postgres/002_create_nodes.sql +18 -0
- flowsmith-0.7.0/flowsmith/migrations/sqlite/001_create_flows.sql +13 -0
- flowsmith-0.7.0/flowsmith/migrations/sqlite/002_create_nodes.sql +18 -0
- flowsmith-0.7.0/flowsmith/scripts/rag_pipeline/chat.py +159 -0
- flowsmith-0.7.0/flowsmith/scripts/rag_pipeline/cli.py +136 -0
- flowsmith-0.7.0/flowsmith/scripts/rag_pipeline/index_enriched.py +59 -0
- flowsmith-0.7.0/flowsmith/scripts/rag_pipeline/store_vectors.py +60 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/storage/__init__.py +2 -1
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/storage/postgres.py +13 -1
- flowsmith-0.7.0/flowsmith/storage/sqlite.py +192 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith.egg-info/PKG-INFO +1 -1
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith.egg-info/SOURCES.txt +12 -1
- {flowsmith-0.6.0 → flowsmith-0.7.0}/pyproject.toml +4 -1
- {flowsmith-0.6.0 → flowsmith-0.7.0}/LICENSE +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/README.md +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/context.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/contrib/__init__.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/decorators.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/exceptions.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/executor.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/flow.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/migrations/__init__.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/models/__init__.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/models/flow_record.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/models/node_record.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/py.typed +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/step.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/storage/base.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/storage/memory.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/storage/mysql.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith/watchdog.py +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith.egg-info/dependency_links.txt +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith.egg-info/entry_points.txt +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith.egg-info/requires.txt +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/flowsmith.egg-info/top_level.txt +0 -0
- {flowsmith-0.6.0 → flowsmith-0.7.0}/setup.cfg +0 -0
|
@@ -3,7 +3,7 @@ FlowSmith CLI
|
|
|
3
3
|
Usage:
|
|
4
4
|
flowsmith migrate --url postgresql://user:pass@localhost/db
|
|
5
5
|
flowsmith migrate --url mysql://user:pass@localhost/db
|
|
6
|
-
flowsmith migrate
|
|
6
|
+
flowsmith migrate --url sqlite:///flowsmith.db
|
|
7
7
|
flowsmith migrate # reads DATABASE_URL from environment
|
|
8
8
|
"""
|
|
9
9
|
|
|
@@ -25,12 +25,30 @@ def detect_dialect(url: str) -> str:
|
|
|
25
25
|
return "postgres"
|
|
26
26
|
if url.startswith("mysql://"):
|
|
27
27
|
return "mysql"
|
|
28
|
+
if url.startswith("sqlite://"):
|
|
29
|
+
return "sqlite"
|
|
28
30
|
raise ValueError(
|
|
29
31
|
f"Unsupported database URL scheme: '{url.split('://')[0]}'\n"
|
|
30
|
-
"Supported schemes: postgresql://, postgres://, mysql://"
|
|
32
|
+
"Supported schemes: postgresql://, postgres://, mysql://, sqlite://"
|
|
31
33
|
)
|
|
32
34
|
|
|
33
35
|
|
|
36
|
+
def run_migrations_sqlite(url: str) -> None:
|
|
37
|
+
import sqlite3
|
|
38
|
+
|
|
39
|
+
from flowsmith.storage.sqlite import sqlite_path
|
|
40
|
+
|
|
41
|
+
migration_dir = MIGRATIONS_DIR / "sqlite"
|
|
42
|
+
conn = sqlite3.connect(sqlite_path(url))
|
|
43
|
+
try:
|
|
44
|
+
for sql_file in sorted(migration_dir.glob("*.sql")):
|
|
45
|
+
print(f" -> {sql_file.name}")
|
|
46
|
+
conn.executescript(sql_file.read_text())
|
|
47
|
+
conn.commit()
|
|
48
|
+
finally:
|
|
49
|
+
conn.close()
|
|
50
|
+
|
|
51
|
+
|
|
34
52
|
def run_migrations_postgres(url: str) -> None:
|
|
35
53
|
try:
|
|
36
54
|
import psycopg2
|
|
@@ -153,6 +171,8 @@ def cmd_migrate(args: argparse.Namespace) -> None:
|
|
|
153
171
|
run_migrations_postgres(url)
|
|
154
172
|
elif dialect == "mysql":
|
|
155
173
|
run_migrations_mysql(url)
|
|
174
|
+
elif dialect == "sqlite":
|
|
175
|
+
run_migrations_sqlite(url)
|
|
156
176
|
except Exception as e:
|
|
157
177
|
print(f"\nERROR: Migration failed: {e}")
|
|
158
178
|
sys.exit(1)
|
|
@@ -27,9 +27,13 @@ def _make_storage(
|
|
|
27
27
|
from flowsmith.storage.mysql import MySQLStorage
|
|
28
28
|
return MySQLStorage(url=database_url, pool_min=pool_min, pool_max=pool_max, pool_timeout=pool_timeout)
|
|
29
29
|
|
|
30
|
+
if database_url.startswith("sqlite://"):
|
|
31
|
+
from flowsmith.storage.sqlite import SQLiteStorage
|
|
32
|
+
return SQLiteStorage(url=database_url, pool_min=pool_min, pool_max=pool_max, pool_timeout=pool_timeout)
|
|
33
|
+
|
|
30
34
|
raise ValueError(
|
|
31
35
|
f"Unsupported database URL scheme: '{database_url.split('://')[0]}'\n"
|
|
32
|
-
"Supported: postgresql://, postgres://, mysql://"
|
|
36
|
+
"Supported: postgresql://, postgres://, mysql://, sqlite://"
|
|
33
37
|
)
|
|
34
38
|
|
|
35
39
|
|
|
@@ -44,9 +48,10 @@ def configure(
|
|
|
44
48
|
Call once at server startup.
|
|
45
49
|
|
|
46
50
|
Args:
|
|
47
|
-
database_url: PostgreSQL or
|
|
51
|
+
database_url: PostgreSQL, MySQL or SQLite connection string.
|
|
48
52
|
postgresql://user:password@host:port/dbname
|
|
49
53
|
mysql://user:password@host:port/dbname
|
|
54
|
+
sqlite:///path/to/file.db
|
|
50
55
|
pool_min: Minimum connections kept alive in the pool. Default 2.
|
|
51
56
|
pool_max: Maximum connections in the pool. Default 10.
|
|
52
57
|
pool_timeout: Seconds to wait for a connection before raising. Default 30.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS fs_flows (
|
|
2
|
+
id VARCHAR(255) NOT NULL PRIMARY KEY,
|
|
3
|
+
name VARCHAR(255) NOT NULL,
|
|
4
|
+
status VARCHAR(50) NOT NULL DEFAULT 'RUNNING',
|
|
5
|
+
input_data JSON NOT NULL,
|
|
6
|
+
output_data JSON,
|
|
7
|
+
error TEXT,
|
|
8
|
+
created_at DATETIME(6) NOT NULL DEFAULT NOW(6),
|
|
9
|
+
updated_at DATETIME(6) NOT NULL DEFAULT NOW(6) ON UPDATE NOW(6)
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
-- Create indexes only if they don't already exist
|
|
13
|
+
-- (MySQL does not support CREATE INDEX IF NOT EXISTS)
|
|
14
|
+
DROP PROCEDURE IF EXISTS fs_create_indexes_flows;
|
|
15
|
+
|
|
16
|
+
CREATE PROCEDURE fs_create_indexes_flows()
|
|
17
|
+
BEGIN
|
|
18
|
+
IF NOT EXISTS (
|
|
19
|
+
SELECT 1 FROM information_schema.statistics
|
|
20
|
+
WHERE table_schema = DATABASE()
|
|
21
|
+
AND table_name = 'fs_flows'
|
|
22
|
+
AND index_name = 'idx_fs_flows_status'
|
|
23
|
+
) THEN
|
|
24
|
+
CREATE INDEX idx_fs_flows_status ON fs_flows (status);
|
|
25
|
+
END IF;
|
|
26
|
+
|
|
27
|
+
IF NOT EXISTS (
|
|
28
|
+
SELECT 1 FROM information_schema.statistics
|
|
29
|
+
WHERE table_schema = DATABASE()
|
|
30
|
+
AND table_name = 'fs_flows'
|
|
31
|
+
AND index_name = 'idx_fs_flows_name'
|
|
32
|
+
) THEN
|
|
33
|
+
CREATE INDEX idx_fs_flows_name ON fs_flows (name);
|
|
34
|
+
END IF;
|
|
35
|
+
END;
|
|
36
|
+
|
|
37
|
+
CALL fs_create_indexes_flows();
|
|
38
|
+
DROP PROCEDURE IF EXISTS fs_create_indexes_flows;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS fs_nodes (
|
|
2
|
+
id VARCHAR(36) NOT NULL PRIMARY KEY DEFAULT (UUID()),
|
|
3
|
+
flow_id VARCHAR(255) NOT NULL,
|
|
4
|
+
step_name VARCHAR(255) NOT NULL,
|
|
5
|
+
status VARCHAR(50) NOT NULL DEFAULT 'RUNNING',
|
|
6
|
+
input_data JSON,
|
|
7
|
+
output_data JSON,
|
|
8
|
+
error TEXT,
|
|
9
|
+
attempt_count INT NOT NULL DEFAULT 1,
|
|
10
|
+
started_at DATETIME(6),
|
|
11
|
+
ended_at DATETIME(6),
|
|
12
|
+
|
|
13
|
+
CONSTRAINT fk_fs_nodes_flow
|
|
14
|
+
FOREIGN KEY (flow_id) REFERENCES fs_flows(id)
|
|
15
|
+
ON DELETE CASCADE,
|
|
16
|
+
|
|
17
|
+
CONSTRAINT uq_fs_nodes_flow_step
|
|
18
|
+
UNIQUE (flow_id, step_name)
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
-- Create indexes only if they don't already exist
|
|
22
|
+
DROP PROCEDURE IF EXISTS fs_create_indexes_nodes;
|
|
23
|
+
|
|
24
|
+
CREATE PROCEDURE fs_create_indexes_nodes()
|
|
25
|
+
BEGIN
|
|
26
|
+
IF NOT EXISTS (
|
|
27
|
+
SELECT 1 FROM information_schema.statistics
|
|
28
|
+
WHERE table_schema = DATABASE()
|
|
29
|
+
AND table_name = 'fs_nodes'
|
|
30
|
+
AND index_name = 'idx_fs_nodes_flow_id'
|
|
31
|
+
) THEN
|
|
32
|
+
CREATE INDEX idx_fs_nodes_flow_id ON fs_nodes (flow_id);
|
|
33
|
+
END IF;
|
|
34
|
+
|
|
35
|
+
IF NOT EXISTS (
|
|
36
|
+
SELECT 1 FROM information_schema.statistics
|
|
37
|
+
WHERE table_schema = DATABASE()
|
|
38
|
+
AND table_name = 'fs_nodes'
|
|
39
|
+
AND index_name = 'idx_fs_nodes_status'
|
|
40
|
+
) THEN
|
|
41
|
+
CREATE INDEX idx_fs_nodes_status ON fs_nodes (status);
|
|
42
|
+
END IF;
|
|
43
|
+
END;
|
|
44
|
+
|
|
45
|
+
CALL fs_create_indexes_nodes();
|
|
46
|
+
DROP PROCEDURE IF EXISTS fs_create_indexes_nodes;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS fs_flows (
|
|
2
|
+
id TEXT PRIMARY KEY, -- caller-supplied tracking_id
|
|
3
|
+
name TEXT NOT NULL, -- workflow name
|
|
4
|
+
status TEXT NOT NULL DEFAULT 'RUNNING', -- RUNNING | FAILED | COMPLETED
|
|
5
|
+
input_data JSONB NOT NULL DEFAULT '{}',
|
|
6
|
+
output_data JSONB,
|
|
7
|
+
error TEXT,
|
|
8
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
9
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
CREATE INDEX IF NOT EXISTS idx_fs_flows_status ON fs_flows (status);
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_fs_flows_name ON fs_flows (name);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS fs_nodes (
|
|
2
|
+
id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
|
3
|
+
flow_id TEXT NOT NULL REFERENCES fs_flows(id) ON DELETE CASCADE,
|
|
4
|
+
step_name TEXT NOT NULL,
|
|
5
|
+
status TEXT NOT NULL DEFAULT 'RUNNING', -- RUNNING | FAILED | COMPLETED
|
|
6
|
+
input_data JSONB,
|
|
7
|
+
output_data JSONB,
|
|
8
|
+
error TEXT,
|
|
9
|
+
attempt_count INT NOT NULL DEFAULT 1,
|
|
10
|
+
started_at TIMESTAMPTZ,
|
|
11
|
+
ended_at TIMESTAMPTZ,
|
|
12
|
+
|
|
13
|
+
-- Ensures only one node record per (flow, step) pair
|
|
14
|
+
CONSTRAINT uq_fs_nodes_flow_step UNIQUE (flow_id, step_name)
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
CREATE INDEX IF NOT EXISTS idx_fs_nodes_flow_id ON fs_nodes (flow_id);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS idx_fs_nodes_status ON fs_nodes (status);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS fs_flows (
|
|
2
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
3
|
+
name TEXT NOT NULL,
|
|
4
|
+
status TEXT NOT NULL DEFAULT 'RUNNING',
|
|
5
|
+
input_data TEXT NOT NULL,
|
|
6
|
+
output_data TEXT,
|
|
7
|
+
error TEXT,
|
|
8
|
+
created_at TEXT NOT NULL,
|
|
9
|
+
updated_at TEXT NOT NULL
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
CREATE INDEX IF NOT EXISTS idx_fs_flows_status ON fs_flows (status);
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_fs_flows_name ON fs_flows (name);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS fs_nodes (
|
|
2
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
3
|
+
flow_id TEXT NOT NULL,
|
|
4
|
+
step_name TEXT NOT NULL,
|
|
5
|
+
status TEXT NOT NULL DEFAULT 'RUNNING',
|
|
6
|
+
input_data TEXT,
|
|
7
|
+
output_data TEXT,
|
|
8
|
+
error TEXT,
|
|
9
|
+
attempt_count INTEGER NOT NULL DEFAULT 1,
|
|
10
|
+
started_at TEXT,
|
|
11
|
+
ended_at TEXT,
|
|
12
|
+
|
|
13
|
+
FOREIGN KEY (flow_id) REFERENCES fs_flows(id) ON DELETE CASCADE,
|
|
14
|
+
UNIQUE (flow_id, step_name)
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
CREATE INDEX IF NOT EXISTS idx_fs_nodes_flow_id ON fs_nodes (flow_id);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS idx_fs_nodes_status ON fs_nodes (status);
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import psycopg2
|
|
5
|
+
from dotenv import load_dotenv
|
|
6
|
+
from google import genai
|
|
7
|
+
from pgvector.psycopg2 import register_vector
|
|
8
|
+
|
|
9
|
+
# Rich UI Components (You were missing these!)
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.live import Live
|
|
12
|
+
from rich.markdown import Markdown
|
|
13
|
+
from rich.panel import Panel
|
|
14
|
+
from rich.prompt import Prompt
|
|
15
|
+
from sentence_transformers import SentenceTransformer
|
|
16
|
+
|
|
17
|
+
# Load environment variables
|
|
18
|
+
load_dotenv()
|
|
19
|
+
|
|
20
|
+
# Initialize the UI
|
|
21
|
+
console = Console()
|
|
22
|
+
console.print(Panel.fit("[bold blue]Starting FlowSmith RAG Engine...[/bold blue]", border_style="blue"))
|
|
23
|
+
|
|
24
|
+
# 1. Initialize Clients
|
|
25
|
+
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
|
|
26
|
+
model_name = "gemini-3.5-flash"
|
|
27
|
+
|
|
28
|
+
with console.status("[bold green]Loading Embedding Model...", spinner="dots"):
|
|
29
|
+
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
|
30
|
+
|
|
31
|
+
with console.status("[bold green]Connecting to PostgreSQL...", spinner="dots"):
|
|
32
|
+
conn = psycopg2.connect(
|
|
33
|
+
dbname="postgres", user="postgres", password="postgres",
|
|
34
|
+
host="localhost", port="5432"
|
|
35
|
+
)
|
|
36
|
+
register_vector(conn)
|
|
37
|
+
|
|
38
|
+
def reformulate_query(current_query: str, history: list[tuple[str, str]]) -> str:
|
|
39
|
+
# Only keep the last 3 turns to save tokens and keep context relevant
|
|
40
|
+
history_text = "\n".join([f"User: {q}\nAI: {a}" for q, a in history[-3:]])
|
|
41
|
+
|
|
42
|
+
prompt = f"""Rewrite the user's latest question into a standalone search query that contains all necessary context from the conversation history. Do not answer the question, just output the reformulated query string.
|
|
43
|
+
|
|
44
|
+
HISTORY:
|
|
45
|
+
{history_text}
|
|
46
|
+
|
|
47
|
+
LATEST QUESTION: {current_query}
|
|
48
|
+
STANDALONE QUERY:"""
|
|
49
|
+
|
|
50
|
+
response = client.models.generate_content(
|
|
51
|
+
model=model_name,
|
|
52
|
+
contents=prompt
|
|
53
|
+
)
|
|
54
|
+
return str(response.text).strip()
|
|
55
|
+
|
|
56
|
+
def ask_codebase(search_query: str, actual_query: str, history: list[tuple[str, str]]) -> Any:
|
|
57
|
+
# 1. Use the standalone search query for vector math
|
|
58
|
+
query_vector = embedding_model.encode(search_query).tolist()
|
|
59
|
+
|
|
60
|
+
cursor = conn.cursor()
|
|
61
|
+
cursor.execute(
|
|
62
|
+
"""
|
|
63
|
+
SELECT content
|
|
64
|
+
FROM codebase_vectors
|
|
65
|
+
ORDER BY embedding <=> %s::vector
|
|
66
|
+
LIMIT 10;
|
|
67
|
+
""",
|
|
68
|
+
(query_vector,)
|
|
69
|
+
)
|
|
70
|
+
results = cursor.fetchall()
|
|
71
|
+
cursor.close()
|
|
72
|
+
|
|
73
|
+
if not results:
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
retrieved_chunks = [row[0] for row in results]
|
|
77
|
+
context_string = "\n\n---\n\n".join(retrieved_chunks)
|
|
78
|
+
|
|
79
|
+
# 2. Format the history block
|
|
80
|
+
history_string = "No previous conversation."
|
|
81
|
+
if history:
|
|
82
|
+
history_string = "\n\n".join([f"USER: {q}\nAI: {a}" for q, a in history[-3:]])
|
|
83
|
+
|
|
84
|
+
# 3. Update the prompt to include both history and the actual question
|
|
85
|
+
prompt = f"""
|
|
86
|
+
You are an expert backend software engineer tool. Answer the user's question using the provided code snippets and conversation history.
|
|
87
|
+
|
|
88
|
+
CRITICAL INSTRUCTIONS FOR TONE AND STYLE:
|
|
89
|
+
1. Never open with introductory boilerplate phrases.
|
|
90
|
+
2. Lead immediately with substance.
|
|
91
|
+
3. Format your response using clean Markdown.
|
|
92
|
+
4. STRICTLY PROHIBITED: Do not use LaTeX formatting. Use standard programming operators (like >=, <=) or plain English text.
|
|
93
|
+
5. If the answer cannot be found in the context, state simply: "I cannot answer this based on the provided codebase context."
|
|
94
|
+
|
|
95
|
+
CONVERSATION HISTORY:
|
|
96
|
+
{history_string}
|
|
97
|
+
|
|
98
|
+
CODEBASE CONTEXT:
|
|
99
|
+
{context_string}
|
|
100
|
+
|
|
101
|
+
USER'S CURRENT QUESTION: {actual_query}
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
response_stream = client.models.generate_content_stream(
|
|
105
|
+
model=model_name,
|
|
106
|
+
contents=prompt
|
|
107
|
+
)
|
|
108
|
+
return response_stream
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
console.print("\n[bold green]✅ System Ready. Type 'exit' to quit.[/bold green]\n")
|
|
112
|
+
|
|
113
|
+
# Initialize the memory list
|
|
114
|
+
chat_history: list[tuple[str, str]] = []
|
|
115
|
+
|
|
116
|
+
while True:
|
|
117
|
+
user_query = Prompt.ask("[bold cyan]Ask FlowSmith[/bold cyan]")
|
|
118
|
+
|
|
119
|
+
if user_query.lower() in ['exit', 'quit']:
|
|
120
|
+
console.print("[bold yellow]Shutting down...[/bold yellow]")
|
|
121
|
+
break
|
|
122
|
+
|
|
123
|
+
with console.status("[bold purple]Searching codebase and thinking...", spinner="bouncingBar"):
|
|
124
|
+
|
|
125
|
+
# 1. Reformulate if we have history!
|
|
126
|
+
search_query = user_query
|
|
127
|
+
if chat_history:
|
|
128
|
+
search_query = reformulate_query(user_query, chat_history)
|
|
129
|
+
|
|
130
|
+
# 2. Pass all three variables to the codebase function
|
|
131
|
+
response_stream = ask_codebase(search_query, user_query, chat_history)
|
|
132
|
+
|
|
133
|
+
if response_stream is None:
|
|
134
|
+
console.print("[bold red]No relevant code found in the database.[/bold red]")
|
|
135
|
+
continue
|
|
136
|
+
|
|
137
|
+
stream_iterator = iter(response_stream)
|
|
138
|
+
try:
|
|
139
|
+
first_chunk = next(stream_iterator)
|
|
140
|
+
except StopIteration:
|
|
141
|
+
first_chunk = None
|
|
142
|
+
|
|
143
|
+
console.print("\n")
|
|
144
|
+
full_response = first_chunk.text if (first_chunk and first_chunk.text) else ""
|
|
145
|
+
|
|
146
|
+
with Live(
|
|
147
|
+
Panel(Markdown(full_response), title="[bold magenta]AI Response[/bold magenta]", border_style="magenta"),
|
|
148
|
+
console=console,
|
|
149
|
+
refresh_per_second=12
|
|
150
|
+
) as live:
|
|
151
|
+
for chunk in stream_iterator:
|
|
152
|
+
if chunk.text:
|
|
153
|
+
full_response += chunk.text
|
|
154
|
+
live.update(Panel(Markdown(full_response), title="[bold magenta]AI Response[/bold magenta]", border_style="magenta"))
|
|
155
|
+
|
|
156
|
+
console.print("\n")
|
|
157
|
+
|
|
158
|
+
# 3. Save the completed interaction to memory for the next loop
|
|
159
|
+
chat_history.append((user_query, full_response))
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import psycopg2
|
|
5
|
+
from dotenv import load_dotenv # Add this
|
|
6
|
+
from google import genai
|
|
7
|
+
from pgvector.psycopg2 import register_vector
|
|
8
|
+
|
|
9
|
+
# Rich UI Components
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.live import Live
|
|
12
|
+
from rich.markdown import Markdown
|
|
13
|
+
from rich.panel import Panel
|
|
14
|
+
from rich.prompt import Prompt
|
|
15
|
+
from sentence_transformers import SentenceTransformer
|
|
16
|
+
|
|
17
|
+
# Load environment variables from the .env file
|
|
18
|
+
load_dotenv()
|
|
19
|
+
|
|
20
|
+
# Initialize the UI
|
|
21
|
+
console = Console()
|
|
22
|
+
|
|
23
|
+
console.print(Panel.fit("[bold blue]Starting FlowSmith RAG Engine...[/bold blue]", border_style="blue"))
|
|
24
|
+
|
|
25
|
+
# 1. Initialize Clients
|
|
26
|
+
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
|
|
27
|
+
model_name = "gemini-3.5-flash"
|
|
28
|
+
|
|
29
|
+
with console.status("[bold green]Loading Embedding Model...", spinner="dots"):
|
|
30
|
+
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
|
31
|
+
|
|
32
|
+
with console.status("[bold green]Connecting to PostgreSQL...", spinner="dots"):
|
|
33
|
+
conn = psycopg2.connect(
|
|
34
|
+
dbname="postgres", user="postgres", password="postgres",
|
|
35
|
+
host="localhost", port="5432"
|
|
36
|
+
)
|
|
37
|
+
register_vector(conn)
|
|
38
|
+
|
|
39
|
+
def ask_codebase(query: str) -> Any:
|
|
40
|
+
# Embed the query
|
|
41
|
+
query_vector = embedding_model.encode(query).tolist()
|
|
42
|
+
|
|
43
|
+
# Search the database
|
|
44
|
+
cursor = conn.cursor()
|
|
45
|
+
cursor.execute(
|
|
46
|
+
"""
|
|
47
|
+
SELECT content
|
|
48
|
+
FROM codebase_vectors
|
|
49
|
+
ORDER BY embedding <=> %s::vector
|
|
50
|
+
LIMIT 10;
|
|
51
|
+
""",
|
|
52
|
+
(query_vector,)
|
|
53
|
+
)
|
|
54
|
+
results = cursor.fetchall()
|
|
55
|
+
cursor.close()
|
|
56
|
+
|
|
57
|
+
# Handle empty results
|
|
58
|
+
if not results:
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
# Construct the context payload
|
|
62
|
+
retrieved_chunks = [row[0] for row in results]
|
|
63
|
+
context_string = "\n\n---\n\n".join(retrieved_chunks)
|
|
64
|
+
|
|
65
|
+
prompt = f"""
|
|
66
|
+
You are an expert backend software engineer tool. Answer the user's question using the provided code snippets.
|
|
67
|
+
|
|
68
|
+
CRITICAL INSTRUCTIONS FOR TONE AND STYLE:
|
|
69
|
+
1. Never open with introductory boilerplate phrases like "Based on the provided code snippets...", "According to the context...", or "Here is an explanation...".
|
|
70
|
+
2. Lead immediately with substance, the direct answer, or the structural breakdown.
|
|
71
|
+
3. Format your response using clean Markdown (such as syntax-highlighted code blocks, bold key terms, and scannable bullet points).
|
|
72
|
+
4. STRICTLY PROHIBITED: Do not use LaTeX formatting, dollar signs ($), or math equation blocks (like \ge or \le). Instead, use standard programming operators (like >=, <=) or plain English text for comparisons.
|
|
73
|
+
5. If the answer cannot be found in the context, state simply: "I cannot answer this based on the provided codebase context."
|
|
74
|
+
|
|
75
|
+
CONTEXT:
|
|
76
|
+
{context_string}
|
|
77
|
+
|
|
78
|
+
USER QUESTION: {query}
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
# Return the stream iterator instead of the resolved string
|
|
82
|
+
response_stream = client.models.generate_content_stream(
|
|
83
|
+
model=model_name,
|
|
84
|
+
contents=prompt
|
|
85
|
+
)
|
|
86
|
+
return response_stream
|
|
87
|
+
|
|
88
|
+
if __name__ == "__main__":
|
|
89
|
+
console.print("\n[bold green]✅ System Ready. Type 'exit' to quit.[/bold green]\n")
|
|
90
|
+
|
|
91
|
+
while True:
|
|
92
|
+
# Styled user input prompt
|
|
93
|
+
user_query = Prompt.ask("[bold cyan]Ask FlowSmith[/bold cyan]")
|
|
94
|
+
|
|
95
|
+
if user_query.lower() in ['exit', 'quit']:
|
|
96
|
+
console.print("[bold yellow]Shutting down...[/bold yellow]")
|
|
97
|
+
break
|
|
98
|
+
|
|
99
|
+
# Show the spinner while querying Postgres AND waiting for the network
|
|
100
|
+
with console.status("[bold purple]Searching codebase and thinking...", spinner="bouncingBar"):
|
|
101
|
+
response_stream = ask_codebase(user_query)
|
|
102
|
+
|
|
103
|
+
if response_stream is None:
|
|
104
|
+
console.print("[bold red]No relevant code found in the database.[/bold red]")
|
|
105
|
+
continue
|
|
106
|
+
|
|
107
|
+
# Convert the stream into a manual iterator
|
|
108
|
+
stream_iterator = iter(response_stream)
|
|
109
|
+
|
|
110
|
+
# Force the program to wait here for the first network byte
|
|
111
|
+
# before letting the spinner disappear
|
|
112
|
+
try:
|
|
113
|
+
first_chunk = next(stream_iterator)
|
|
114
|
+
except StopIteration:
|
|
115
|
+
first_chunk = None
|
|
116
|
+
|
|
117
|
+
console.print("\n")
|
|
118
|
+
|
|
119
|
+
# Initialize the UI with that first chunk instead of an empty string
|
|
120
|
+
full_response = first_chunk.text if (first_chunk and first_chunk.text) else ""
|
|
121
|
+
|
|
122
|
+
# Open the Live rendering panel for the rest of the stream
|
|
123
|
+
with Live(
|
|
124
|
+
Panel(Markdown(full_response), title="[bold magenta]AI Response[/bold magenta]", border_style="magenta"),
|
|
125
|
+
console=console,
|
|
126
|
+
refresh_per_second=12
|
|
127
|
+
) as live:
|
|
128
|
+
|
|
129
|
+
# Stream the remaining chunks seamlessly
|
|
130
|
+
for chunk in stream_iterator:
|
|
131
|
+
if chunk.text:
|
|
132
|
+
full_response += chunk.text
|
|
133
|
+
# Instantly update the UI panel with the new text
|
|
134
|
+
live.update(Panel(Markdown(full_response), title="[bold magenta]AI Response[/bold magenta]", border_style="magenta"))
|
|
135
|
+
|
|
136
|
+
console.print("\n")
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from langchain_text_splitters import Language, RecursiveCharacterTextSplitter
|
|
5
|
+
|
|
6
|
+
# 1. The Python Parser
|
|
7
|
+
python_splitter = RecursiveCharacterTextSplitter.from_language(
|
|
8
|
+
language=Language.PYTHON, chunk_size=1500, chunk_overlap=100
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
# 2. The Generic Parser (For YAML, Dockerfile, txt, md)
|
|
12
|
+
generic_splitter = RecursiveCharacterTextSplitter(
|
|
13
|
+
chunk_size=1000, chunk_overlap=100
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
def chunk_codebase_professionally(filepath: str) -> Any:
|
|
17
|
+
with open(filepath, encoding="utf-8") as f:
|
|
18
|
+
content = f.read()
|
|
19
|
+
|
|
20
|
+
enriched_chunks = []
|
|
21
|
+
print(f"Processing {filepath}...")
|
|
22
|
+
|
|
23
|
+
# Route to the correct splitter based on file type
|
|
24
|
+
if filepath.endswith(".py"):
|
|
25
|
+
raw_chunks = python_splitter.create_documents([content])
|
|
26
|
+
|
|
27
|
+
for index, chunk in enumerate(raw_chunks):
|
|
28
|
+
text = chunk.page_content
|
|
29
|
+
current_class, current_function = "Global Scope", "Global Scope"
|
|
30
|
+
|
|
31
|
+
if class_match := re.search(r"class\s+(\w+)", text):
|
|
32
|
+
current_class = class_match.group(1)
|
|
33
|
+
if func_match := re.search(r"def\s+(\w+)", text):
|
|
34
|
+
current_function = func_match.group(1)
|
|
35
|
+
|
|
36
|
+
enriched_text = f"# File: {filepath}\n# Scope: Class {current_class} -> Function {current_function}\n{text}"
|
|
37
|
+
|
|
38
|
+
enriched_chunks.append({
|
|
39
|
+
"file_path": filepath, "class_name": current_class,
|
|
40
|
+
"function_name": current_function, "chunk_index": index,
|
|
41
|
+
"content": enriched_text
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
else:
|
|
45
|
+
# For YAML, Dockerfiles, and Requirements
|
|
46
|
+
raw_chunks = generic_splitter.create_documents([content])
|
|
47
|
+
|
|
48
|
+
for index, chunk in enumerate(raw_chunks):
|
|
49
|
+
enriched_text = f"# Configuration File: {filepath}\n\n{chunk.page_content}"
|
|
50
|
+
|
|
51
|
+
enriched_chunks.append({
|
|
52
|
+
"file_path": filepath,
|
|
53
|
+
"class_name": "Config",
|
|
54
|
+
"function_name": "Config",
|
|
55
|
+
"chunk_index": index,
|
|
56
|
+
"content": enriched_text
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
return enriched_chunks
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import psycopg2
|
|
4
|
+
from index_enriched import chunk_codebase_professionally
|
|
5
|
+
from pgvector.psycopg2 import register_vector
|
|
6
|
+
from sentence_transformers import SentenceTransformer
|
|
7
|
+
|
|
8
|
+
# 1. Updated Configuration
|
|
9
|
+
REPO_ROOT = "."
|
|
10
|
+
IGNORE_DIRS = {".git", "__pycache__", ".venv", "venv", "node_modules"}
|
|
11
|
+
ALLOWED_EXTENSIONS = {".py", ".txt", ".yml", ".yaml", ".md"}
|
|
12
|
+
ALLOWED_FILENAMES = {"Dockerfile"}
|
|
13
|
+
|
|
14
|
+
# 2. Find target files (now includes config files)
|
|
15
|
+
target_files = []
|
|
16
|
+
for root, dirs, files in os.walk(REPO_ROOT):
|
|
17
|
+
dirs[:] = [d for d in dirs if d not in IGNORE_DIRS]
|
|
18
|
+
for file in files:
|
|
19
|
+
if any(file.endswith(ext) for ext in ALLOWED_EXTENSIONS) or file in ALLOWED_FILENAMES:
|
|
20
|
+
target_files.append(os.path.join(root, file))
|
|
21
|
+
|
|
22
|
+
print(f"🔍 Found {len(target_files)} files to vectorize.")
|
|
23
|
+
|
|
24
|
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
|
25
|
+
conn = psycopg2.connect(
|
|
26
|
+
dbname="postgres", user="postgres", password="postgres", host="localhost", port="5432"
|
|
27
|
+
)
|
|
28
|
+
register_vector(conn)
|
|
29
|
+
cursor = conn.cursor()
|
|
30
|
+
|
|
31
|
+
# 3. Prevent Duplication! Wipe the table before inserting.
|
|
32
|
+
print("🧹 Clearing old vectors from the database...")
|
|
33
|
+
cursor.execute("TRUNCATE TABLE codebase_vectors;")
|
|
34
|
+
conn.commit()
|
|
35
|
+
|
|
36
|
+
# 4. Process and Insert
|
|
37
|
+
total_chunks_processed = 0
|
|
38
|
+
for filepath in target_files:
|
|
39
|
+
chunks = chunk_codebase_professionally(filepath)
|
|
40
|
+
if not chunks:
|
|
41
|
+
continue
|
|
42
|
+
|
|
43
|
+
for chunk in chunks:
|
|
44
|
+
embedding = model.encode(chunk["content"]).tolist()
|
|
45
|
+
cursor.execute(
|
|
46
|
+
"""
|
|
47
|
+
INSERT INTO codebase_vectors
|
|
48
|
+
(file_path, class_name, function_name, chunk_index, content, embedding)
|
|
49
|
+
VALUES (%s, %s, %s, %s, %s, %s)
|
|
50
|
+
""",
|
|
51
|
+
(chunk["file_path"], chunk["class_name"], chunk["function_name"],
|
|
52
|
+
chunk["chunk_index"], chunk["content"], embedding)
|
|
53
|
+
)
|
|
54
|
+
total_chunks_processed += 1
|
|
55
|
+
|
|
56
|
+
conn.commit()
|
|
57
|
+
cursor.close()
|
|
58
|
+
conn.close()
|
|
59
|
+
|
|
60
|
+
print(f"✅ Successfully wiped old data and indexed {total_chunks_processed} chunks across {len(target_files)} files!")
|
|
@@ -2,5 +2,6 @@ from .base import StorageBackend
|
|
|
2
2
|
from .memory import InMemoryStorage
|
|
3
3
|
from .mysql import MySQLStorage
|
|
4
4
|
from .postgres import PostgresStorage
|
|
5
|
+
from .sqlite import SQLiteStorage
|
|
5
6
|
|
|
6
|
-
__all__ = ["StorageBackend", "InMemoryStorage", "MySQLStorage", "PostgresStorage"]
|
|
7
|
+
__all__ = ["StorageBackend", "InMemoryStorage", "MySQLStorage", "PostgresStorage", "SQLiteStorage"]
|
|
@@ -24,6 +24,18 @@ def _from_json(data: Any) -> Any:
|
|
|
24
24
|
return json.loads(data)
|
|
25
25
|
|
|
26
26
|
|
|
27
|
+
def _postgres_url(url: str) -> str:
|
|
28
|
+
"""
|
|
29
|
+
Pin the SQLAlchemy dialect to psycopg2.
|
|
30
|
+
Newer SQLAlchemy defaults a bare postgresql:// URL to psycopg (v3), and
|
|
31
|
+
does not accept postgres:// at all.
|
|
32
|
+
"""
|
|
33
|
+
for prefix in ("postgresql://", "postgres://"):
|
|
34
|
+
if url.startswith(prefix):
|
|
35
|
+
return "postgresql+psycopg2://" + url[len(prefix):]
|
|
36
|
+
return url
|
|
37
|
+
|
|
38
|
+
|
|
27
39
|
class PostgresStorage(StorageBackend):
|
|
28
40
|
"""
|
|
29
41
|
PostgreSQL storage backend using SQLAlchemy connection pooling.
|
|
@@ -56,7 +68,7 @@ class PostgresStorage(StorageBackend):
|
|
|
56
68
|
) from err
|
|
57
69
|
|
|
58
70
|
return create_engine(
|
|
59
|
-
url,
|
|
71
|
+
_postgres_url(url),
|
|
60
72
|
pool_size=pool_min,
|
|
61
73
|
max_overflow=pool_max - pool_min,
|
|
62
74
|
pool_timeout=pool_timeout,
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import sqlite3
|
|
3
|
+
import threading
|
|
4
|
+
import uuid
|
|
5
|
+
from datetime import UTC, datetime, timedelta
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from flowsmith.models import FlowRecord, NodeRecord
|
|
9
|
+
from flowsmith.storage.base import StorageBackend
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _now() -> datetime:
|
|
13
|
+
"""Always return timezone-aware UTC datetime."""
|
|
14
|
+
return datetime.now(UTC)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _ts(dt: datetime) -> str:
|
|
18
|
+
return dt.isoformat()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _parse_ts(value: str | None) -> datetime | None:
|
|
22
|
+
return None if value is None else datetime.fromisoformat(value)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _to_json(data: Any) -> str | None:
|
|
26
|
+
return json.dumps(data) if data is not None else None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _from_json(data: str | None) -> Any:
|
|
30
|
+
return None if data is None else json.loads(data)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def sqlite_path(url: str) -> str:
|
|
34
|
+
"""
|
|
35
|
+
Extract the database path from a sqlite:// URL.
|
|
36
|
+
|
|
37
|
+
sqlite:///relative/path.db -> relative/path.db
|
|
38
|
+
sqlite:////absolute/path.db -> /absolute/path.db
|
|
39
|
+
sqlite:///:memory: -> :memory:
|
|
40
|
+
"""
|
|
41
|
+
for prefix in ("sqlite:///", "sqlite://"):
|
|
42
|
+
if url.startswith(prefix):
|
|
43
|
+
return url[len(prefix):] or ":memory:"
|
|
44
|
+
return url
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SQLiteStorage(StorageBackend):
|
|
48
|
+
"""
|
|
49
|
+
SQLite storage backend using the standard library sqlite3 module.
|
|
50
|
+
|
|
51
|
+
No extra dependencies. Intended for local development, tests and
|
|
52
|
+
single-process deployments. A single connection is shared and guarded
|
|
53
|
+
by a lock, so it is safe to use from multiple threads (including the
|
|
54
|
+
watchdog). pool_* arguments are accepted for interface parity with the
|
|
55
|
+
other backends and ignored.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
url: str,
|
|
61
|
+
pool_min: int = 2,
|
|
62
|
+
pool_max: int = 10,
|
|
63
|
+
pool_timeout: int = 30,
|
|
64
|
+
):
|
|
65
|
+
self._url = url
|
|
66
|
+
self._lock = threading.RLock()
|
|
67
|
+
self._conn = sqlite3.connect(
|
|
68
|
+
sqlite_path(url),
|
|
69
|
+
timeout=pool_timeout,
|
|
70
|
+
check_same_thread=False,
|
|
71
|
+
)
|
|
72
|
+
self._conn.row_factory = sqlite3.Row
|
|
73
|
+
self._conn.execute("PRAGMA foreign_keys = ON")
|
|
74
|
+
|
|
75
|
+
def close(self) -> None:
|
|
76
|
+
with self._lock:
|
|
77
|
+
self._conn.close()
|
|
78
|
+
|
|
79
|
+
def _execute(self, sql: str, params: tuple[Any, ...] = ()) -> list[sqlite3.Row]:
|
|
80
|
+
with self._lock:
|
|
81
|
+
try:
|
|
82
|
+
rows = self._conn.execute(sql, params).fetchall()
|
|
83
|
+
self._conn.commit()
|
|
84
|
+
except Exception:
|
|
85
|
+
self._conn.rollback()
|
|
86
|
+
raise
|
|
87
|
+
return rows
|
|
88
|
+
|
|
89
|
+
# -------------------------------------------------------------------------
|
|
90
|
+
# Flow operations
|
|
91
|
+
# -------------------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
def get_flow(self, tracking_id: str) -> FlowRecord | None:
|
|
94
|
+
rows = self._execute("SELECT * FROM fs_flows WHERE id = ?", (tracking_id,))
|
|
95
|
+
return self._row_to_flow(rows[0]) if rows else None
|
|
96
|
+
|
|
97
|
+
def create_flow(self, tracking_id: str, name: str, input_data: dict[str, Any]) -> FlowRecord:
|
|
98
|
+
now = _now()
|
|
99
|
+
self._execute(
|
|
100
|
+
"INSERT INTO fs_flows (id, name, status, input_data, created_at, updated_at) "
|
|
101
|
+
"VALUES (?, ?, 'RUNNING', ?, ?, ?)",
|
|
102
|
+
(tracking_id, name, _to_json(input_data), _ts(now), _ts(now)),
|
|
103
|
+
)
|
|
104
|
+
return FlowRecord(id=tracking_id, name=name, status="RUNNING",
|
|
105
|
+
input_data=input_data, created_at=now, updated_at=now)
|
|
106
|
+
|
|
107
|
+
def complete_flow(self, flow_id: str, output_data: dict[str, Any]) -> None:
|
|
108
|
+
self._execute(
|
|
109
|
+
"UPDATE fs_flows SET status='COMPLETED', output_data=?, updated_at=? WHERE id=?",
|
|
110
|
+
(_to_json(output_data), _ts(_now()), flow_id),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def fail_flow(self, flow_id: str, error: str) -> None:
|
|
114
|
+
self._execute(
|
|
115
|
+
"UPDATE fs_flows SET status='FAILED', error=?, updated_at=? WHERE id=?",
|
|
116
|
+
(error, _ts(_now()), flow_id),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# -------------------------------------------------------------------------
|
|
120
|
+
# Node operations
|
|
121
|
+
# -------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
def get_node(self, flow_id: str, step_name: str) -> NodeRecord | None:
|
|
124
|
+
rows = self._execute(
|
|
125
|
+
"SELECT * FROM fs_nodes WHERE flow_id=? AND step_name=?",
|
|
126
|
+
(flow_id, step_name),
|
|
127
|
+
)
|
|
128
|
+
return self._row_to_node(rows[0]) if rows else None
|
|
129
|
+
|
|
130
|
+
def start_node(self, flow_id: str, step_name: str, input_data: dict[str, Any]) -> NodeRecord:
|
|
131
|
+
with self._lock:
|
|
132
|
+
self._execute(
|
|
133
|
+
"""
|
|
134
|
+
INSERT INTO fs_nodes (id, flow_id, step_name, status, input_data, attempt_count, started_at)
|
|
135
|
+
VALUES (?, ?, ?, 'RUNNING', ?, 1, ?)
|
|
136
|
+
ON CONFLICT (flow_id, step_name) DO UPDATE SET
|
|
137
|
+
status='RUNNING', input_data=excluded.input_data,
|
|
138
|
+
attempt_count=attempt_count+1, started_at=excluded.started_at,
|
|
139
|
+
output_data=NULL, error=NULL, ended_at=NULL
|
|
140
|
+
""",
|
|
141
|
+
(str(uuid.uuid4()), flow_id, step_name, _to_json(input_data), _ts(_now())),
|
|
142
|
+
)
|
|
143
|
+
node = self.get_node(flow_id, step_name)
|
|
144
|
+
assert node is not None
|
|
145
|
+
return node
|
|
146
|
+
|
|
147
|
+
def complete_node(self, flow_id: str, step_name: str, output_data: dict[str, Any]) -> None:
|
|
148
|
+
self._execute(
|
|
149
|
+
"UPDATE fs_nodes SET status='COMPLETED', output_data=?, ended_at=? "
|
|
150
|
+
"WHERE flow_id=? AND step_name=?",
|
|
151
|
+
(_to_json(output_data), _ts(_now()), flow_id, step_name),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
def fail_node(self, flow_id: str, step_name: str, error: str, attempt: int) -> None:
|
|
155
|
+
self._execute(
|
|
156
|
+
"UPDATE fs_nodes SET status='FAILED', error=?, attempt_count=?, ended_at=? "
|
|
157
|
+
"WHERE flow_id=? AND step_name=?",
|
|
158
|
+
(error, attempt, _ts(_now()), flow_id, step_name),
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def get_stuck_nodes(self, timeout_seconds: int) -> list[NodeRecord]:
|
|
162
|
+
# Timestamps are stored as UTC ISO-8601 strings, which sort lexicographically.
|
|
163
|
+
cutoff = _ts(_now() - timedelta(seconds=timeout_seconds))
|
|
164
|
+
rows = self._execute(
|
|
165
|
+
"SELECT * FROM fs_nodes WHERE status='RUNNING' AND started_at < ?",
|
|
166
|
+
(cutoff,),
|
|
167
|
+
)
|
|
168
|
+
return [self._row_to_node(row) for row in rows]
|
|
169
|
+
|
|
170
|
+
# -------------------------------------------------------------------------
|
|
171
|
+
# Row mappers
|
|
172
|
+
# -------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
def _row_to_flow(self, row: sqlite3.Row) -> FlowRecord:
|
|
175
|
+
return FlowRecord(
|
|
176
|
+
id=row["id"], name=row["name"], status=row["status"],
|
|
177
|
+
input_data=_from_json(row["input_data"]),
|
|
178
|
+
output_data=_from_json(row["output_data"]),
|
|
179
|
+
error=row["error"],
|
|
180
|
+
created_at=_parse_ts(row["created_at"]),
|
|
181
|
+
updated_at=_parse_ts(row["updated_at"]),
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def _row_to_node(self, row: sqlite3.Row) -> NodeRecord:
|
|
185
|
+
return NodeRecord(
|
|
186
|
+
id=row["id"], flow_id=row["flow_id"], step_name=row["step_name"],
|
|
187
|
+
status=row["status"], input_data=_from_json(row["input_data"]),
|
|
188
|
+
output_data=_from_json(row["output_data"]), error=row["error"],
|
|
189
|
+
attempt_count=row["attempt_count"],
|
|
190
|
+
started_at=_parse_ts(row["started_at"]),
|
|
191
|
+
ended_at=_parse_ts(row["ended_at"]),
|
|
192
|
+
)
|
|
@@ -20,11 +20,22 @@ flowsmith.egg-info/requires.txt
|
|
|
20
20
|
flowsmith.egg-info/top_level.txt
|
|
21
21
|
flowsmith/contrib/__init__.py
|
|
22
22
|
flowsmith/migrations/__init__.py
|
|
23
|
+
flowsmith/migrations/mysql/001_create_flows.sql
|
|
24
|
+
flowsmith/migrations/mysql/002_create_nodes.sql
|
|
25
|
+
flowsmith/migrations/postgres/001_create_flows.sql
|
|
26
|
+
flowsmith/migrations/postgres/002_create_nodes.sql
|
|
27
|
+
flowsmith/migrations/sqlite/001_create_flows.sql
|
|
28
|
+
flowsmith/migrations/sqlite/002_create_nodes.sql
|
|
23
29
|
flowsmith/models/__init__.py
|
|
24
30
|
flowsmith/models/flow_record.py
|
|
25
31
|
flowsmith/models/node_record.py
|
|
32
|
+
flowsmith/scripts/rag_pipeline/chat.py
|
|
33
|
+
flowsmith/scripts/rag_pipeline/cli.py
|
|
34
|
+
flowsmith/scripts/rag_pipeline/index_enriched.py
|
|
35
|
+
flowsmith/scripts/rag_pipeline/store_vectors.py
|
|
26
36
|
flowsmith/storage/__init__.py
|
|
27
37
|
flowsmith/storage/base.py
|
|
28
38
|
flowsmith/storage/memory.py
|
|
29
39
|
flowsmith/storage/mysql.py
|
|
30
|
-
flowsmith/storage/postgres.py
|
|
40
|
+
flowsmith/storage/postgres.py
|
|
41
|
+
flowsmith/storage/sqlite.py
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "flowsmith"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.0"
|
|
8
8
|
description = "Lightweight durable workflow execution for Python backends"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -48,6 +48,9 @@ flowsmith = "flowsmith.__main__:main"
|
|
|
48
48
|
where = ["."]
|
|
49
49
|
include = ["flowsmith*"]
|
|
50
50
|
|
|
51
|
+
[tool.setuptools.package-data]
|
|
52
|
+
flowsmith = ["migrations/**/*.sql"]
|
|
53
|
+
|
|
51
54
|
# ---------------------------------------------------------------------------
|
|
52
55
|
# pytest
|
|
53
56
|
# ---------------------------------------------------------------------------
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|