Skip to content

Commit

Permalink
feat: added example code in comments
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniAkash committed Mar 11, 2024
1 parent 39c0f68 commit 418db6a
Show file tree
Hide file tree
Showing 3 changed files with 211 additions and 8 deletions.
39 changes: 32 additions & 7 deletions src/client/auth/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,29 @@ export class ClarifaiAuthHelper {
private _base: string;
private _ui: string;

/**
* A helper to get the authorization information needed to make API calls with the grpc
* client to a specific app using a personal access token.
*
* There are class methods to make this object easily from either query_params provided by streamlit or from env vars.
*
* Note: only one of personal access token (pat) or a session token (token) can be provided.
* Always use PATs in your code and never session tokens, those are only provided internal UI code.
*
* @param user_id - A user id who owns the resource you want to make calls to.
* @param app_id - An app id for the application that owns the resource you want to interact with.
* @param pat - A personal access token.
* @param token - A session token (internal use only, always use a PAT).
* @param base - A url to the API endpoint to hit. Examples include api.clarifai.com,
* https://api.clarifai.com (default), https://host:port, http://host:port,
* host:port (will be treated as http, not https). It's highly recommended to include
* the http:// or https:// otherwise we need to check the endpoint to determine if it has SSL during this __init__.
* @param ui - A url to the UI. Examples include clarifai.com,
* https://clarifai.com (default), https://host:port, http://host:port,
* host:port (will be treated as http, not https). It's highly recommended to include
* the http:// or https:// otherwise we need to check the endpoint to determine if it has SSL during this __init__.
* @param validate - Whether to validate the inputs. This is useful for overriding vars then validating.
*/
constructor(
userId: string,
appId: string,
Expand Down Expand Up @@ -113,13 +136,15 @@ export class ClarifaiAuthHelper {
}

/**
* Will look for the following environment variables:
* - user_id: CLARIFAI_USER_ID environment variable.
* - app_id: CLARIFAI_APP_ID environment variable.
* - One of:
* - token: CLARIFAI_SESSION_TOKEN environment variable.
* - pat: CLARIFAI_PAT environment variable.
* - base: CLARIFAI_API_BASE environment variable.
* Will look for the following env vars:
* user_id: CLARIFAI_USER_ID env var.
* app_id: CLARIFAI_APP_ID env var.
* one of:
* token: CLARIFAI_SESSION_TOKEN env var.
* pat: CLARIFAI_PAT env var.
* base: CLARIFAI_API_BASE env var.
*
* @param validate - Whether to validate the inputs. This is useful for overriding vars then validating.
*/
static fromEnv(validate: boolean = true): ClarifaiAuthHelper {
const userId = process.env.CLARIFAI_USER_ID || "";
Expand Down
175 changes: 174 additions & 1 deletion src/client/user.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,69 @@
import { Lister } from "./lister";
import { AuthConfig, PaginationRequestParams } from "../utils/types";
import {
GetAppRequest,
ListAppsRequest,
ListRunnersRequest,
MultiAppResponse,
MultiRunnerResponse,
PostAppsRequest,
PostRunnersRequest,
SingleAppResponse,
} from "clarifai-nodejs-grpc/proto/clarifai/api/service_pb";
import { mapParamsToRequest, promisifyGrpcCall } from "../utils/misc";
import {
App,
Runner,
UserAppIDSet,
Workflow,
} from "clarifai-nodejs-grpc/proto/clarifai/api/resources_pb";
import { StatusCode } from "clarifai-nodejs-grpc/proto/clarifai/api/status/status_code_pb";

/**
* User is a class that provides access to Clarifai API endpoints related to user information.
*/
export class User extends Lister {
/**
* Initializes an User object with the specified authentication configuration.
*
* @param authConfig An object containing the authentication configuration. Defaults to an empty object.
* @param authConfig.userId The user ID for the user to interact with.
* @param authConfig.appId The application ID associated with the user.
* @param authConfig.pat A personal access token for authentication. Can also be set as an environment variable CLARIFAI_PAT.
* @param authConfig.token A session token for authentication. Accepts either a session token or a personal access token (pat). Can also be set as an environment variable CLARIFAI_SESSION_TOKEN.
* @param authConfig.base Optional. The base API URL. Defaults to "https://api.clarifai.com".
* @param authConfig.ui Optional. Additional UI configurations.
* @param [authConfig] Additional keyword arguments can be passed to configure the User object.
*/
constructor(authConfig: AuthConfig = {}) {
super({ authConfig });
}

/**
* Lists all the apps for the user.
*
* @param params A dictionary of filters to be applied to the list of apps.
* @param pageNo The page number to list.
* @param perPage The number of items per page.
* @yields App objects for the user.
*
* @example
* ```typescript
* import { User } from 'clarifai-nodejs';
* const user = new User(authConfig);
* const appsGenerator = user.listApps({
* pageNo: 1,
* perPage: 20,
* params: {
* sortAscending: true,
* },
* });
* const apps = (await appsGenerator.next()).value;
* ```
*
* @note Defaults to 16 per page if pageNo is specified and perPage is not specified.
* If both pageNo and perPage are None, then lists all the resources.
*/
async *listApps({
params = {},
pageNo,
Expand All @@ -45,6 +90,31 @@ export class User extends Lister {
}
}

/**
* Lists all the runners for the user.
*
* @param params A dictionary of filters to be applied to the list of runners.
* @param pageNo The page number to list.
* @param perPage The number of items per page.
* @yields Runner objects for the user.
*
* @example
* ```typescript
* import { User } from 'clarifai-nodejs';
* const user = new User(authConfig);
* const runnersGenerator = user.listRunners({
* pageNo: 1,
* perPage: 20,
* params: {
* sortAscending: true,
* },
* });
* const runners = (await runnersGenerator.next()).value;
* ```
*
* @note Defaults to 16 per page if pageNo is specified and perPage is not specified.
* If both pageNo and perPage are None, then lists all the resources.
*/
async *listRunners({
params = {},
pageNo,
Expand All @@ -71,13 +141,30 @@ export class User extends Lister {
}
}

/**
* Creates an app for the user.
*
* @param appId The app ID for the app to create.
* @param baseWorkflow The base workflow to use for the app. Examples: 'Universal', 'Language-Understanding', 'General'
* @returns An App object for the specified app ID.
*
* @example
* ```typescript
* import { User } from 'clarifai-nodejs';
* const user = new User(authConfig);
* const app = await user.createApp({
* appId: "app_id",
* baseWorkflow: "Universal",
* });
* ```
*/
async createApp({
appId,
baseWorkflow = "Empty",
}: {
appId: string;
baseWorkflow: string;
}) {
}): Promise<MultiAppResponse.AsObject> {
const workflow = new Workflow();
workflow.setId(baseWorkflow);
workflow.setAppId("main");
Expand Down Expand Up @@ -108,4 +195,90 @@ export class User extends Lister {

return responseObject;
}

/**
* Creates a runner for the user.
*
* @param runnerId The Id of runner to create.
* @param labels Labels to match runner.
* @param description Description of Runner.
* @returns A runner object for the specified Runner ID.
*
* @example
* ```typescript
* import { User } from 'clarifai-nodejs';
* const user = new User(authConfig);
* const runner = await user.createRunner({
* runnerId: "runner_id",
* labels: ["label to link runner"],
* description: "laptop runner",
* });
* ```
*/
async createRunner({
runnerId,
labels,
description,
}: {
runnerId: string;
labels: string[];
description: string;
}): Promise<MultiRunnerResponse.AsObject> {
if (!Array.isArray(labels)) {
throw new Error("Labels must be an array of strings");
}

const request = new PostRunnersRequest();
request.setUserAppId(this.userAppId);
const runner = new Runner();
runner.setId(runnerId);
runner.setLabelsList(labels);
runner.setDescription(description);
request.setRunnersList([runner]);

const postRunners = promisifyGrpcCall(
this.STUB.client.postRunners,
this.STUB.client,
);
const response = await this.grpcRequest(postRunners, request);
const responseObject = response.toObject();
if (responseObject.status?.code !== StatusCode.SUCCESS) {
throw new Error(
`Failed to create runner: ${responseObject.status?.description}`,
);
}
console.info("\nRunner created\n%s", responseObject.status.description);

return responseObject;
}

/**
* Returns an App object for the specified app ID.
*
* @param appId The app ID for the app to interact with.
* @returns An App object for the specified app ID.
*
* @example
* ```typescript
* import { User } from 'clarifai-nodejs';
* const user = new User(authConfig);
* const app = await user.app({ appId: 'app_id' });
* ```
*/
async app({ appId }: { appId: string }): Promise<SingleAppResponse.AsObject> {
const request = new GetAppRequest();
const appIdSet = new UserAppIDSet();
appIdSet.setUserId(this.userAppId.getUserId());
appIdSet.setAppId(appId);
request.setUserAppId(appIdSet);
const getApp = promisifyGrpcCall(this.STUB.client.getApp, this.STUB.client);
const response = await this.grpcRequest(getApp, request);
const responseObject = response.toObject();
if (responseObject.status?.code !== StatusCode.SUCCESS) {
throw new Error(
`Failed to retrieve app: ${responseObject.status?.description}`,
);
}
return responseObject;
}
}
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export * from "./client/user";
export * from "./client/app";
export * from "./client/input";
export * from "./client/model";
export * from "./client/search";
export * from "./client/workflow";

0 comments on commit 418db6a

Please sign in to comment.