Skip to content

Commit 56a78a5

Browse files
Merge pull request #12 from madschristensen99/main
Add documentation
2 parents d3bd939 + 95fe753 commit 56a78a5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

61 files changed

+1892
-225
lines changed

packages/fss-agent/src/lib/agent.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
// Import the OpenAI class from the 'openai' package.
12
import { OpenAI } from 'openai';
23
import type {
34
IntentMatcher,
45
IntentMatcherResponse,
56
} from '@lit-protocol/fss-signer';
67
import type { FssTool } from '@lit-protocol/fss-tool';
78

9+
// Import helper functions for matching tools and parsing parameters based on intent.
810
import { getToolForIntent } from './get-tool-for-intent';
911
import { parseToolParametersFromIntent } from './parse-tool-parameters';
1012

@@ -37,15 +39,17 @@ export class OpenAiIntentMatcher implements IntentMatcher {
3739
registeredTools
3840
);
3941

42+
// If a tool is matched, parse the parameters from the intent using `parseToolParametersFromIntent`.
4043
const params = matchedTool
4144
? await parseToolParametersFromIntent(
4245
this.openai,
4346
this.model,
4447
intent,
4548
matchedTool
4649
)
47-
: { foundParams: {}, missingParams: [] };
50+
: { foundParams: {}, missingParams: [] }; // If no tool is matched, return empty parameters.
4851

52+
// Return the analysis, matched tool, and parameters.
4953
return { analysis, matchedTool, params };
5054
}
5155
}

packages/fss-agent/src/lib/get-tool-for-intent.ts

+22-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,23 @@
1+
// Import the OpenAI class from the 'openai' package.
12
import { OpenAI } from 'openai';
3+
24
import type { FssTool } from '@lit-protocol/fss-tool';
35

6+
// Import a helper function to generate a prompt for tool matching.
47
import { getToolMatchingPrompt } from './get-tool-matching-prompt';
58

9+
/**
10+
* Matches a user's intent to an appropriate tool from the available tools on a specified Lit network.
11+
* This function uses OpenAI's API to analyze the intent and recommend a tool.
12+
*
13+
* @param openai - An instance of the OpenAI client.
14+
* @param openAiModel - The name of the OpenAI model to use for analysis.
15+
* @param userIntent - The user's intent as a string (e.g., "I want to mint an NFT").
16+
* @param litNetwork - The Lit network to use for filtering available tools.
17+
* @returns A Promise that resolves to an object containing:
18+
* - analysis: The raw analysis result from OpenAI, parsed as a JSON object.
19+
* - matchedTool: The tool matched to the user's intent, or `null` if no match is found.
20+
*/
621
export async function getToolForIntent(
722
openai: OpenAI,
823
openAiModel: string,
@@ -12,6 +27,7 @@ export async function getToolForIntent(
1227
analysis: any;
1328
matchedTool: FssTool | null;
1429
}> {
30+
1531
const completion = await openai.chat.completions.create({
1632
model: openAiModel,
1733
messages: [
@@ -21,18 +37,22 @@ export async function getToolForIntent(
2137
},
2238
{
2339
role: 'user',
24-
content: userIntent,
40+
content: userIntent, // Provide the user's intent as input.
2541
},
2642
],
27-
response_format: { type: 'json_object' },
43+
response_format: { type: 'json_object' }, // Request the response in JSON format.
2844
});
2945

46+
// Parse the analysis result from OpenAI's response.
3047
const analysis = JSON.parse(completion.choices[0].message.content || '{}');
48+
49+
// Find the matched tool based on the recommended CID from the analysis.
3150
const matchedTool = analysis.recommendedCID
3251
? registeredTools.find(
3352
(tool) => tool.ipfsCid === analysis.recommendedCID
3453
) || null
3554
: null;
3655

56+
// Return the analysis and the matched tool (or null if no match is found).
3757
return { analysis, matchedTool };
3858
}

packages/fss-agent/src/lib/get-tool-matching-prompt.ts

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
1+
// Import the FssTool type from the '@lit-protocol/fss-tool' package.
12
import type { FssTool } from '@lit-protocol/fss-tool';
23

4+
/**
5+
* Generates a prompt for OpenAI to analyze a user's intent and match it to an appropriate tool.
6+
* The prompt includes descriptions of the available tools and instructions for OpenAI to follow.
7+
*
8+
* @param tools - An array of FssTool objects representing the available tools.
9+
* @returns A string containing the generated prompt.
10+
*/
311
export function getToolMatchingPrompt(tools: FssTool<any, any>[]): string {
12+
413
const toolDescriptions = tools
514
.map(
615
(tool) =>
@@ -11,7 +20,6 @@ export function getToolMatchingPrompt(tools: FssTool<any, any>[]): string {
1120
return `
1221
You are a web3 transaction analyzer.
1322
Given a user's intent and available tools, determine if there's an appropriate tool that matches exactly what the user wants to do.
14-
1523
Available tools:
1624
${toolDescriptions}
1725
Important:

packages/fss-agent/src/lib/parse-tool-parameters.ts

+25-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,24 @@
1+
// Import the OpenAI class from the 'openai' package.
12
import { OpenAI } from 'openai';
3+
4+
// Import the FssTool type from the '@lit-protocol/fss-tool' package.
25
import type { FssTool } from '@lit-protocol/fss-tool';
36

7+
/**
8+
* Parses and validates parameters from a user's intent for a given tool.
9+
* This function uses OpenAI's API to extract parameter values and ensures they conform to the tool's validation rules.
10+
*
11+
* @template TParams - A generic type representing the tool's parameter structure.
12+
* @template TPolicy - A generic type representing the tool's policy structure.
13+
* @param openai - An instance of the OpenAI client.
14+
* @param openAiModel - The name of the OpenAI model to use for parsing.
15+
* @param intent - The user's intent as a string.
16+
* @param tool - The tool for which parameters are being parsed.
17+
* @returns A Promise that resolves to an object containing:
18+
* - foundParams: A partial object of the parsed parameters.
19+
* - missingParams: An array of parameter names that could not be parsed.
20+
* - validationErrors: An array of validation errors for invalid parameters.
21+
*/
422
export async function parseToolParametersFromIntent<
523
TParams extends Record<string, any>,
624
TPolicy extends { type: string }
@@ -14,6 +32,7 @@ export async function parseToolParametersFromIntent<
1432
missingParams: Array<keyof TParams>;
1533
validationErrors: Array<{ param: string; error: string }>;
1634
}> {
35+
// Use OpenAI's API to parse parameters from the user's intent.
1736
const completion = await openai.chat.completions.create({
1837
model: openAiModel,
1938
messages: [
@@ -65,12 +84,14 @@ export async function parseToolParametersFromIntent<
6584
response_format: { type: 'json_object' },
6685
});
6786

87+
// Parse the result from OpenAI's response.
6888
const result = JSON.parse(completion.choices[0].message.content || '{}');
6989

70-
// Validate found parameters
90+
// Validate the found parameters using the tool's validation function.
7191
const foundParams = result.foundParams || {};
7292
const validationResult = tool.parameters.validate(foundParams);
7393

94+
// If validation passes, return the found and missing parameters.
7495
if (validationResult === true) {
7596
return {
7697
foundParams,
@@ -80,12 +101,12 @@ export async function parseToolParametersFromIntent<
80101
};
81102
}
82103

83-
// If validation fails, only treat invalid params as missing
104+
// If validation fails, filter out invalid parameters and add them to missingParams.
84105
const invalidParams = new Set(validationResult.map((error) => error.param));
85106
const filteredParams: Partial<TParams> = {};
86107
const missingParams = new Set<keyof TParams>(result.missingParams || []);
87108

88-
// Keep only valid params in foundParams
109+
// Keep only valid parameters in foundParams.
89110
Object.entries(foundParams).forEach(([param, value]) => {
90111
if (!invalidParams.has(param)) {
91112
filteredParams[param as keyof TParams] = value as TParams[keyof TParams];
@@ -94,6 +115,7 @@ export async function parseToolParametersFromIntent<
94115
}
95116
});
96117

118+
// Return the filtered parameters, missing parameters, and validation errors.
97119
return {
98120
foundParams: filteredParams,
99121
missingParams: Array.from(missingParams),
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,58 @@
1+
// Import the FssAdmin type from the '@lit-protocol/full-self-signing' package.
12
import { type Admin as FssAdmin } from '@lit-protocol/full-self-signing';
23

4+
// Import the logger utility for logging messages.
35
import { logger } from '../../utils/logger';
6+
7+
// Import custom error types and utilities.
48
import { FssCliError, FssCliErrorType } from '../../errors';
59
import { promptDelegateeAddress } from '../../prompts/admin';
610

11+
/**
12+
* Adds a delegatee to the Full Self-Signing (FSS) system.
13+
* This function logs the progress and success of the operation.
14+
*
15+
* @param fssAdmin - An instance of the FssAdmin class.
16+
* @param address - The address of the delegatee to add.
17+
*/
718
const addDelegatee = async (fssAdmin: FssAdmin, address: string) => {
19+
// Log a loading message to indicate the operation is in progress.
820
logger.loading('Adding delegatee...');
21+
22+
// Add the delegatee to the FSS system.
923
await fssAdmin.addDelegatee(address);
24+
25+
// Log a success message once the delegatee is added.
1026
logger.success(`Successfully added delegatee ${address}.`);
1127
};
1228

29+
/**
30+
* Handles the process of adding a delegatee to the FSS system.
31+
* This function prompts the user for the delegatee's address, adds the delegatee,
32+
* and handles any errors that occur during the process.
33+
*
34+
* @param fssAdmin - An instance of the FssAdmin class.
35+
*/
1336
export const handleAddDelegatee = async (fssAdmin: FssAdmin) => {
1437
try {
38+
// Prompt the user for the delegatee's address.
1539
const address = await promptDelegateeAddress();
40+
41+
// Add the delegatee to the FSS system.
1642
await addDelegatee(fssAdmin, address);
1743
} catch (error) {
44+
// Handle specific errors related to delegatee addition.
1845
if (error instanceof FssCliError) {
1946
if (
2047
error.type === FssCliErrorType.ADMIN_GET_DELEGATEE_ADDRESS_CANCELLED
2148
) {
49+
// Log an error message if the user cancels the operation.
2250
logger.error('Delegatee addition cancelled.');
2351
return;
2452
}
2553
}
2654

55+
// Re-throw any other errors to be handled by the caller.
2756
throw error;
2857
}
2958
};
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,56 @@
1+
// Import the FssAdmin type from the '@lit-protocol/full-self-signing' package.
12
import { type Admin as FssAdmin } from '@lit-protocol/full-self-signing';
23

4+
// Import the logger utility for logging messages.
35
import { logger } from '../../utils/logger';
6+
7+
// Import custom error types and utilities.
48
import { FssCliError, FssCliErrorType } from '../../errors';
59
import { promptSelectDelegateesToAdd } from '../../prompts/admin';
610

11+
/**
12+
* Adds multiple delegatees to the Full Self-Signing (FSS) system in a batch operation.
13+
* This function logs the progress and success of the operation.
14+
*
15+
* @param fssAdmin - An instance of the FssAdmin class.
16+
* @param addresses - An array of delegatee addresses to add.
17+
*/
718
const batchAddDelegatees = async (fssAdmin: FssAdmin, addresses: string[]) => {
19+
// Log a loading message to indicate the operation is in progress.
820
logger.loading('Adding delegatees...');
21+
22+
// Add the delegatees to the FSS system in a batch operation.
923
await fssAdmin.batchAddDelegatees(addresses);
10-
logger.success('Successfully added delegatees');
24+
25+
// Log a success message once the delegatees are added.
26+
logger.success('Successfully added delegatees.');
1127
};
1228

29+
/**
30+
* Handles the process of adding multiple delegatees to the FSS system in a batch operation.
31+
* This function prompts the user to select delegatee addresses, adds the delegatees,
32+
* and handles any errors that occur during the process.
33+
*
34+
* @param fssAdmin - An instance of the FssAdmin class.
35+
*/
1336
export const handleBatchAddDelegatee = async (fssAdmin: FssAdmin) => {
1437
try {
38+
// Prompt the user to select delegatee addresses.
1539
const addresses = await promptSelectDelegateesToAdd();
40+
41+
// Add the selected delegatees to the FSS system.
1642
await batchAddDelegatees(fssAdmin, addresses);
1743
} catch (error) {
44+
// Handle specific errors related to batch delegatee addition.
1845
if (error instanceof FssCliError) {
1946
if (error.type === FssCliErrorType.ADMIN_BATCH_ADD_DELEGATEE_CANCELLED) {
47+
// Log an error message if the user cancels the operation.
2048
logger.error('Batch delegatee addition cancelled.');
2149
return;
2250
}
2351
}
2452

53+
// Re-throw any other errors to be handled by the caller.
2554
throw error;
2655
}
2756
};
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,64 @@
1+
// Import the FssAdmin type from the '@lit-protocol/full-self-signing' package.
12
import { type Admin as FssAdmin } from '@lit-protocol/full-self-signing';
23

4+
// Import the logger utility for logging messages.
35
import { logger } from '../../utils/logger';
6+
7+
// Import custom error types and utilities.
48
import { FssCliError, FssCliErrorType } from '../../errors';
59
import { promptSelectDelegateesToRemove } from '../../prompts/admin';
610

11+
/**
12+
* Removes multiple delegatees from the Full Self-Signing (FSS) system in a batch operation.
13+
* This function logs the progress and success of the operation.
14+
*
15+
* @param fssAdmin - An instance of the FssAdmin class.
16+
* @param addresses - An array of delegatee addresses to remove.
17+
*/
718
const batchRemoveDelegatees = async (
819
fssAdmin: FssAdmin,
920
addresses: string[]
1021
) => {
22+
// Log a loading message to indicate the operation is in progress.
1123
logger.loading('Removing delegatees...');
24+
25+
// Remove the delegatees from the FSS system in a batch operation.
1226
await fssAdmin.batchRemoveDelegatees(addresses);
13-
logger.success('Successfully removed delegatees');
27+
28+
// Log a success message once the delegatees are removed.
29+
logger.success('Successfully removed delegatees.');
1430
};
1531

32+
/**
33+
* Handles the process of removing multiple delegatees from the FSS system in a batch operation.
34+
* This function prompts the user to select delegatee addresses, removes the delegatees,
35+
* and handles any errors that occur during the process.
36+
*
37+
* @param fssAdmin - An instance of the FssAdmin class.
38+
*/
1639
export const handleBatchRemoveDelegatee = async (fssAdmin: FssAdmin) => {
1740
try {
18-
const addresses = await promptSelectDelegateesToRemove(
19-
await fssAdmin.getDelegatees()
20-
);
41+
// Retrieve the current list of delegatees from the FSS system.
42+
const delegatees = await fssAdmin.getDelegatees();
43+
44+
// Prompt the user to select delegatee addresses to remove.
45+
const addresses = await promptSelectDelegateesToRemove(delegatees);
46+
47+
// Remove the selected delegatees from the FSS system.
2148
await batchRemoveDelegatees(fssAdmin, addresses);
2249
} catch (error) {
50+
// Handle specific errors related to batch delegatee removal.
2351
if (error instanceof FssCliError) {
2452
if (
2553
error.type === FssCliErrorType.ADMIN_BATCH_REMOVE_DELEGATEE_CANCELLED
2654
) {
55+
// Log an error message if the user cancels the operation.
2756
logger.error('Batch delegatee removal cancelled.');
2857
return;
2958
}
3059
}
3160

61+
// Re-throw any other errors to be handled by the caller.
3262
throw error;
3363
}
3464
};

0 commit comments

Comments
 (0)