Skip to content

Commit

Permalink
release v0.0.6
Browse files Browse the repository at this point in the history
  • Loading branch information
xiv-bazed-ai committed Jan 27, 2024
1 parent f818efa commit 1ba8840
Show file tree
Hide file tree
Showing 25 changed files with 906 additions and 489 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,5 @@ dist
.pnp.*

.DS_Store
docs
docs
project
375 changes: 3 additions & 372 deletions LICENSE

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
To create a new Bazed.ai Agent Framework project, run the following command and follow the instructions:

```bash
npx @bazed/bazed init my-project
npx @xiv-bazed-ai/bazed-af init my-project
```

It will create `my-project` directory and set up a fresh Bazed.ai Agent Framework project there.
Expand Down
172 changes: 148 additions & 24 deletions bin/bazed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,23 @@ import prompts from "prompts";
import chalk from "chalk";
import { startServer } from "../src/server/server";
import dotenv from "dotenv";
import child_process from "child_process";
import axios from "axios";
import FormData from "form-data";
import { SingleBar, Presets } from "cli-progress";
dotenv.config();

const PACKAGE_PATH = Path.resolve(__dirname, "..");

// TODO: set this to NPM package name when published
const PACKAGE_NAME = PACKAGE_PATH;
const PACKAGE_NAME = "@xiv-bazed-ai/bazed-af";

const banner = () => {
console.log(`\n😎 ${chalk.yellow(`Bazed.ai Agent Framework`)} ${chalk.gray("v" + version)}\n`);
console.log(
`\n😎 ${chalk.yellow(`Bazed.ai Agent Framework`)} ${chalk.gray(
"v" + version
)}\n`
);
};

const outro = (pm: "yarn" | "npm", projectPath: string) => {
Expand All @@ -32,16 +40,16 @@ const outro = (pm: "yarn" | "npm", projectPath: string) => {
const relativeStep =
cdCommand.length === 0
? ""
: `${i++}. Change directory to your project folder:
: `${i++}. Enter your project directory:\n
${chalk.cyan(cdCommand)}\n`;

console.log(`🙌 ${chalk.yellow("You're all set!")}\n
Next steps:\n
console.log(`\n🙌 ${chalk.yellow("You're all set!")}\n
${chalk.bold("Next steps")}\n
${relativeStep}
${i++}. Set your OpenAI API key in the ${chalk.cyan(".env")} file.\n
${i++}. Install dependencies and run the development server:
${i++}. Install dependencies:\n
${chalk.cyan(installCommand)}\n
${i++}. Start the development server:
${i++}. Start the development server:\n
${chalk.cyan(runCommand)}\n`);
};

Expand Down Expand Up @@ -73,6 +81,40 @@ const copyTemplate = (
}
};

const copySrcTemplate = (
templateName: string,
targetPath: string,
variables: Record<string, string>
) => {
const templatePath = Path.join(PACKAGE_PATH, "templates", templateName);
let content = FS.readFileSync(templatePath, "utf-8");
for (const key in variables) {
content = content.replace(new RegExp(`${key}`, "g"), variables[key]);
}
FS.writeFileSync(targetPath, content);
};

const toPascalCase = (name: string): string => {
return name
.split("-")
.map((word) => word[0].toUpperCase() + word.slice(1))
.join("");
};

const toKebabCase = (name: string): string => {
return name
.split(/(?=[A-Z])/)
.map((word) => word.toLowerCase())
.join("-");
};

const toCamelCase = (name: string): string => {
return name
.split("-")
.map((word, i) => (i === 0 ? word : word[0].toUpperCase() + word.slice(1)))
.join("");
};

const program = new Command();

program
Expand Down Expand Up @@ -100,12 +142,12 @@ program

// if path doesn't exist, create it
if (!targetPathExists) {
console.log(`${chalk.blue(path)} doesn't exist.`);
console.log(`Directory ${chalk.blue(path)} doesn't exist.`);
const { ok } = await prompts({
type: "confirm",
name: "ok",
initial: true,
message: `Create ${chalk.blue(path)}?`,
message: `Create ${chalk.blue(path)} directory?`,
});
if (!ok) {
console.log("Aborting");
Expand All @@ -129,35 +171,56 @@ program
BAZED_PACKAGE: PACKAGE_NAME,
};
copyTemplate("project", fullPath, variables);

console.log(
"Initializing a new project at",
path,
process.cwd(),
options.name,
fullPath
);
outro("yarn", fullPath);
});

const commandNew = program
.command("new")
.description("Scaffold agents and tools");

const addExport = (path: string, name: string, importPath: string) => {
const content = FS.readFileSync(path, "utf-8");
const lines = content.split("\n");
const lastImport = lines.findIndex((line) => line.startsWith("import"));
lines.splice(lastImport + 1, 0, `import ${name} from "./${importPath}";`);

const exportIndex = lines.findIndex((line) => line.startsWith("export"));
lines.splice(exportIndex + 1, 0, ` ${name},`);

FS.writeFileSync(path, lines.join("\n"));
};

commandNew
.command("agent")
.argument("<name>", "Name of the new agent")
.argument("[type]", "Type of the new agent", "reactive")
.description("Scaffold a new agent")
.action(() => {
console.log("Creating new agent");
.action(async (name: string, type: string) => {
const fullPath = Path.join(
process.cwd(),
"agents",
toKebabCase(name) + ".ts"
);
copySrcTemplate(`agents/${type}.ts`, fullPath, {
Example: toPascalCase(name),
});
addExport(
Path.join(process.cwd(), "index.ts"),
toPascalCase(name),
`agents/${toKebabCase(name)}`
);
});

commandNew
.command("tool")
.argument("<name>", "Name of the new tool")
.description("Scaffold a new tool")
.action(() => {
console.log("Running a project");
.action((name: string) => {
const fullPath = Path.join(process.cwd(), "tools", toKebabCase(name));
const type = "tool";
copySrcTemplate(`tools/${type}.ts`, fullPath, {
ExampleAgent: toCamelCase(name),
});
});

program
Expand All @@ -175,11 +238,72 @@ program
});
});

program.command("platform").action(async (_options: object) => {
await startServer({
port: process.env.PORT ? parseInt(process.env.PORT) : 9000,
openaiApiKey: process.env.OPENAI_API_KEY || "",
imports: [],
platform: true,
});
});

program
.command("deploy")
.description("Deploy a project to Bazed.ai")
.action(() => {
console.log("Deploying project");
.description("Deploy a project to bazed.ai")
.action(async () => {
const progress = new SingleBar({});
try {
const path = process.cwd();
const distPath = Path.join(path, "dist");
if (!FS.existsSync(distPath)) {
console.log(
`No ${chalk.cyan("dist")} folder found in ${chalk.blue(
path
)}. Please build your project first.`
);
return;
}

// parse the package.json file
const packageJsonPath = Path.join(path, "package.json");
const packageJson = JSON.parse(FS.readFileSync(packageJsonPath, "utf-8"));
packageJson.dependencies.bazed = "../../dist";
// write the package.json file to dist
const distPackageJsonPath = Path.join(distPath, "package.json");
FS.writeFileSync(
distPackageJsonPath,
JSON.stringify(packageJson, null, 2)
);

console.log("Deploying project");
// zip the dist folder
const zipPath = Path.join(path, "dist.zip");
// invoke zip command with dist folder
const zipCommand = `zip -r ${zipPath} dist/*`;
child_process.execSync(zipCommand);
// upload to bazed.ai with axios
const url = "http://p.bazed.ai/deploy";
const formData = new FormData();
formData.append("file", FS.createReadStream(zipPath));
const headers = formData.getHeaders();

progress.start(100, 0);
const response = await axios.post(url, formData, {
headers,
onUploadProgress: (progressEvent) => {
if (progressEvent.total)
progress.update((100 * progressEvent.loaded) / progressEvent.total);
},
});
progress.stop();
// delete the zip file
FS.unlinkSync(zipPath);
// console.log(response.data);
console.log("Project deployed successfully");
} catch (e) {
progress.stop();
console.log(e);
}
});

program.parse(process.argv);
3 changes: 2 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ export * from "./src/logging";
export * from "./src/common";
export * from "./src/ledger";
export * from "./src/tool";
export * from "./src/agents/one-shot";
export * from "./src/agents/one-shot";
export * from "./src/agents/reactive";
24 changes: 17 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,30 +1,39 @@
{
"name": "bazed-af",
"version": "0.0.1",
"name": "@xiv-bazed-ai/bazed-af",
"version": "0.0.6",
"description": "Bazed.ai Agent Framework",
"main": "./dist/index.js",
"homepage": "https://bazed.ai",
"repository": "[email protected]:bazed-ai/bazed-af.git",
"author": "XIV <[email protected]>",
"license": "MPL-2.0",
"private": true,
"license": "UNLICENSED",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scope": "@xiv-bazed-ai",
"bin": {
"bazed": "./dist/bin/bazed.js"
},
"engines": {
"node": ">=20.0.0"
},
"scripts": {
"build": "tsc && cp -R templates dist/templates && chmod u+x dist/bin/bazed.js",
"build": "rm -rf dist && tsc && cp -R templates dist/templates && chmod u+x dist/bin/bazed.js",
"test": "jest --coverage",
"prepare": "husky install",
"docs": "typedoc --options typedoc.json",
"cli": "yarn build && node ./dist/bin/bazed.js",
"lint": "eslint --ext .ts src"
"lint": "eslint --ext .ts src",
"local": "yarn build && npm install -g .",
"package:publish": "yarn build && npm publish --access private"
},
"dependencies": {
"@fastify/middie": "^8.3.0",
"@fastify/multipart": "^8.1.0",
"axios": "^1.6.0",
"chalk": "=4.1.0",
"cli-progress": "^3.12.0",
"commander": "^11.1.0",
"dotenv": "^16.3.1",
"fastify": "^4.20.0",
Expand All @@ -44,6 +53,7 @@
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@types/cli-progress": "^3.11.5",
"@types/jest": "^29.5.6",
"@types/node": "^20.5.0",
"@types/prompts": "^2.4.9",
Expand Down
16 changes: 15 additions & 1 deletion src/agent.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import chalk from "chalk";
import {
ChildOf,
Conclusible,
Expand Down Expand Up @@ -119,6 +120,7 @@ export class BaseAgent<OptionsType extends AgentOptions, StateType, ResultType>
* @returns the final result of the agent's work
*/
async run(): Promise<ResultType> {
console.log("Agent", chalk.yellow(this.metadata.ID), chalk.blue("start"));
this.trace(`${this.metadata.ID} run started: ${this.metadata.topic}`);
this.state = await this.initialize(this.options);
this.trace("initialize finished", this.state);
Expand All @@ -133,6 +135,14 @@ export class BaseAgent<OptionsType extends AgentOptions, StateType, ResultType>
this.isActive = false;
this.result = await this.finalize(this.state);
this.conclude();
console.log(
"Agent",
chalk.yellow(this.metadata.ID),
chalk.green("done"),
chalk.gray(
`(took ${this.metadata.timing.elapsed.as("seconds").toFixed(2)}s)`
)
);
return this.result;
}

Expand Down Expand Up @@ -208,7 +218,6 @@ export class BaseAgent<OptionsType extends AgentOptions, StateType, ResultType>
throw new Error("Thread is complete");
}
const messages = thread.messages;

const response = await this.session.invokeModel(
this,
this.model,
Expand Down Expand Up @@ -336,6 +345,11 @@ export class BaseAgent<OptionsType extends AgentOptions, StateType, ResultType>
constructor: Constructor<T>,
options?: AgentOptions
): T {
console.log(
chalk.yellow(this.metadata.ID),
chalk.blue("spawn"),
constructor.name
);
return this.session.spawnAgent(constructor, options);
}

Expand Down
Loading

0 comments on commit 1ba8840

Please sign in to comment.