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

window is not defined in a Lambda function when creating InvokeModelCommand instance for Bedrock #1589

Open
3 tasks done
gpavlov2016 opened this issue May 13, 2024 · 5 comments
Assignees
Labels
pending-triage Incoming issues that need categorization transferred Issue was transferred from another Amplify repository

Comments

@gpavlov2016
Copy link

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Predictions

Amplify Version

v6

Amplify Categories

function, predictions

Backend

Amplify Gen 2 (Preview)

Environment information

# Put output below this line
System:
    OS: Windows 11 10.0.22631
    CPU: (20) x64 13th Gen Intel(R) Core(TM) i9-13900H
    Memory: 4.34 GB / 31.68 GB
  Binaries:
    Node: 18.19.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 10.2.4 - C:\Program Files\nodejs\npm.CMD
    pnpm: 8.15.4 - ~\AppData\Local\pnpm\pnpm.EXE
  Browsers:
    Edge: Chromium (123.0.2420.97)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    %name%:  0.1.0
    @ampproject/toolbox-optimizer:  undefined ()
    @aws-amplify/adapter-nextjs: ^1.1.5 => 1.1.6
    @aws-amplify/adapter-nextjs/api:  undefined ()
    @aws-amplify/adapter-nextjs/data:  undefined ()
    @aws-amplify/backend: ^1.0.0 => 1.0.1
    @aws-amplify/backend-cli: ^1.0.1 => 1.0.2
    @aws-amplify/ui-react: ^6.1.9 => 6.1.9
    @aws-amplify/ui-react-internal:  undefined ()
    @aws-cdk/asset-awscli-v1: ^2.2.202 => 2.2.202
    @aws-sdk/client-bedrock-runtime: ^3.569.0 => 3.574.0
    @babel/core:  undefined ()
    @babel/runtime:  7.22.5
    @edge-runtime/cookies:  4.1.1
    @edge-runtime/ponyfill:  2.4.2
    @edge-runtime/primitives:  4.1.0
    @hapi/accept:  undefined ()
    @headlessui/react: ^1.7.17 => 1.7.19
    @heroicons/react: ^2.1.3 => 2.1.3
    @mswjs/interceptors:  undefined ()
    @napi-rs/triples:  undefined ()
    @next/font:  undefined ()
    @opentelemetry/api:  undefined ()
    @svgr/webpack: ^8.1.0 => 8.1.0
    @tailwindcss/forms: ^0.5.7 => 0.5.7
    @types/next: ^9.0.0 => 9.0.0
    @types/node: ^20.10.4 => 20.12.11
    @types/react: ^18.2.42 => 18.3.2
    @types/react-dom: ^18.2.17 => 18.3.0
    @types/react-flatpickr: ^3.8.11 => 3.8.11
    @ungap/with-resolvers: github:ungap/with-resolvers => 0.1.0
    @vercel/nft:  undefined ()
    @vercel/og:  0.6.2
    acorn:  undefined ()
    amphtml-validator:  undefined ()
    anser:  undefined ()
    arg:  undefined ()
    assert:  undefined ()
    async-retry:  undefined ()
    async-sema:  undefined ()
    autoprefixer: ^10.4.16 => 10.4.19
    aws-amplify: ^6.2.0 => 6.3.0
    aws-amplify/adapter-core:  undefined ()
    aws-amplify/analytics:  undefined ()
    aws-amplify/analytics/kinesis:  undefined ()
    aws-amplify/analytics/kinesis-firehose:  undefined ()
    aws-amplify/analytics/personalize:  undefined ()
    aws-amplify/analytics/pinpoint:  undefined ()
    aws-amplify/api:  undefined ()
    aws-amplify/api/server:  undefined ()
    aws-amplify/auth:  undefined ()
    aws-amplify/auth/cognito:  undefined ()
    aws-amplify/auth/cognito/server:  undefined ()
    aws-amplify/auth/enable-oauth-listener:  undefined ()
    aws-amplify/auth/server:  undefined ()
    aws-amplify/data:  undefined ()
    aws-amplify/data/server:  undefined ()
    aws-amplify/datastore:  undefined ()
    aws-amplify/in-app-messaging:  undefined ()
    aws-amplify/in-app-messaging/pinpoint:  undefined ()
    aws-amplify/push-notifications:  undefined ()
    aws-amplify/push-notifications/pinpoint:  undefined ()
    aws-amplify/storage:  undefined ()
    aws-amplify/storage/s3:  undefined ()
    aws-amplify/storage/s3/server:  undefined ()
    aws-amplify/storage/server:  undefined ()
    aws-amplify/utils:  undefined ()
    aws-cdk: ^2.140.0 => 2.141.0
    aws-cdk-lib: ^2.140.0 => 2.141.0
    aws-lambda: ^1.0.7 => 1.0.7
    babel-packages:  undefined ()
    browserify-zlib:  undefined ()
    browserslist:  undefined ()
    buffer:  undefined ()
    bytes:  undefined ()
    chart.js: ^4.4.1 => 4.4.2
    chart.js-auto:  undefined ()
    chart.js-helpers:  undefined ()
    chartjs-adapter-moment: ^1.0.1 => 1.0.1
    ci-info:  undefined ()
    cli-select:  undefined ()
    client-only:  0.0.1
    commander:  undefined ()
    comment-json:  undefined ()
    compression:  undefined ()
    conf:  undefined ()
    constants-browserify:  undefined ()
    constructs: ^10.3.0 => 10.3.0
    content-disposition:  undefined ()
    content-type:  undefined ()
    cookie:  undefined ()
    cross-spawn:  undefined ()
    crypto-browserify:  undefined ()
    css.escape:  undefined ()
    data-uri-to-buffer:  undefined ()
    debug:  undefined ()
    devalue:  undefined ()
    domain-browser:  undefined ()
    edge-runtime:  undefined ()
    esbuild: ^0.20.2 => 0.20.2
    eslint: ^8 => 8.57.0
    eslint-config-next: 14.2.3 => 14.2.3
    events:  undefined ()
    find-cache-dir:  undefined ()
    find-up:  undefined ()
    fresh:  undefined ()
    get-orientation:  undefined ()
    glob:  undefined ()
    gzip-size:  undefined ()
    http-proxy:  undefined ()
    http-proxy-agent:  undefined ()
    https-browserify:  undefined ()
    https-proxy-agent:  undefined ()
    icss-utils:  undefined ()
    ignore-loader:  undefined ()
    image-size:  undefined ()
    is-animated:  undefined ()
    is-docker:  undefined ()
    is-wsl:  undefined ()
    jest-worker:  undefined ()
    json5:  undefined ()
    jsonwebtoken:  undefined ()
    loader-runner:  undefined ()
    loader-utils:  undefined ()
    lodash.curry:  undefined ()
    lru-cache:  undefined ()
    mini-css-extract-plugin:  undefined ()
    nanoid:  undefined ()
    native-url:  undefined ()
    neo-async:  undefined ()
    next: ^14.0.3 => 14.2.3
    next-themes: ^0.2.1 => 0.2.1
    node-fetch:  undefined ()
    node-html-parser:  undefined ()
    ora:  undefined ()
    os-browserify:  undefined ()
    p-limit:  undefined ()
    path-browserify:  undefined ()
    pdfjs-dist: ^4.2.67 => 4.2.67
    picomatch:  undefined ()
    platform:  undefined ()
    postcss: ^8.4.32 => 8.4.38 (8.4.31)
    postcss-flexbugs-fixes:  undefined ()
    postcss-modules-extract-imports:  undefined ()
    postcss-modules-local-by-default:  undefined ()
    postcss-modules-scope:  undefined ()
    postcss-modules-values:  undefined ()
    postcss-preset-env:  undefined ()
    postcss-safe-parser:  undefined ()
    postcss-scss:  undefined ()
    postcss-value-parser:  undefined ()
    process:  undefined ()
    punycode:  undefined ()
    querystring-es3:  undefined ()
    raw-body:  undefined ()
    react: 18.2.0 => 18.2.0
    react-builtin:  undefined ()
    react-dom: 18.2.0 => 18.2.0
    react-dom-builtin:  undefined ()
    react-dom-experimental-builtin:  undefined ()
    react-experimental-builtin:  undefined ()
    react-flatpickr: ^3.10.13 => 3.10.13
    react-is:  18.2.0
    react-refresh:  0.12.0
    react-server-dom-turbopack-builtin:  undefined ()
    react-server-dom-turbopack-experimental-builtin:  undefined ()
    react-server-dom-webpack-builtin:  undefined ()
    react-server-dom-webpack-experimental-builtin:  undefined ()
    regenerator-runtime:  0.13.4
    sass-loader:  undefined ()
    scheduler-builtin:  undefined ()
    scheduler-experimental-builtin:  undefined ()
    schema-utils:  undefined ()
    semver:  undefined ()
    send:  undefined ()
    server-only:  0.0.1
    setimmediate:  undefined ()
    shell-quote:  undefined ()
    source-map:  undefined ()
    source-map08:  undefined ()
    stacktrace-parser:  undefined ()
    stream-browserify:  undefined ()
    stream-http:  undefined ()
    string-hash:  undefined ()
    string_decoder:  undefined ()
    strip-ansi:  undefined ()
    superstruct:  undefined ()
    tailwindcss: ^3.3.6 => 3.4.3
    tar:  undefined ()
    terser:  undefined ()
    text-table:  undefined ()
    timers-browserify:  undefined ()
    tsx: ^4.9.3 => 4.10.1
    tty-browserify:  undefined ()
    typescript: ^5.3.3 => 5.4.5 (4.4.4, 4.9.5)
    ua-parser-js:  undefined ()
    unistore:  undefined ()
    util:  undefined ()
    vm-browserify:  undefined ()
    watchpack:  undefined ()
    web-vitals:  undefined ()
    webpack:  undefined ()
    webpack-sources:  undefined ()
    ws:  undefined ()
    zod:  undefined ()
  npmGlobalPackages:
    @aws-amplify/cli: 12.10.3
    corepack: 0.22.0
    create-next-app: 14.2.3
    npm: 10.2.4

Describe the bug

Following the documentation here, the invocation of the function produces an error while importing the Bedrock Runtime.
Function:

import type { Schema } from "../../data/resource";
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
  InvokeModelCommandInput,
} from "@aws-sdk/client-bedrock-runtime";
import { MODEL_ID } from "./resource";

export const handler: Schema["handler"]["functionHandler"] = async (
  event,
  context
) => {
  // User prompt
  const prompt = event.arguments.prompt;

  const AWS_REGION = "us-east-1";

  const messages = [{
    role: "user",
    content: `${prompt}
    Here is the context: ######`
}]

// Create a new Bedrock Runtime client instance.
const client = new BedrockRuntimeClient({ region: AWS_REGION });

// Prepare the payload for the model.
const payload = {
    anthropic_version: "bedrock-2023-05-31",
    max_tokens: 2000,
    messages: messages,
    // temperature: 0,
    // top_p: 1,
};
const command = new InvokeModelCommand({
  contentType: "application/json",
  body: JSON.stringify(payload),
  modelId: MODEL_ID,
})

  return prompt;
};

Error:

{
"errorType": "ReferenceError",
"errorMessage": "window is not defined",
"stack": [
"ReferenceError: window is not defined",
" at exports3.default (file:///var/task/index.mjs:637376:71)",
" at Object. (file:///var/task/index.mjs:636120:46)",
" at webpack_require (file:///var/task/index.mjs:636023:31)",
" at Object. (file:///var/task/index.mjs:636038:38)",
" at webpack_require (file:///var/task/index.mjs:636023:31)",
" at file:///var/task/index.mjs:636030:18",
" at file:///var/task/index.mjs:636031:10",
" at webpackUniversalModuleDefinition (file:///var/task/index.mjs:635999:27)",
" at node_modules/handlebars/dist/handlebars.js (file:///var/task/index.mjs:636006:7)",
" at __require2 (file:///var/task/index.mjs:19:50)"
]
}

Expected behavior

Function should execute without errorsThe function

Reproduction steps

  1. Define a custom query with a function handler as shown in the configuration
  2. Define the function handler using the code above (mostly follows the documentation)
  3. Call the custom query that invokes the handler from an API handler in Next.js app/api folder as follows:
const { data, errors } = await cookiesClient.queries.customQuery({
    prompt,
  });

Observe the error in Cloudwatch for the handler and in the errors member above.

Code Snippet

// Put your code below this line.

Log output

// Put your logs below this line


aws-exports.js

No response

Manual configuration

No response

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

@gpavlov2016 gpavlov2016 added the pending-triage Incoming issues that need categorization label May 13, 2024
@cwomack cwomack assigned cwomack and chrisbonifacio and unassigned cwomack May 14, 2024
@chrisbonifacio
Copy link

Hi @gpavlov2016, thanks for raising this issue.

Copy/pasting the function from the docs example seems to work fine, but I am able to reproduce the issue using the hanlder logic you provided.

Not sure why exactly this was causing the window is not defined error but the issue seems to be the importing of the MODEL_ID from the resource file rather than just the Schema type, probably importing something else from that file that is using the window object.

I basically just replaced the import of MODEL_ID to be an environment as shown in the docs example and that seems to work.

// amplify/data/resource.ts
export const MODEL_ID = "anthropic.claude-3-haiku-20240307-v1:0";

export const generateHaikuFunction = defineFunction({
  entry: "generateHaiku.ts",
  environment: {
    MODEL_ID,
  },
});
// generate-haiku.ts

import type { Schema } from "./resource";
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
  InvokeModelCommandInput,
} from "@aws-sdk/client-bedrock-runtime";

export const handler: Schema["generateHaiku"]["functionHandler"] = async (
  event,
  context
) => {
  // User prompt
  const prompt = event.arguments.prompt;

  const AWS_REGION = "us-east-1";

  const messages = [
    {
      role: "user",
      content: `${prompt}
    Here is the context: ######`,
    },
  ];

  // Create a new Bedrock Runtime client instance.
  const client = new BedrockRuntimeClient({ region: AWS_REGION });

  // Prepare the payload for the model.
  const payload = {
    anthropic_version: "bedrock-2023-05-31",
    max_tokens: 2000,
    messages: messages,
    // temperature: 0,
    // top_p: 1,
  };

  const command = new InvokeModelCommand({
    contentType: "application/json",
    body: JSON.stringify(payload),
    modelId: process.env.MODEL_ID,
  });

  const response = await client.send(command);

  // Parse the response and return the generated haiku
  const data = JSON.parse(Buffer.from(response.body).toString());

  return data.content[0].text;
};

@chrisbonifacio chrisbonifacio added question Question or confusion about some aspect of the product pending-response Issue is pending response from author and removed pending-triage Incoming issues that need categorization labels May 17, 2024
@chrisbonifacio
Copy link

chrisbonifacio commented May 17, 2024

Coming back to this, I tried the code I shared above a few times and noticed that the query would error intermittently. I also can't see any error messages in the cloudwatch logs.

My best guess is that perhaps the requests are being rate limited but sometimes I get nothing but Unhandled lambda errors for quite a while and randomly a query will work.

I'll keep digging into this, discuss with the team, and come back with any findings.

Weirdly enough, the snippet from the docs works every time. Only have issues with the code above but there's no obvious difference that might explain what the issue is 🤔

@chrisbonifacio chrisbonifacio changed the title window is not defined in a Lambda function when creating InvokeModelCommand isntance for Bedrock window is not defined in a Lambda function when creating InvokeModelCommand instance for Bedrock May 23, 2024
@chrisbonifacio chrisbonifacio added bug Something isn't working and removed pending-response Issue is pending response from author labels May 23, 2024
@david-mcafee david-mcafee transferred this issue from aws-amplify/amplify-js May 30, 2024
@david-mcafee
Copy link
Member

I've transferred this ticket from amplify-js as this might be backend related. If not, is there potentially something incorrect in the docs linked in the ticket description?

@josefaidt josefaidt added pending-triage Incoming issues that need categorization transferred Issue was transferred from another Amplify repository and removed bug Something isn't working question Question or confusion about some aspect of the product labels May 30, 2024
@josefaidt
Copy link
Contributor

Hey @gpavlov2016 👋 the error is a bit interesting. Is the source code shared in the original post the full handler code? The dependencies used there shouldn't produce a webpack/handlebars error, nor look for a window global. Is that an error you're seeing in your frontend from calling the Lambda, or the error in your Lambda's execution logs?

@josefaidt josefaidt added the pending-response Issue is pending response from author label May 30, 2024
@gpavlov2016
Copy link
Author

The error is showing when amplify is trying to update the stack while you have 'npx amplify sandbox' running and saving the file. Therefore I don't think it's a backend issue, most likely related to webpack.
My original handler was larger but I narrowed it down to the instantiation of the bedrock runtime module. If I remove the statement everything works. As soon as I add it and save the error is shown, before the code is even deployed

@github-actions github-actions bot removed the pending-response Issue is pending response from author label May 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pending-triage Incoming issues that need categorization transferred Issue was transferred from another Amplify repository
Projects
None yet
Development

No branches or pull requests

5 participants