#Predictions in Lambda

1 messages · Page 1 of 1 (latest)

hexed salmon
#

When trying to use Predictions.identify({}) from my Lambda function, I get the following error:

ERROR Invoke Error {"errorType":"NoCredentials","errorMessage":"Credentials should not be empty.","name":"NoCredentials","stack":["NoCredentials: Credentials should not be empty.","..."]}

How do I define the credentials?
This is my function.

import { Amplify } from 'aws-amplify'
import { generateClient } from 'aws-amplify/data';
import { Schema } from '../data/resource';
import { env } from '$amplify/env/processSupplierContractsWithDataAccess-handler';
import { Predictions } from '@aws-amplify/predictions';

Amplify.configure(
{
API: {
GraphQL: {
endpoint: env.AMPLIFY_DATA_GRAPHQL_ENDPOINT,
region: env.AWS_REGION,
defaultAuthMode: 'identityPool',
}
},
},
{
Auth: {
credentialsProvider: {
getCredentialsAndIdentityId: async () => ({
credentials: {
accessKeyId: env.AWS_ACCESS_KEY_ID,
secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
sessionToken: env.AWS_SESSION_TOKEN,
},
}),
clearCredentialsAndIdentityId: () => {
/* noop */
},
},
},
}
);

const dataClient = generateClient<Schema>();

export const handler: Schema["processDocumentRecord"]["functionHandler"] = async (event) => {

const { document } = event.arguments;
const documentText = await Predictions.identify({
    text: {
        source: {
            key: document!,
        },
        format: "ALL"
    },
})

console.log(documentText)
return "success";    

};

gleaming rivet
#

Hi @hexed salmon can you share how this lambda is configured in the backend code? Is it tied to a query/mutation in the schema or is it completely separate from the API?

hexed salmon
#

Hi @gleaming rivet , It is through a query.

here is my amplify/data/resource.ts

import { type ClientSchema, a, defineFunction, secret } from "@aws-amplify/backend";

const processDocumentRecordWithDataAccess = defineFunction({
entry: '../functions/processDocumentRecordWithDataAccess-handler.ts',
timeoutSeconds: 300,
memoryMB: 256,
environment: {
SENDGRID_API_KEY: secret('SENDGRID_API_KEY'),
}
});

const schema = a.schema({
processDocumentRecord: a
.query()
.arguments({
document: a.string(),
})
.returns(a.string())
.handler(a.handler.function(processDocumentRecordWithDataAccess))
.authorization((allow) => [allow.publicApiKey(),allow.authenticated()]),

})
.authorization(allow => [
allow.resource(processDocumentRecordWithDataAccess),
allow.authenticated('userPools'),
allow.authenticated('identityPool'),
]);
export type Schema = ClientSchema<typeof schema>;

gleaming rivet
hexed salmon
#

Ahh.. I missed this part

Amplify.configure({
...amplifyConfig,
Predictions: outputs.custom.Predictions,
});

How do I get this into my Amplify.configure? I don't have access to '../amplify_outputs.json' in Lambda

gleaming rivet
#

you should have access to it if you import from it

hexed salmon
#

I can reference amplify_outputs.json when running locally...

import { parseAmplifyConfig } from "aws-amplify/utils";
import outputs from '../../amplify_outputs.json';

const amplifyConfig = parseAmplifyConfig(outputs);

Amplify.configure({
...amplifyConfig,
Predictions: outputs.custom.Predictions,
});

but it breaks the build in staging...

error TS2307: Cannot find module '../../amplify_outputs.json' or its corresponding type declarations.

But that didn't fix my issue on local anyway

gleaming rivet
#

do you have a monorepo?

hexed salmon
#

No, its a single app

gleaming rivet
#
import type { Handler } from 'aws-lambda';
import type { Schema } from '../../data/resource';
import { Amplify } from 'aws-amplify';
import { generateClient } from 'aws-amplify/data';
import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime';
import { env } from '$amplify/env/<function-name>'; // replace with your function name

const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig(env);

Amplify.configure(resourceConfig, libraryOptions);

const client = generateClient<Schema>();

export const handler = async (event) => {
  // your function code goes here
}
hexed salmon
#

Thanks, that didn't return the full config, only the API. And still left me with my original error

{"errorType":"NoCredentials","errorMessage":"Credentials should not be empty.","name":"NoCredentials","stack":["NoCredentials: Credentials should not be empty."," at Ozi (file:///var/task/index.mjs:393:65975)"," at m5e.identifyText (file:///var/task/index.mjs:505:57993)"," at async Runtime.AQc [as handler] (file:///var/task/index.mjs:641:32459)"]}

It looks like that error is thrown where fetchAuthSession() fails.

    const { credentials } = await fetchAuthSession();
    assertValidationError(
        !!credentials,
        PredictionsValidationErrorCode.NoCredentials,
    );```