Skip to content

Commit

Permalink
Merge pull request #1004 from Sifchain/realitySpiral/addExamples
Browse files Browse the repository at this point in the history
feat: create example folder with example plugin
  • Loading branch information
monilpat authored Dec 13, 2024
2 parents 2f56f37 + b6eac4e commit 5a3d348
Show file tree
Hide file tree
Showing 15 changed files with 410 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lerna.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "0.1.5-alpha.5",
"packages": ["packages/*", "docs", "agent", "client"],
"packages": ["packages/*", "docs", "agent", "client", "!packages/_examples"],
"npmClient": "pnpm"
}
6 changes: 6 additions & 0 deletions packages/_examples/plugin/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*

!dist/**
!package.json
!readme.md
!tsup.config.ts
32 changes: 32 additions & 0 deletions packages/_examples/plugin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Sample Plugin for Eliza

The Sample Plugin for Eliza extends the functionality of the Eliza platform by providing additional actions, providers, evaluators, and more. This plugin is designed to be easily extendable and customizable to fit various use cases.

## Description
The Sample Plugin offers a set of features that can be integrated into the Eliza platform to enhance its capabilities. Below is a high-level overview of the different components available in this plugin.

## Actions
- **createResourceAction**: This action enables the creation and management of generic resources. It can be customized to handle different types of resources and integrate with various data sources.

## Providers
- **sampleProvider**: This provider offers a mechanism to supply data or services to the plugin. It can be extended to include additional providers as needed.

## Evaluators
- **sampleEvaluator**: This evaluator provides a way to assess or analyze data within the plugin. It can be extended to include additional evaluators as needed.

## Services
- **[ServiceName]**: Description of the service and its functionality. This can be extended to include additional services as needed.

## Clients
- **[ClientName]**: Description of the client and its functionality. This can be extended to include additional clients as needed.

## How to Extend
To extend the Sample Plugin, you can add new actions, providers, evaluators, services, and clients by following the structure provided in the plugin. Each component can be customized to fit your specific requirements.

1. **Actions**: Add new actions by defining them in the `actions` array.
2. **Providers**: Add new providers by defining them in the `providers` array.
3. **Evaluators**: Add new evaluators by defining them in the `evaluators` array.
4. **Services**: Add new services by defining them in the `services` array.
5. **Clients**: Add new clients by defining them in the `clients` array.

For more detailed information on how to extend the plugin, refer to the documentation provided in the Eliza platform.
3 changes: 3 additions & 0 deletions packages/_examples/plugin/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import eslintGlobalConfig from "../../eslint.config.mjs";

export default [...eslintGlobalConfig];
19 changes: 19 additions & 0 deletions packages/_examples/plugin/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@ai16z/plugin-sample",
"version": "0.1.5-alpha.5",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"dependencies": {
"@ai16z/eliza": "workspace:*"
},
"devDependencies": {
"tsup": "8.3.5",
"@types/node": "^20.0.0"
},
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --format esm --dts --watch",
"lint": "eslint . --fix"
}
}
117 changes: 117 additions & 0 deletions packages/_examples/plugin/src/actions/sampleAction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import {
Action,
IAgentRuntime,
Memory,
HandlerCallback,
State,
composeContext,
generateObjectV2,
ModelClass,
elizaLogger,
} from "@ai16z/eliza";

import {
CreateResourceSchema,
isCreateResourceContent,
} from "../types";

import { createResourceTemplate } from "../templates";

export const createResourceAction: Action = {
name: "CREATE_RESOURCE",
description: "Create a new resource with the specified details",
validate: async (runtime: IAgentRuntime, _message: Memory) => {
return !!(runtime.character.settings.secrets?.API_KEY);
},
handler: async (
runtime: IAgentRuntime,
_message: Memory,
state: State,
_options: any,
callback: HandlerCallback
) => {
try {
const context = composeContext({
state,
template: createResourceTemplate,
});

const resourceDetails = await generateObjectV2({
runtime,
context,
modelClass: ModelClass.SMALL,
schema: CreateResourceSchema,
});

if (!isCreateResourceContent(resourceDetails.object)) {
callback(
{ text: "Invalid resource details provided." },
[]
);
return;
}

// persist relevant data if needed to memory/knowledge
// const memory = {
// type: "resource",
// content: resourceDetails.object,
// timestamp: new Date().toISOString()
// };

// await runtime.storeMemory(memory);

callback(
{
text: `Resource created successfully:
- Name: ${resourceDetails.object.name}
- Type: ${resourceDetails.object.type}
- Description: ${resourceDetails.object.description}
- Tags: ${resourceDetails.object.tags.join(", ")}
Resource has been stored in memory.`
},
[]
);
} catch (error) {
elizaLogger.error("Error creating resource:", error);
callback(
{ text: "Failed to create resource. Please check the logs." },
[]
);
}
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "Create a new resource with the name 'Resource1' and type 'TypeA'",
},
},
{
user: "{{agentName}}",
content: {
text: `Resource created successfully:
- Name: Resource1
- Type: TypeA`,
},
},
],
[
{
user: "{{user1}}",
content: {
text: "Create a new resource with the name 'Resource2' and type 'TypeB'",
},
},
{
user: "{{agentName}}",
content: {
text: `Resource created successfully:
- Name: Resource2
- Type: TypeB`,
},
},
],
],
};
47 changes: 47 additions & 0 deletions packages/_examples/plugin/src/evaluators/sampleEvalutor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Evaluator, IAgentRuntime, Memory, State, elizaLogger } from "@ai16z/eliza";

export const sampleEvaluator: Evaluator = {
alwaysRun: false,
description: "Sample evaluator for checking important content in memory",
similes: ["content checker", "memory evaluator"],
examples: [
{
context: "Checking if memory contains important content",
messages: [
{
action: "evaluate",
input: "This is an important message",
output: {
score: 1,
reason: "Memory contains important content."
}
}
],
outcome: "Memory should be evaluated as important"
}
],
handler: async (runtime: IAgentRuntime, memory: Memory, state: State) => {
// Evaluation logic for the evaluator
elizaLogger.log("Evaluating data in sampleEvaluator...");

// Example evaluation logic
if (memory.content && memory.content.includes("important")) {
elizaLogger.log("Important content found in memory.");
return {
score: 1,
reason: "Memory contains important content."
};
} else {
elizaLogger.log("No important content found in memory.");
return {
score: 0,
reason: "Memory does not contain important content."
};
}
},
name: "sampleEvaluator",
validate: async (runtime: IAgentRuntime, memory: Memory, state: State) => {
// Validation logic for the evaluator
return true;
}
};
8 changes: 8 additions & 0 deletions packages/_examples/plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { samplePlugin } from './plugins/samplePlugin';



export * from './plugins/samplePlugin';


export default samplePlugin;
17 changes: 17 additions & 0 deletions packages/_examples/plugin/src/plugins/samplePlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import {
Plugin,
} from "@ai16z/eliza";
import { createResourceAction } from "../actions/sampleAction";
import { sampleProvider } from "../providers/sampleProvider";
import { sampleEvaluator } from "../evaluators/sampleEvalutor";

export const samplePlugin: Plugin = {
name: "sample",
description: "Enables creation and management of generic resources",
actions: [createResourceAction],
providers: [sampleProvider],
evaluators: [sampleEvaluator],
// separate examples will be added for services and clients
services: [],
clients: [],
};
14 changes: 14 additions & 0 deletions packages/_examples/plugin/src/providers/sampleProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {
Provider,
IAgentRuntime,
Memory,
State,
elizaLogger
} from "@ai16z/eliza";

export const sampleProvider: Provider = {
get: async (runtime: IAgentRuntime, message: Memory, state: State) => {
// Data retrieval logic for the provider
elizaLogger.log("Retrieving data in sampleProvider...");
},
};
60 changes: 60 additions & 0 deletions packages/_examples/plugin/src/templates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
export const createResourceTemplate = `
Extract the following details to create a new resource:
- **name** (string): Name of the resource
- **type** (string): Type of resource (document, image, video)
- **description** (string): Description of the resource
- **tags** (array): Array of tags to categorize the resource
Provide the values in the following JSON format:
\`\`\`json
{
"name": "<resource_name>",
"type": "<resource_type>",
"description": "<resource_description>",
"tags": ["<tag1>", "<tag2>"]
}
\`\`\`
Here are the recent user messages for context:
{{recentMessages}}
`;

export const readResourceTemplate = `
Extract the following details to read a resource:
- **id** (string): Unique identifier of the resource
- **fields** (array): Specific fields to retrieve (optional)
Provide the values in the following JSON format:
\`\`\`json
{
"id": "<resource_id>",
"fields": ["<field1>", "<field2>"]
}
\`\`\`
Here are the recent user messages for context:
{{recentMessages}}
`;

export const updateResourceTemplate = `
Extract the following details to update a resource:
- **id** (string): Unique identifier of the resource
- **updates** (object): Key-value pairs of fields to update
Provide the values in the following JSON format:
\`\`\`json
{
"id": "<resource_id>",
"updates": {
"<field1>": "<new_value1>",
"<field2>": "<new_value2>"
}
}
\`\`\`
Here are the recent user messages for context:
{{recentMessages}}
`;
51 changes: 51 additions & 0 deletions packages/_examples/plugin/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { z } from "zod";

// Base resource schema
export const ResourceSchema = z.object({
id: z.string().optional(),
name: z.string().min(1),
type: z.enum(["document", "image", "video"]),
description: z.string(),
tags: z.array(z.string())
});

// Create resource schema
export const CreateResourceSchema = ResourceSchema.omit({ id: true });

// Read resource schema
export const ReadResourceSchema = z.object({
id: z.string(),
fields: z.array(z.string()).optional()
});

// Update resource schema
export const UpdateResourceSchema = z.object({
id: z.string(),
updates: z.record(z.string(), z.any())
});

// Type definitions
export type Resource = z.infer<typeof ResourceSchema>;
export type CreateResourceContent = z.infer<typeof CreateResourceSchema>;
export type ReadResourceContent = z.infer<typeof ReadResourceSchema>;
export type UpdateResourceContent = z.infer<typeof UpdateResourceSchema>;

// Type guards
export const isCreateResourceContent = (obj: any): obj is CreateResourceContent => {
return CreateResourceSchema.safeParse(obj).success;
};

export const isReadResourceContent = (obj: any): obj is ReadResourceContent => {
return ReadResourceSchema.safeParse(obj).success;
};

export const isUpdateResourceContent = (obj: any): obj is UpdateResourceContent => {
return UpdateResourceSchema.safeParse(obj).success;
};

// Plugin configuration type
export interface ExamplePluginConfig {
apiKey: string;
apiSecret: string;
endpoint?: string;
}
Loading

0 comments on commit 5a3d348

Please sign in to comment.