deeplyzer 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +115 -3
- package/deepAnalysis/exec/buildCode.js +17 -0
- package/deepAnalysis/exec/execCommand.js +65 -0
- package/deepAnalysis/exec/planExecutor.js +34 -0
- package/deepAnalysis/orchestrator.js +43 -0
- package/deepAnalysis/plan/infraAnalysisPlanner.js +45 -0
- package/deepAnalysis/plan/workflowAnalysisPlanner.js +7 -0
- package/engine.js +50 -0
- package/img/a_clean_infographic_on_white_background_a_horizon.png +0 -0
- package/index.js +41 -0
- package/llm/llm.js +58 -0
- package/llm/providers/claude.js +65 -0
- package/llm/providers/gemini.js +66 -0
- package/llm/providers/openai.js +91 -0
- package/package.json +19 -4
- package/prompts/build_nodes +551 -0
- package/prompts/check_exit +25 -0
- package/prompts/infra_plan +483 -0
- package/prompts/resolve_edges +44 -0
- package/prompts/static_analysis +58 -0
- package/services/graphService.js +269 -0
- package/services/staticAnalyzerService.js +84 -0
- package/services/workflowService.js +56 -0
- package/utils/fileUtil.js +223 -0
- package/utils/idUtil.js +17 -0
- package/utils/promptsUtil.js +29 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AreteQA
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,115 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# Deeplyzer
|
|
2
|
+
|
|
3
|
+
### Deep analysis of software beyond static code analysis.
|
|
4
|
+
|
|
5
|
+
## The Problem
|
|
6
|
+
|
|
7
|
+
Software failures are rarely limited to bugs in source code.
|
|
8
|
+
|
|
9
|
+
An application can fail for thousands of reasons across its code, infrastructure, dependencies, and runtime environment.
|
|
10
|
+
|
|
11
|
+
Consider a few examples:
|
|
12
|
+
|
|
13
|
+
- **Configuration issues:** Missing environment variables, incorrect configurations, invalid credentials.
|
|
14
|
+
- **Network issues:** Connectivity failures, DNS resolution, firewall restrictions, API timeouts.
|
|
15
|
+
- **Database issues:** Invalid schemas, unexpected data formats, missing tables, permission issues, connection failures.
|
|
16
|
+
- **Infrastructure issues:** Misconfigured cloud resources, insufficient permissions, resource limits, incorrect deployment configurations.
|
|
17
|
+
- **Workflow issues:** Broken execution paths, unexpected dependencies, incorrect assumptions between components.
|
|
18
|
+
- **Integration issues:** Incompatible API responses, third-party service failures, version mismatches.
|
|
19
|
+
- **Runtime issues:** Memory exhaustion, concurrency problems, unhandled exceptions, resource leaks.
|
|
20
|
+
|
|
21
|
+
The possibilities run into thousands.
|
|
22
|
+
|
|
23
|
+
This makes traditional validation approaches insufficient. It is practically impossible to anticipate every failure scenario and build a fixed set of algorithms or rules to validate them all.
|
|
24
|
+
|
|
25
|
+
## The Solution: Deeplyzer
|
|
26
|
+
|
|
27
|
+
Deeplyzer takes a fundamentally different approach to software analysis.
|
|
28
|
+
|
|
29
|
+
Instead of relying on predefined validation rules, it understands the application, discovers its dependencies, maps its workflows, and autonomously investigates potential failure scenarios.
|
|
30
|
+
|
|
31
|
+
### How It Works
|
|
32
|
+
|
|
33
|
+
1. **Builds Code Graphs**
|
|
34
|
+
|
|
35
|
+
Analyzes source code and creates semantic graphs representing classes, functions, variables, dependencies, and relationships across the codebase.
|
|
36
|
+
|
|
37
|
+
2. **Understands Application Workflows**
|
|
38
|
+
|
|
39
|
+
Connects the graphs to discover how different components interact and maps end-to-end execution workflows.
|
|
40
|
+
|
|
41
|
+
3. **Analyzes Infrastructure**
|
|
42
|
+
|
|
43
|
+
Discovers and understands the underlying infrastructure, including cloud resources, configurations, permissions, databases, and external dependencies.
|
|
44
|
+
|
|
45
|
+
4. **Plans Validations Autonomously**
|
|
46
|
+
|
|
47
|
+
Uses its understanding of the application and infrastructure to identify potential failure scenarios and formulate targeted validation plans.
|
|
48
|
+
|
|
49
|
+
5. **Generates Executable Checks**
|
|
50
|
+
|
|
51
|
+
Generates the necessary code, scripts, and commands to investigate the identified scenarios.
|
|
52
|
+
|
|
53
|
+
6. **Executes and Evaluates**
|
|
54
|
+
|
|
55
|
+
Executes the generated checks, evaluates the results, and determines whether the application and its underlying infrastructure behave as expected.
|
|
56
|
+
|
|
57
|
+
## Beyond Static Code Analysis
|
|
58
|
+
|
|
59
|
+
Traditional static analysis examines code against predefined rules and known patterns.
|
|
60
|
+
|
|
61
|
+
Deeplyzer goes further. It understands how the application works, investigates the environment it depends on, and actively validates whether the entire system can operate as expected.
|
|
62
|
+
|
|
63
|
+
**Deeplyzer doesn't just analyze code. It investigates how software can fail.**
|
|
64
|
+
|
|
65
|
+
## How Deeplyzer Works
|
|
66
|
+
|
|
67
|
+

|
|
68
|
+
|
|
69
|
+
## Installation
|
|
70
|
+
|
|
71
|
+
Install Deeplyzer using npm:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
npm install deeplyzer
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Configuration
|
|
78
|
+
|
|
79
|
+
Create a configuration file (e.g. `deeplyzer.json`) in your project root.
|
|
80
|
+
|
|
81
|
+
```json
|
|
82
|
+
{
|
|
83
|
+
"sources": [],
|
|
84
|
+
"source-exclusions": [],
|
|
85
|
+
"llm": {
|
|
86
|
+
"provider": "openai",
|
|
87
|
+
"model": "gpt-6.1-sol",
|
|
88
|
+
"apiKey": "<API key goes here>"
|
|
89
|
+
},
|
|
90
|
+
"build_graph": false,
|
|
91
|
+
"static_analysis": false,
|
|
92
|
+
"batch_size": 10
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Configuration Options
|
|
97
|
+
|
|
98
|
+
| Option | Required | Default | Description |
|
|
99
|
+
|---|---|---|---|
|
|
100
|
+
| `sources` | Yes | `[]` | Source files or directories to analyze. |
|
|
101
|
+
| `source-exclusions` | No | `[]` | Files or directories to exclude from analysis. |
|
|
102
|
+
| `llm.provider` | Yes | - | LLM provider (`openai`, `claude`, `gemini`). |
|
|
103
|
+
| `llm.model` | Yes | - | Model to use for analysis. |
|
|
104
|
+
| `llm.apiKey` | Yes | - | API key for the selected LLM provider. |
|
|
105
|
+
| `build_graph` | No | `true` | Build semantic code graphs. |
|
|
106
|
+
| `static_analysis` | No | `true` | Enable static code analysis. |
|
|
107
|
+
| `batch_size` | No | `10` | Number of sources processed in each batch. |
|
|
108
|
+
|
|
109
|
+
**Note:** `build_graph`, `static_analysis`, and `batch_size` are optional. If omitted, their default values are used.
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
Deeplyzer is open-source software licensed under the [MIT License](LICENSE).
|
|
114
|
+
|
|
115
|
+
You are free to use, modify, distribute, and use it commercially, subject to the terms of the license.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const LLM = require('../../llm/llm');
|
|
2
|
+
const FileUtil = require('../../utils/fileUtil');
|
|
3
|
+
|
|
4
|
+
class BuildCode {
|
|
5
|
+
constructor(config){
|
|
6
|
+
this.llm = new LLM(config.llm);
|
|
7
|
+
this.fileUtil = new FileUtil();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async build(prompt, id) {
|
|
11
|
+
const response = await this.llm.generate({ prompt: prompt, json: true });
|
|
12
|
+
|
|
13
|
+
this.fileUtil.saveCodeFiles(response, id);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
module.exports = BuildCode;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
|
|
2
|
+
const path = require("path");
|
|
3
|
+
const { exec } = require("child_process");
|
|
4
|
+
const util = require("util");
|
|
5
|
+
const fs = require("fs");
|
|
6
|
+
|
|
7
|
+
class ExecCommand {
|
|
8
|
+
constructor() {
|
|
9
|
+
this.baseDir = path.join(process.cwd(), ".deeplyzer");
|
|
10
|
+
this.execAsync = util.promisify(exec);
|
|
11
|
+
|
|
12
|
+
this.platform = process.platform;
|
|
13
|
+
this.shell = this.getShell();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
getShell() {
|
|
17
|
+
switch (this.platform) {
|
|
18
|
+
case "win32":
|
|
19
|
+
return "powershell.exe";
|
|
20
|
+
|
|
21
|
+
case "darwin":
|
|
22
|
+
return "/bin/zsh";
|
|
23
|
+
|
|
24
|
+
case "linux":
|
|
25
|
+
return "/bin/bash";
|
|
26
|
+
|
|
27
|
+
default:
|
|
28
|
+
throw new Error(
|
|
29
|
+
`Unsupported operating system: ${this.platform}`
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async exec(command, id) {
|
|
35
|
+
const cwd = path.join(this.baseDir, "src", id);
|
|
36
|
+
|
|
37
|
+
fs.mkdirSync(cwd, { recursive: true });
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
const { stdout, stderr } = await this.execAsync(command, {
|
|
41
|
+
cwd,
|
|
42
|
+
shell: this.shell,
|
|
43
|
+
windowsHide: true,
|
|
44
|
+
maxBuffer: 10 * 1024 * 1024
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
if (stdout) process.stdout.write(stdout);
|
|
48
|
+
if (stderr) process.stderr.write(stderr);
|
|
49
|
+
|
|
50
|
+
return { success: true, stdout, stderr };
|
|
51
|
+
|
|
52
|
+
} catch (error) {
|
|
53
|
+
console.error(`[COMMAND ERROR] ${error.message}`);
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
success: false,
|
|
57
|
+
stdout: error.stdout || "",
|
|
58
|
+
stderr: error.stderr || "",
|
|
59
|
+
error: error.message
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
module.exports = ExecCommand;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
const BuildCode = require('./buildCode');
|
|
2
|
+
const ExecCommand = require('./execCommand');
|
|
3
|
+
const IdUtil = require('../../utils/idUtil');
|
|
4
|
+
|
|
5
|
+
class PlanExecutor {
|
|
6
|
+
constructor(config) {
|
|
7
|
+
this.buildCode = new BuildCode(config);
|
|
8
|
+
this.execCommand = new ExecCommand();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async exec(plan) {
|
|
12
|
+
let responses = [];
|
|
13
|
+
|
|
14
|
+
for (const planItem of plan) {
|
|
15
|
+
const id = IdUtil.generate();
|
|
16
|
+
|
|
17
|
+
if (planItem.prompt && planItem.prompt != "") {
|
|
18
|
+
await this.buildCode.build(planItem.prompt, id);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (planItem.commands && planItem.commands.length > 0) {
|
|
22
|
+
for(const command of planItem.commands) {
|
|
23
|
+
const response = await this.execCommand.exec(command, id);
|
|
24
|
+
|
|
25
|
+
responses.push(response);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return responses;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
module.exports = PlanExecutor;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const WorkflowAnalysisPlanner = require('./plan/workflowAnalysisPlanner');
|
|
2
|
+
const PlanExecutor = require('./exec/planExecutor');
|
|
3
|
+
const InfraAnalysisPlanner = require('./plan/infraAnalysisPlanner');
|
|
4
|
+
|
|
5
|
+
class DeepAnalysisOrchestrator {
|
|
6
|
+
constructor(config) {
|
|
7
|
+
this.config = config;
|
|
8
|
+
this.planExecutor = new PlanExecutor(config);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async analyzeWorkflows(workflows) {
|
|
12
|
+
if(!workflows) return;
|
|
13
|
+
|
|
14
|
+
const planner = new WorkflowAnalysisPlanner();
|
|
15
|
+
for(const workflow of workflows) {
|
|
16
|
+
const plan = planner.plan(workflow);
|
|
17
|
+
|
|
18
|
+
await this.planExecutor.exec(plan);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async analyzeInfra(graphs) {
|
|
23
|
+
const planner = new InfraAnalysisPlanner(graphs, this.config);
|
|
24
|
+
planner.graphs = graphs;
|
|
25
|
+
|
|
26
|
+
let exit = false, count = 0, plan, responses;
|
|
27
|
+
while(!exit) {
|
|
28
|
+
console.log("Generating infra validation plan");
|
|
29
|
+
plan = await planner.plan(plan, responses);
|
|
30
|
+
|
|
31
|
+
console.log("Executing infra validations");
|
|
32
|
+
responses = await this.planExecutor.exec(plan);
|
|
33
|
+
|
|
34
|
+
console.log("Checking infra validation exit");
|
|
35
|
+
exit = planner.checkExit(plan, responses);
|
|
36
|
+
|
|
37
|
+
count = count + 1;
|
|
38
|
+
if(count > 3) break;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = DeepAnalysisOrchestrator;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
const PromptsUtil = require('../../utils/promptsUtil');
|
|
2
|
+
const LLM = require('../../llm/llm');
|
|
3
|
+
|
|
4
|
+
class InfraAnalysisPlanner {
|
|
5
|
+
constructor(graphs, config) {
|
|
6
|
+
this.graphs = graphs;
|
|
7
|
+
|
|
8
|
+
this.llm = new LLM(config.llm);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async plan(existingPlan, existingResponses) {
|
|
12
|
+
let infraInstructions = [];
|
|
13
|
+
for(const graph of this.graphs) {
|
|
14
|
+
if(graph.file.is_infra) {
|
|
15
|
+
infraInstructions.push(graph.file.content);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if(infraInstructions.length == 0) return null;
|
|
20
|
+
|
|
21
|
+
let prompt = PromptsUtil.read("infra_plan");
|
|
22
|
+
|
|
23
|
+
prompt = prompt.replaceAll("***INSTRUCTIONS***", infraInstructions.join("\n"));
|
|
24
|
+
prompt = prompt.replaceAll("***EXISTING_PLAN***", JSON.stringify(existingPlan ?? {}));
|
|
25
|
+
prompt = prompt.replaceAll("***EXISTING_RESPONSES***", JSON.stringify(existingResponses ?? {}));
|
|
26
|
+
|
|
27
|
+
const response = await this.llm.generate({ prompt: prompt });
|
|
28
|
+
|
|
29
|
+
return response;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async checkExit(responses) {
|
|
33
|
+
let prompt = PromptsUtil.read("check_exit");
|
|
34
|
+
|
|
35
|
+
prompt = prompt.replaceAll("***RESPONSES***", JSON.stringify(responses));
|
|
36
|
+
|
|
37
|
+
const response = await this.llm.generate({ prompt: prompt, text: true });
|
|
38
|
+
|
|
39
|
+
const exit = response?.trim().toUpperCase() === "TRUE";
|
|
40
|
+
|
|
41
|
+
return exit;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = InfraAnalysisPlanner;
|
package/engine.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const GraphService = require('./services/graphService');
|
|
2
|
+
const WorkflowService = require('./services/workflowService');
|
|
3
|
+
const StaticAnalyzerService = require('./services/staticAnalyzerService');
|
|
4
|
+
|
|
5
|
+
const DeepAnalysisOrchestrator = require('./deepAnalysis/orchestrator');
|
|
6
|
+
|
|
7
|
+
class Engine {
|
|
8
|
+
constructor(config = {}) {
|
|
9
|
+
this.config = config;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async run() {
|
|
13
|
+
try {
|
|
14
|
+
console.log("[ENGINE] Starting Deeplyzer...");
|
|
15
|
+
console.log("[ENGINE] Configuration loaded.");
|
|
16
|
+
|
|
17
|
+
// step 1: build graph
|
|
18
|
+
let graphs;
|
|
19
|
+
const graphService = new GraphService(this.config);
|
|
20
|
+
if (this.config.build_graph ?? true) {
|
|
21
|
+
graphs = await graphService.buildGraphs();
|
|
22
|
+
} else {
|
|
23
|
+
graphs = await graphService.loadGraphs();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
// step 2: build workflows
|
|
28
|
+
const workflowService = new WorkflowService();
|
|
29
|
+
const workflows = workflowService.build(graphs);
|
|
30
|
+
|
|
31
|
+
// step 3: perform static code analysis
|
|
32
|
+
if (this.config.static_analysis ?? true) {
|
|
33
|
+
const staticAnalyzerService = new StaticAnalyzerService(this.config);
|
|
34
|
+
await staticAnalyzerService.analyze(graphs, workflows);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
console.log("[ENGINE] Starting deep analysis...");
|
|
38
|
+
const orchestrator = new DeepAnalysisOrchestrator(this.config);
|
|
39
|
+
//await orchestrator.analyzeWorkflows(null);
|
|
40
|
+
await orchestrator.analyzeInfra(graphs);
|
|
41
|
+
|
|
42
|
+
console.log("[ENGINE] Execution completed.");
|
|
43
|
+
} catch (error) {
|
|
44
|
+
console.error("[ENGINE ERROR]", error);
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
module.exports = Engine;
|
|
Binary file
|
package/index.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
|
|
2
|
+
const Engine = require("./engine");
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
|
|
6
|
+
(async () => {
|
|
7
|
+
try {
|
|
8
|
+
const config = _loadConfig();
|
|
9
|
+
|
|
10
|
+
const engine = new Engine(config);
|
|
11
|
+
|
|
12
|
+
await engine.run();
|
|
13
|
+
|
|
14
|
+
} catch (error) {
|
|
15
|
+
console.error(`[ERROR] ${error.message}`);
|
|
16
|
+
process.exitCode = 1;
|
|
17
|
+
}
|
|
18
|
+
})();
|
|
19
|
+
|
|
20
|
+
function _loadConfig() {
|
|
21
|
+
const configPath = process.argv[2];
|
|
22
|
+
|
|
23
|
+
if (!configPath) {
|
|
24
|
+
throw new Error("Configuration file path is required.\nUsage: node index.js <config.json>");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const resolvedPath = path.resolve(configPath);
|
|
28
|
+
|
|
29
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
30
|
+
throw new Error(`Configuration file not found: ${resolvedPath}`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const configContent = fs.readFileSync(resolvedPath, "utf8");
|
|
34
|
+
const config = JSON.parse(configContent);
|
|
35
|
+
|
|
36
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
37
|
+
throw new Error("Configuration must be a valid JSON object.");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return config;
|
|
41
|
+
}
|
package/llm/llm.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
|
|
2
|
+
const OpenAIProvider = require("./providers/openai");
|
|
3
|
+
const ClaudeProvider = require("./providers/claude");
|
|
4
|
+
const GeminiProvider = require("./providers/gemini");
|
|
5
|
+
|
|
6
|
+
class LLM {
|
|
7
|
+
constructor(llmConfig = {}) {
|
|
8
|
+
const providers = {
|
|
9
|
+
openai: OpenAIProvider,
|
|
10
|
+
claude: ClaudeProvider,
|
|
11
|
+
gemini: GeminiProvider
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const Provider = providers[llmConfig.provider];
|
|
15
|
+
|
|
16
|
+
if (!Provider) {
|
|
17
|
+
throw new Error(`Unsupported LLM provider: ${llmConfig.provider}`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (!llmConfig.model || !llmConfig.apiKey) {
|
|
21
|
+
throw new Error("LLM model and API key are required.");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
this.llmConfig = llmConfig;
|
|
25
|
+
this.provider = new Provider(llmConfig);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async generate(options = {}) {
|
|
29
|
+
if (!options.prompt) {
|
|
30
|
+
throw new Error("Prompt is required.");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
const response = await this.provider.generate(options);
|
|
35
|
+
|
|
36
|
+
if(options.text) return response.text;
|
|
37
|
+
|
|
38
|
+
return this._parseJSON(response.text);
|
|
39
|
+
|
|
40
|
+
} catch (error) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`[${this.llmConfig.provider}] ${error.message}`
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
_parseJSON(text) {
|
|
48
|
+
return JSON.parse(
|
|
49
|
+
text
|
|
50
|
+
.replace(/^```json\s*/i, "")
|
|
51
|
+
.replace(/^```\s*/i, "")
|
|
52
|
+
.replace(/\s*```$/, "")
|
|
53
|
+
.trim()
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
module.exports = LLM;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
|
|
2
|
+
const axios = require("axios");
|
|
3
|
+
|
|
4
|
+
class ClaudeProvider {
|
|
5
|
+
constructor(llmConfig) {
|
|
6
|
+
this.llmConfig = llmConfig;
|
|
7
|
+
|
|
8
|
+
this.client = axios.create({
|
|
9
|
+
baseURL: "https://api.anthropic.com/v1",
|
|
10
|
+
headers: {
|
|
11
|
+
"x-api-key": llmConfig.apiKey,
|
|
12
|
+
"anthropic-version": "2023-06-01",
|
|
13
|
+
"Content-Type": "application/json"
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async generate(options) {
|
|
19
|
+
const payload = {
|
|
20
|
+
model: this.llmConfig.model,
|
|
21
|
+
messages: [
|
|
22
|
+
{
|
|
23
|
+
role: "user",
|
|
24
|
+
content: options.prompt
|
|
25
|
+
}
|
|
26
|
+
]
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
if (options.system) {
|
|
30
|
+
payload.system = options.system;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (options.temperature !== undefined) {
|
|
34
|
+
payload.temperature = options.temperature;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (options.json) {
|
|
38
|
+
payload.system = [
|
|
39
|
+
payload.system || "",
|
|
40
|
+
"Return only valid JSON. No markdown code fences."
|
|
41
|
+
].join("\n");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const { data } = await this.client.post("/messages", payload);
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
text: data.content
|
|
48
|
+
.filter(item => item.type === "text")
|
|
49
|
+
.map(item => item.text)
|
|
50
|
+
.join("\n"),
|
|
51
|
+
model: data.model,
|
|
52
|
+
provider: "claude",
|
|
53
|
+
usage: {
|
|
54
|
+
inputTokens: data.usage?.input_tokens || 0,
|
|
55
|
+
outputTokens: data.usage?.output_tokens || 0,
|
|
56
|
+
totalTokens:
|
|
57
|
+
(data.usage?.input_tokens || 0) +
|
|
58
|
+
(data.usage?.output_tokens || 0)
|
|
59
|
+
},
|
|
60
|
+
raw: data
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
module.exports = ClaudeProvider;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
|
|
2
|
+
const axios = require("axios");
|
|
3
|
+
|
|
4
|
+
class GeminiProvider {
|
|
5
|
+
constructor(llmConfig) {
|
|
6
|
+
this.llmConfig = llmConfig;
|
|
7
|
+
|
|
8
|
+
this.client = axios.create({
|
|
9
|
+
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
10
|
+
headers: {
|
|
11
|
+
Authorization: `Bearer ${llmConfig.apiKey}`,
|
|
12
|
+
"Content-Type": "application/json"
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async generate(options) {
|
|
18
|
+
const messages = [];
|
|
19
|
+
|
|
20
|
+
if (options.system) {
|
|
21
|
+
messages.push({
|
|
22
|
+
role: "system",
|
|
23
|
+
content: options.system
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
messages.push({
|
|
28
|
+
role: "user",
|
|
29
|
+
content: options.prompt
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const payload = {
|
|
33
|
+
model: this.llmConfig.model,
|
|
34
|
+
messages
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
if (options.temperature !== undefined) {
|
|
38
|
+
payload.temperature = options.temperature;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (options.json) {
|
|
42
|
+
payload.response_format = {
|
|
43
|
+
type: "json_object"
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const { data } = await this.client.post(
|
|
48
|
+
"/chat/completions",
|
|
49
|
+
payload
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
text: data.choices?.[0]?.message?.content || "",
|
|
54
|
+
model: data.model,
|
|
55
|
+
provider: "gemini",
|
|
56
|
+
usage: {
|
|
57
|
+
inputTokens: data.usage?.prompt_tokens || 0,
|
|
58
|
+
outputTokens: data.usage?.completion_tokens || 0,
|
|
59
|
+
totalTokens: data.usage?.total_tokens || 0
|
|
60
|
+
},
|
|
61
|
+
raw: data
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = GeminiProvider;
|