mirror of
https://github.com/tcsenpai/ollamagents.git
synced 2025-07-29 14:11:26 +00:00
first commit
This commit is contained in:
commit
a02bc41368
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
*.cast
|
||||
node_modules
|
||||
*.lock
|
||||
package-lock.json
|
||||
.env
|
7
LICENSE.md
Normal file
7
LICENSE.md
Normal file
@ -0,0 +1,7 @@
|
||||
Copyright 2024 tcsenpai
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
78
README.md
Normal file
78
README.md
Normal file
@ -0,0 +1,78 @@
|
||||
# OllamaAgents
|
||||
|
||||
OllamaAgents is a TypeScript-based CLI application that provides a Linux command interpreter using the Ollama API. It converts natural language queries into appropriate Linux commands, offering explanations and cautions when necessary.
|
||||
|
||||
## Features
|
||||
|
||||
- Convert natural language queries to Linux commands
|
||||
- Provide explanations for generated commands
|
||||
- Offer cautions for potentially dangerous operations
|
||||
- Colorful and interactive CLI interface
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js (version 14 or higher recommended)
|
||||
- Yarn package manager
|
||||
- Ollama API endpoint
|
||||
|
||||
## Installation
|
||||
|
||||
1. Clone the repository:
|
||||
```
|
||||
git clone https://github.com/yourusername/ollamagents.git
|
||||
cd ollamagents
|
||||
```
|
||||
|
||||
2. Install dependencies:
|
||||
```
|
||||
yarn install
|
||||
```
|
||||
|
||||
3. Create a `.env` file in the root directory and add your Ollama API URL:
|
||||
```
|
||||
OLLAMA_URL=http://your-ollama-api-url
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
To start the application, run:
|
||||
|
||||
```
|
||||
yarn start
|
||||
```
|
||||
|
||||
|
||||
Once started, you can enter natural language queries or commands. The application will interpret your input and provide the corresponding Linux command, along with an explanation and any necessary cautions.
|
||||
|
||||
Type 'exit' to quit the application.
|
||||
|
||||
## Development
|
||||
|
||||
This project uses TypeScript and is set up with TSX for running TypeScript files directly. The main entry point is `main.ts`.
|
||||
|
||||
To modify the system prompt or adjust the behavior of the Ollama API integration, refer to the `OllamaAPI` class in `ollamapi.ts`.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- tsx: For running TypeScript files directly
|
||||
- axios: HTTP client for making requests to the Ollama API
|
||||
- dotenv: For loading environment variables
|
||||
- readline: For reading input from the user
|
||||
- terminal-kit: For colorful CLI output
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License - see the LICENSE file for details.
|
||||
|
||||
## Author
|
||||
|
||||
tcsenpai <dev@tcsenpai.com>
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions, issues, and feature requests are welcome. Feel free to check issues page if you want to contribute.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
- Ollama for providing the underlying language model capabilities
|
||||
- The TypeScript and Node.js communities for their excellent tools and libraries
|
1
env.example
Normal file
1
env.example
Normal file
@ -0,0 +1 @@
|
||||
OLLAMA_URL=http://localhost:11434
|
61
main.ts
Normal file
61
main.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { OllamaAPI } from './ollamapi';
|
||||
import dotenv from 'dotenv';
|
||||
import readline from 'readline';
|
||||
import * as term from 'terminal-kit';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const ollama_url = process.env.OLLAMA_URL as string;
|
||||
const systemPrompt = `You are a Linux command interpreter. Your task is to convert natural language queries or commands into appropriate Linux commands. Always respond with a valid JSON object containing the following keys:
|
||||
1. 'command': The Linux command to execute (string). Double check the command to ensure it's correct and works.
|
||||
2. 'explanation': A brief explanation of what the command does (string).
|
||||
3. 'caution': Any warnings or cautions about using the command, if applicable (string or null).
|
||||
|
||||
Only provide existing and working Linux commands. If you cannot interpret the input or if it's not applicable to Linux, return a JSON object with an 'error' key explaining the issue. Do not include any text outside of the JSON structure in your response.
|
||||
|
||||
The produced JSON should be valid JSON that can be parsed by JSON.parse() in JavaScript, so it cannot contain \` or headers like \`\`\`json.`;
|
||||
const ollama = new OllamaAPI(ollama_url, 'llama3.1', systemPrompt);
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
|
||||
async function main() {
|
||||
term.terminal.bold.cyan('Welcome to the Linux Command Assistant. Type \'exit\' to quit.\n\n');
|
||||
|
||||
while (true) {
|
||||
term.terminal.green('Enter your command or question: \n');
|
||||
const input = await new Promise<string>(resolve => rl.question('', resolve));
|
||||
term.terminal('\n');
|
||||
|
||||
if (input.toLowerCase() === 'exit') {
|
||||
term.terminal.yellow('Goodbye!\n');
|
||||
rl.close();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
|
||||
const response = await ollama.chat(input);
|
||||
try {
|
||||
const parsedResponse = JSON.parse(response);
|
||||
|
||||
if (parsedResponse.error) {
|
||||
term.terminal.red('Error: ').white(parsedResponse.error + '\n');
|
||||
} else {
|
||||
term.terminal.bold.blue('Command: ').white(parsedResponse.command + '\n');
|
||||
term.terminal.bold.magenta('Explanation: ').white(parsedResponse.explanation + '\n');
|
||||
if (parsedResponse.caution) {
|
||||
term.terminal.bold.yellow('Caution: ').white(parsedResponse.caution + '\n');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
term.terminal.red('An error occurred: ').white((error as Error).message + '\n');
|
||||
term.terminal.red('Response: ').white(response + '\n');
|
||||
}
|
||||
|
||||
term.terminal('\n'); // Add a blank line for readability
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
69
ollamapi.ts
Normal file
69
ollamapi.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import axios from 'axios';
|
||||
|
||||
interface Message {
|
||||
role: 'system' | 'user' | 'assistant';
|
||||
content: string;
|
||||
}
|
||||
|
||||
export class OllamaAPI {
|
||||
private baseURL: string;
|
||||
private model: string;
|
||||
private memory: Message[] = [];
|
||||
private systemPrompt: string;
|
||||
|
||||
constructor(ollamaURL: string, model: string = 'llama2', systemPrompt: string = '') {
|
||||
this.baseURL = ollamaURL;
|
||||
this.model = model;
|
||||
this.systemPrompt = systemPrompt;
|
||||
if (systemPrompt) {
|
||||
this.memory.push({ role: 'system', content: systemPrompt });
|
||||
}
|
||||
}
|
||||
|
||||
async chat(prompt: string): Promise<string> {
|
||||
try {
|
||||
//this.memory.push({ role: 'user', content: prompt });
|
||||
let systemAndPrompt: Message[] = []
|
||||
systemAndPrompt.push({ role: 'system', content: this.systemPrompt })
|
||||
systemAndPrompt.push({ role: 'user', content: prompt })
|
||||
const response = await axios.post(`${this.baseURL}/api/chat`, {
|
||||
model: this.model,
|
||||
messages: systemAndPrompt,
|
||||
stream: false
|
||||
});
|
||||
const assistantResponse = response.data.message.content;
|
||||
//this.memory.push({ role: 'assistant', content: assistantResponse });
|
||||
return assistantResponse;
|
||||
} catch (error) {
|
||||
console.error('Error in chat:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async complete(prompt: string): Promise<string> {
|
||||
try {
|
||||
const fullPrompt = this.memory.map(m => `${m.role}: ${m.content}`).join('\n') + `\nuser: ${prompt}\nassistant:`;
|
||||
const response = await axios.post(`${this.baseURL}/api/generate`, {
|
||||
model: this.model,
|
||||
prompt: fullPrompt,
|
||||
stream: false
|
||||
});
|
||||
const assistantResponse = response.data.response;
|
||||
//this.memory.push({ role: 'user', content: prompt });
|
||||
//this.memory.push({ role: 'assistant', content: assistantResponse });
|
||||
return assistantResponse;
|
||||
} catch (error) {
|
||||
console.error('Error in complete:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
clearMemory() {
|
||||
this.memory = this.systemPrompt ? [{ role: 'system', content: this.systemPrompt }] : [];
|
||||
}
|
||||
|
||||
setSystemPrompt(prompt: string) {
|
||||
this.systemPrompt = prompt;
|
||||
this.clearMemory();
|
||||
}
|
||||
}
|
21
package.json
Normal file
21
package.json
Normal file
@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "ollamagents",
|
||||
"version": "1.0.0",
|
||||
"main": "main.ts",
|
||||
"author": "tcsenpai <dev@tcsenpai.com>",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"start": "tsx main.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.7.3",
|
||||
"dotenv": "^16.4.5",
|
||||
"terminal-kit": "^3.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.1.0",
|
||||
"@types/terminal-kit": "^2.5.6",
|
||||
"tsx": "^4.16.5",
|
||||
"typescript": "^5.0.0"
|
||||
}
|
||||
}
|
101
tsconfig.json
Normal file
101
tsconfig.json
Normal file
@ -0,0 +1,101 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Enable incremental compilation */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
|
||||
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
|
||||
/* Modules */
|
||||
"module": "commonjs", /* Specify what module code is generated. */
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files */
|
||||
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
|
||||
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
|
||||
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
|
||||
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user