Skip to content

Commit

Permalink
feat(viewer): add OpenAI API key param
Browse files Browse the repository at this point in the history
- `utils/parameters.ts` introduces a new function
  `getOpenAiApiKeyParameter` that obtains the OpenAI API key from the
  Parameter Store on AWS Systems Manager. It reads the parameter path
  from the environment variable `OPENAI_API_KEY_PARAMETER_PATH`.
  `getDomainNameParameter` and `getOpenAiApiKeyParameter` shares a new
  function `getParameter` that performs actual requests to AWS.

issue #26
  • Loading branch information
kikuomax committed Oct 17, 2023
1 parent d9fa412 commit cf300cd
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions cdk/viewer/src/utils/parameters.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm";

// AWS Systems Manager client.
let ssm: SSMClient | null = null;

/**
* Obtains the optional domain name from the Parameter Store on AWS Systems
* Manager.
Expand All @@ -11,11 +14,42 @@ export async function getDomainNameParameter(): Promise<string | null> {
console.log("no domain name parameter configured");
return null;
}
const ssm = new SSMClient({});
return await getParameter(parameterName);
}

/**
* Obtains the OpenAI API key from the Parameter Store on AWS Systems Manager.
*/
export async function getOpenAiApiKeyParameter(): Promise<string> {
const parameterName = process.env.OPENAI_API_KEY_PARAMETER_PATH;
console.log("obtaining OpenAI API key from Parameter Store", parameterName);
if (parameterName == null) {
throw new Error("no parameter path to OpenAI API key configured");
}
const apiKey = await getParameter(parameterName);
if (apiKey == null) {
throw new Error("no OpenAI API key configured");
}
return apiKey;
}

/**
* Obtains a parameter from the Parameter Store on AWS Systems Manager.
*
* @returns
*
* `null` if no parameter is configured in the Parameter Store on AWS Systems
* Manager.
*/
export async function getParameter(
parameterName: string,
): Promise<string | null> {
if (ssm == null) {
ssm = new SSMClient({});
}
const res = await ssm.send(new GetParameterCommand({
Name: parameterName,
WithDecryption: true,
}));
// service should not start with a bad configuration
return res.Parameter?.Value ?? null;
}

0 comments on commit cf300cd

Please sign in to comment.