Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(conversation): use functionMap for custom handler IFunction reference #2922

Merged
merged 6 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions dependency_licenses.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14486,6 +14486,32 @@ SOFTWARE.

-----

The following software may be included in this product: esbuild. A copy of the source code may be downloaded from git+https://github.com/evanw/esbuild.git. This software contains the following license and notice below:
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is from adding esbuild as a dev dependency in the conversation transformer.


MIT License

Copyright (c) 2020 Evan Wallace

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

-----

The following software may be included in this product: escalade. A copy of the source code may be downloaded from https://github.com/lukeed/escalade.git. This software contains the following license and notice below:

MIT License
Expand Down
3 changes: 2 additions & 1 deletion packages/amplify-graphql-conversation-transformer/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { DirectiveNode } from 'graphql';
import { FieldDefinitionNode } from 'graphql';
import { HasManyTransformer } from '@aws-amplify/graphql-relational-transformer';
import { InterfaceTypeDefinitionNode } from 'graphql';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { ObjectTypeDefinitionNode } from 'graphql';
import { TransformerAuthProvider } from '@aws-amplify/graphql-transformer-interfaces';
Expand All @@ -19,7 +20,7 @@ import { TransformerSchemaVisitStepContextProvider } from '@aws-amplify/graphql-

// @public (undocumented)
export class ConversationTransformer extends TransformerPluginBase {
constructor(modelTransformer: ModelTransformer, hasManyTransformer: HasManyTransformer, belongsToTransformer: BelongsToTransformer, authProvider: TransformerAuthProvider);
constructor(modelTransformer: ModelTransformer, hasManyTransformer: HasManyTransformer, belongsToTransformer: BelongsToTransformer, authProvider: TransformerAuthProvider, functionNameMap?: Record<string, lambda.IFunction>);
// (undocumented)
field: (parent: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode, definition: FieldDefinitionNode, directive: DirectiveNode, context: TransformerSchemaVisitStepContextProvider) => void;
// (undocumented)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"immer": "^9.0.12"
},
"devDependencies": {
"@aws-amplify/graphql-transformer-test-utils": "1.0.3"
"@aws-amplify/graphql-transformer-test-utils": "1.0.3",
"esbuild": "^0.24.0"
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

required for test cases

},
"peerDependencies": {
"aws-cdk-lib": "^2.158.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,9 @@ exports[`ConversationTransformer valid schemas should transform conversation rou
ctx.stash.connectionAttributes = {};
ctx.stash.lambdaFunctionArn = "",
{
"Fn::Sub": [
"arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:\${name}",
{
"name": "conversation-handler",
},
"Fn::GetAtt": [
"PirateChatConversationDirectiveLambdaStack",
"Outputs.transformerrootstackPirateChatConversationDirectiveLambdaStackPirateChatDefaultConversationHandlerconversationHandlerFunction2B526F1AArn",
],
},
"";
Expand Down Expand Up @@ -144,11 +142,9 @@ exports[`ConversationTransformer valid schemas should transform conversation rou
ctx.stash.connectionAttributes = {};
ctx.stash.lambdaFunctionArn = "",
{
"Fn::Sub": [
"arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:\${name}",
{
"name": "conversation-handler",
},
"Fn::GetAtt": [
"PirateChatConversationDirectiveLambdaStack",
"Outputs.transformerrootstackPirateChatConversationDirectiveLambdaStackPirateChatDefaultConversationHandlerconversationHandlerFunction2B526F1AArn",
],
},
"";
Expand Down Expand Up @@ -268,11 +264,9 @@ exports[`ConversationTransformer valid schemas should transform conversation rou
ctx.stash.connectionAttributes = {};
ctx.stash.lambdaFunctionArn = "",
{
"Fn::Sub": [
"arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:\${name}",
{
"name": "conversation-handler",
},
"Fn::GetAtt": [
"PirateChatConversationDirectiveLambdaStack",
"Outputs.transformerrootstackPirateChatConversationDirectiveLambdaStackPirateChatDefaultConversationHandlerconversationHandlerFunction2B526F1AArn",
],
},
"";
Expand Down Expand Up @@ -392,11 +386,9 @@ exports[`ConversationTransformer valid schemas should transform conversation rou
ctx.stash.connectionAttributes = {};
ctx.stash.lambdaFunctionArn = "",
{
"Fn::Sub": [
"arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:\${name}",
{
"name": "conversation-handler",
},
"Fn::GetAtt": [
"PirateChatConversationDirectiveLambdaStack",
"Outputs.transformerrootstackPirateChatConversationDirectiveLambdaStackPirateChatDefaultConversationHandlerconversationHandlerFunction2B526F1AArn",
],
},
"";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import { IndexTransformer, PrimaryKeyTransformer } from '@aws-amplify/graphql-in
import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { validateModelSchema } from '@aws-amplify/graphql-transformer-core';
import { AppSyncAuthConfiguration, ModelDataSourceStrategy } from '@aws-amplify/graphql-transformer-interfaces';
import { DeploymentResources, testTransform } from '@aws-amplify/graphql-transformer-test-utils';
import { DeploymentResources, testTransform, TransformManager } from '@aws-amplify/graphql-transformer-test-utils';
import { parse } from 'graphql';
import { ConversationTransformer } from '..';
import { BelongsToTransformer, HasManyTransformer, HasOneTransformer } from '@aws-amplify/graphql-relational-transformer';
import * as fs from 'fs-extra';
import * as path from 'path';
import { Code, Function, IFunction, Runtime } from 'aws-cdk-lib/aws-lambda';
import { GenerationTransformer } from '@aws-amplify/graphql-generation-transformer';
import { toUpper } from 'graphql-transformer-common';

Expand Down Expand Up @@ -44,6 +45,35 @@ describe('ConversationTransformer', () => {
const schema = parse(out.schema);
validateModelSchema(schema);
});

it('uses functionMap for custom handler', () => {
const routeName = 'pirateChat';
const inputSchema = getSchema('conversation-route-custom-handler.graphql', { ROUTE_NAME: routeName });

const transformerManager = new TransformManager();
const stack = transformerManager.getTransformScope();
const customHandler = new Function(stack, 'conversation-handler', {
runtime: Runtime.NODEJS_18_X,
code: Code.fromInline('exports.handler = async (event) => { return "Hello World"; }'),
handler: 'index.handler',
});

const functionMap = {
[`Fn${routeName}`]: customHandler,
};

const out = transform(inputSchema, {}, defaultAuthConfig, functionMap, transformerManager);
expect(out).toBeDefined();

const expectedCustomHandlerArn = out.rawRootStack.resolve(customHandler.functionArn);
const conversationLambdaStackName = `${toUpper(routeName)}ConversationDirectiveLambdaStack`;
const conversationLambdaDataSourceName = `Fn${routeName}LambdaDataSource`;
const conversationLambdaDataSourceFunctionArnRef =
out.stacks[conversationLambdaStackName].Resources?.[conversationLambdaDataSourceName].Properties.LambdaConfig.LambdaFunctionArn.Ref;
const lambdaDataSourceFunctionArn =
out.rootStack.Resources?.[conversationLambdaStackName].Properties?.Parameters?.[conversationLambdaDataSourceFunctionArnRef];
expect(lambdaDataSourceFunctionArn).toEqual(expectedCustomHandlerArn);
Comment on lines +68 to +75
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I welcome suggestions for a more succinct way to do this, like using CDK test helpers -- I was unable to find a better way.

});
});

describe('invalid schemas', () => {
Expand Down Expand Up @@ -114,6 +144,8 @@ function transform(
inputSchema: string,
dataSourceStrategies?: Record<string, ModelDataSourceStrategy>,
authConfig: AppSyncAuthConfiguration = defaultAuthConfig,
functionMap?: Record<string, IFunction>,
transformerManager?: TransformManager,
): DeploymentResources {
const modelTransformer = new ModelTransformer();
const authTransformer = new AuthTransformer();
Expand All @@ -129,7 +161,7 @@ function transform(
hasManyTransformer,
hasOneTransformer,
belongsToTransformer,
new ConversationTransformer(modelTransformer, hasManyTransformer, belongsToTransformer, authTransformer),
new ConversationTransformer(modelTransformer, hasManyTransformer, belongsToTransformer, authTransformer, functionMap),
new GenerationTransformer(),
authTransformer,
];
Expand All @@ -139,6 +171,7 @@ function transform(
authConfig,
transformers,
dataSourceStrategies,
transformerManager,
});

return out;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
type Mutation {
ROUTE_NAME(
conversationId: ID!,
content: [ContentBlockInput],
aiContext: AWSJSON,
toolConfiguration: ToolConfigurationInput
): ConversationMessage
@conversation(
aiModel: "anthropic.claude-3-haiku-20240307-v1:0",
functionName: "FnROUTE_NAME",
systemPrompt: "You are a helpful chatbot. Answer questions to the best of your ability.",
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ type Mutation {
): ConversationMessage
@conversation(
aiModel: "anthropic.claude-3-haiku-20240307-v1:0",
functionName: "conversation-handler",
systemPrompt: "You are a helpful chatbot. Answer questions to the best of your ability.",
tools: [{ name: "getTemperature", description: "does a thing" }, { name: "plus", description: "does a different thing" }]
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ type Mutation {
): ConversationMessage
@conversation(
aiModel: "anthropic.claude-3-haiku-20240307-v1:0",
functionName: "conversation-handler",
systemPrompt: "You are a helpful chatbot. Answer questions to the best of your ability.",
INFERENENCE_CONFIGURATION
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ type Mutation {
toolConfiguration: ToolConfigurationInput
): ConversationMessage
@conversation(
functionName: "conversation-handler",
systemPrompt: "You are a helpful chatbot."
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ type Mutation {
): String
@conversation(
aiModel: "anthropic.claude-3-haiku-20240307-v1:0",
functionName: "conversation-handler",
systemPrompt: "You are a helpful chatbot."
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ type Mutation {
): ConversationMessage
@conversation(
aiModel: "anthropic.claude-3-haiku-20240307-v1:0",
functionName: "conversation-handler",
systemPrompt: "You are a helpful chatbot. Answer questions to the best of your ability.",
tools: [{ name: "listCustomers", description: "Provides data about the customer sending a message" }]
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ type Mutation {
): ConversationMessage
@conversation(
aiModel: "anthropic.claude-3-haiku-20240307-v1:0",
functionName: "conversation-handler",
systemPrompt: "You are a helpful chatbot. Answer questions to the best of your ability.",
tools: [{ name: "listTodos", description: "lists todos" }]
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ type Mutation {
@conversation(
aiModel: "anthropic.claude-3-haiku-20240307-v1:0",
systemPrompt: "You are a helpful chatbot. Answer questions to the best of your ability.",
functionName: "conversation-handler",
inferenceConfiguration: {
temperature: 0.5,
topP: 0.9,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { type ToolDefinition, type Tools } from './utils/tools';
import { ConversationPrepareHandler } from './transformer-steps/conversation-prepare-handler';
import { ConversationResolverGenerator } from './transformer-steps/conversation-resolver-generator';
import { ConversationFieldHandler } from './transformer-steps/conversation-field-handler';
import * as lambda from 'aws-cdk-lib/aws-lambda';

/**
* Configuration for the Conversation Directive
Expand Down Expand Up @@ -58,11 +59,12 @@ export class ConversationTransformer extends TransformerPluginBase {
hasManyTransformer: HasManyTransformer,
belongsToTransformer: BelongsToTransformer,
authProvider: TransformerAuthProvider,
functionNameMap?: Record<string, lambda.IFunction>,
) {
super('amplify-conversation-transformer', ConversationDirective.definition);
this.fieldHandler = new ConversationFieldHandler();
this.prepareHandler = new ConversationPrepareHandler(modelTransformer, hasManyTransformer, belongsToTransformer, authProvider);
this.resolverGenerator = new ConversationResolverGenerator();
this.resolverGenerator = new ConversationResolverGenerator(functionNameMap);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { APPSYNC_JS_RUNTIME, TransformerResolver } from '@aws-amplify/graphql-tr
import { ResolverResourceIDs, FunctionResourceIDs, ResourceConstants, toUpper } from 'graphql-transformer-common';
import * as cdk from 'aws-cdk-lib';
import { conversation } from '@aws-amplify/ai-constructs';
import { IFunction, Function } from 'aws-cdk-lib/aws-lambda';
import { IFunction } from 'aws-cdk-lib/aws-lambda';
import { getModelDataSourceNameForTypeName, getTable } from '@aws-amplify/graphql-transformer-core';
import { initMappingTemplate } from '../resolvers/init-resolver';
import { authMappingTemplate } from '../resolvers/auth-resolver';
Expand All @@ -24,6 +24,8 @@ type KeyAttributeDefinition = {

// TODO: add explanation for the tool model queries
export class ConversationResolverGenerator {
constructor(private readonly functionNameMap?: Record<string, IFunction>) {}

generateResolvers(directives: ConversationDirectiveConfiguration[], ctx: TransformerContextProvider): void {
for (const directive of directives) {
this.processToolsForDirective(directive, ctx);
Expand Down Expand Up @@ -89,7 +91,7 @@ export class ConversationResolverGenerator {
capitalizedFieldName: string,
): { functionDataSourceId: string; referencedFunction: IFunction } {
if (directive.functionName) {
return this.setupExistingFunctionDataSource(directive.functionName, functionStack);
return this.setupExistingFunctionDataSource(directive.functionName);
} else {
return this.setupDefaultConversationHandler(functionStack, capitalizedFieldName, directive.aiModel);
}
Expand All @@ -101,28 +103,18 @@ export class ConversationResolverGenerator {
* @param functionStack - The CDK stack to add the function to
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: delete

Suggested change
* @param functionStack - The CDK stack to add the function to

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks. will remove in follow up.

* @returns An object containing the function data source ID and the referenced function
*/
private setupExistingFunctionDataSource(
functionName: string,
functionStack: cdk.Stack,
): { functionDataSourceId: string; referencedFunction: IFunction } {
private setupExistingFunctionDataSource(functionName: string): { functionDataSourceId: string; referencedFunction: IFunction } {
const functionDataSourceId = FunctionResourceIDs.FunctionDataSourceID(functionName);
const referencedFunction = Function.fromFunctionAttributes(functionStack, `${functionDataSourceId}Function`, {
functionArn: this.lambdaArnResource(functionName),
});

if (!this.functionNameMap) {
throw new Error('Function name map is not provided');
}
const referencedFunction = this.functionNameMap[functionName];
if (!referencedFunction) {
throw new Error(`Function ${functionName} not found in function name map`);
}
return { functionDataSourceId, referencedFunction };
}

/**
* Generates the Lambda ARN resource string
* @param name - The name of the Lambda function
* @returns The Lambda ARN resource string
*/
private lambdaArnResource(name: string): string {
// eslint-disable-next-line no-template-curly-in-string
return cdk.Fn.sub('arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${name}', { name });
}

/**
* Sets up a default conversation handler function
* @param functionStack - The CDK stack to add the function to
Expand Down
1 change: 1 addition & 0 deletions packages/amplify-graphql-transformer-test-utils/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ export type TestTransformParameters = RDSLayerMappingProvider & RDSSNSTopicMappi
transformers: TransformerPluginProvider[];
transformParameters?: Partial<TransformParameters>;
userDefinedSlots?: Record<string, UserDefinedSlot[]>;
transformerManager?: TransformManager;
};

// @public (undocumented)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type TestTransformParameters = RDSLayerMappingProvider &
transformers: TransformerPluginProvider[];
transformParameters?: Partial<TransformParameters>;
userDefinedSlots?: Record<string, UserDefinedSlot[]>;
transformerManager?: TransformManager;
};

/**
Expand All @@ -52,6 +53,7 @@ export const testTransform = (params: TestTransformParameters): DeploymentResour
transformers,
transformParameters,
userDefinedSlots,
transformerManager,
} = params;

const transform = new GraphQLTransform({
Expand All @@ -63,7 +65,7 @@ export const testTransform = (params: TestTransformParameters): DeploymentResour
resolverConfig,
});

const transformManager = new TransformManager(overrideConfig);
const transformManager = transformerManager ?? new TransformManager(overrideConfig);

const authConfigTypes = [authConfig?.defaultAuthentication, ...(authConfig?.additionalAuthenticationProviders ?? [])].map(
(authConfigEntry) => authConfigEntry?.authenticationType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const constructTransformerChain = (options?: TransformerFactoryArgs): Tra
hasOneTransformer,
new ManyToManyTransformer(modelTransformer, indexTransformer, hasOneTransformer, authTransformer),
belongsToTransformer,
new ConversationTransformer(modelTransformer, hasManyTransformer, belongsToTransformer, authTransformer),
new ConversationTransformer(modelTransformer, hasManyTransformer, belongsToTransformer, authTransformer, options?.functionNameMap),
new GenerationTransformer(),
new DefaultValueTransformer(),
authTransformer,
Expand Down
Loading
Loading