langchain-ai / langchainjs

🦜🔗 Build context-aware reasoning applications 🦜🔗
https://js.langchain.com/docs/
MIT License
12.43k stars 2.1k forks source link

Cannot find name 'this' #4043

Closed bryantpa closed 6 months ago

bryantpa commented 8 months ago

getting the following error when compiling in node 18 environment on my express server with ts: node_modules/@langchain/core/dist/language_models/chat_models.d.ts(64,129): error TS2304: Cannot find name 'this'. node_modules/@langchain/core/dist/language_models/llms.d.ts(66,122): error TS2304: Cannot find name 'this'.

updated from "langchain": "^0.0.72" due to davinci deprecation

here is my package.json:

{
    "name": "docker_web_app",
    "description": "A web app to serve apis",
    "type": "module",
    "scripts": {
        "testingRun": "node src/server.ts",
        "clean": "rimraf dist/*",
        "lint": "eslint . --ext .ts --fix",
        "build": "npm-run-all clean lint tsc",
        "tsc": "tsc",
        "start": "node ./dist/server.js",
        "dev:start": "npm-run-all build start",
        "dev": "nodemon --watch,ejs --exec npm run dev:start",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "dependencies": {
        "@aws-sdk/client-cloudfront": "^3.363.0",
        "@aws-sdk/client-s3": "^3.362.0",
        "@aws-sdk/s3-request-presigner": "^3.362.0",
        "@babel/cli": "^7.23.0",
        "@babel/node": "^7.22.19",
        "@babel/preset-typescript": "^7.23.2",
        "@dropbox/sign": "^1.1.3",
        "@pdf-lib/fontkit": "^1.1.1",
        "@react-pdf/renderer": "^3.1.14",
        "@sendgrid/mail": "^7.7.0",
        "@types/node": "^18.11.3",
        "@types/react": "^18.2.36",
        "@types/react-dom": "^18.2.14",
        "@types/validator": "^13.7.16",
        "@types/ws": "^8.5.4",
        "@typescript-eslint/eslint-plugin": "^5.40.1",
        "@typescript-eslint/parser": "^5.40.1",
        "axios": "^1.1.3",
        "bcrypt": "^5.1.0",
        "body-parser": "^1.20.0",
        "config": "^3.3.7",
        "cookie-parser": "^1.4.6",
        "cors": "^2.8.5",
        "dateformat": "^5.0.3",
        "dayjs": "^1.11.9",
        "dayjs-plugin-utc": "^0.1.2",
        "docxtemplater": "^3.31.3",
        "dotenv": "^16.0.1",
        "ejs": "^3.1.8",
        "eslint": "^8.26.0",
        "exec": "^0.2.1",
        "express": "^4.18.2",
        "express-validator": "^7.0.1",
        "jsonwebtoken": "^8.5.1",
        "langchain": "^0.1.3",
        "multer": "^1.4.5-lts.1",
        "mysql2": "^2.3.3",
        "npm-run-all": "^4.1.5",
        "numeral": "^2.0.6",
        "pdf-lib": "^1.17.1",
        "react": "^18.2.0",
        "react-pdf": "^7.5.1",
        "reflect-metadata": "^0.1.13",
        "sequelize": "^6.31.1",
        "sequelize-typescript": "^2.1.5",
        "shelljs": "^0.8.5",
        "tmp": "^0.2.1",
        "twilio": "^3.84.0",
        "typeorm": "^0.3.16",
        "typescript": "^5.0.4",
        "ws": "^8.13.0"
    },
    "devDependencies": {
        "@babel/core": "^7.23.2",
        "@babel/preset-env": "^7.23.2",
        "@babel/preset-react": "^7.22.15",
        "@types/express": "^4.17.20",
        "@types/express-serve-static-core": "^4.17.37",
        "@types/multer": "^1.4.7",
        "@types/stream-to-promise": "^2.2.4",
        "@types/tmp": "^0.2.3",
        "babel-loader": "^9.1.3",
        "install": "^0.13.0",
        "nodemon": "^2.0.19",
        "npm": "^10.2.0",
        "ts-node": "^10.9.1",
        "webpack": "^5.89.0",
        "webpack-cli": "^5.1.4"
    }
}

and tsconfig

{
    "compilerOptions": {
        "module": "ES2022",
        "esModuleInterop": true,
        "target": "ES2022",
        "jsx": "react",
        "lib": [
            "ES2022",
            "DOM"
        ],
        "moduleResolution": "node",
        "forceConsistentCasingInFileNames": true,
        "noImplicitAny": false,
        "strict": false,
        "noImplicitReturns": false,
        "strictPropertyInitialization": false,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "allowJs": true,
        "noUnusedLocals": true,
        "sourceMap": true,
        "outDir": "dist",
        "rootDir": "src",
    },
    "include": [
        "**/*.ts",
        "**/*.tsx",
    ],
    "exclude": [
        "node_modules",
        "dist",
        "**/*.js"
    ]
}
dosubot[bot] commented 8 months ago

🤖

Hello @bryantpa! Just wanted to jump in and say a quick hello. I'm Dosu, a friendly bot here to assist you with any bugs, questions, or contributions while you wait for a human maintainer. Looking forward to helping you out!

The error you're encountering, "Cannot find name 'this'", typically occurs when the this keyword is used in a context where it's not defined. In TypeScript, this is not bound in arrow functions and always represents the object that defined the arrow function.

The error is likely happening because this is being accessed inside an arrow function where it's not defined. To resolve this issue, you could convert the arrow function to a regular function and use the bind method to bind this to the appropriate context. Here's an example:

private transform(parsed: CallExpressionType): Operation | Comparison {
    const traverse = function(node: ParsedType): TraverseType {
      // ...
    }.bind(this);
    return traverse(parsed) as Operation | Comparison;
  }

In this code, traverse is converted to a regular function and this is bound to the appropriate context using the bind method. Now, this inside traverse will refer to the correct context, and you should no longer get the "Cannot find name 'this'" error.

However, this is a general solution and might not apply directly to your case as I don't have visibility into the exact code causing the issue. If the error is coming from within the langchain package, it might be an issue with the package itself. In that case, you might want to reach out to the maintainers of the package or check if there's an updated version that resolves this issue.

Also, I noticed that you're using TypeScript version 5.0.4 in your project. According to the LangChain.js compatibility information, LangChain.js is compatible with TypeScript versions less than 5.2.0. So, your TypeScript version should be compatible with LangChain.js.

If the issue persists, could you please provide more information about the context in which the error occurs? Specifically, the part of your code where you're using the langchain package would be helpful. This will allow me to provide a more accurate solution.

Sources


This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.

Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.

If you want to continue the conversation, start your reply with @dosu-bot.

RingoTC commented 8 months ago

Can't reproduce your situation, can you provide me more detail informations?

jacoblee93 commented 8 months ago

You can also leave it at your old version and just change model name to gpt-3.5-turbo-instruct.

mdnazim5 commented 8 months ago

I am facing the exact same issue during the build of my project that is using langchain. My use case is that I am trying to write a wrapper class extending the ChatOpenAI class and override the _generate method. The reason for doing this is because my organization uses OpenAI model with OAuth2 authentication. The code for the wrapper class is given below,

import { CallbackManagerForLLMRun } from "langchain/callbacks";
import { BaseMessage, ChatResult} from "langchain/schema";
import { BaseLLMParams } from "langchain/llms/base";
import { ChatOpenAI, OpenAIInput } from "@langchain/openai";

export interface CustomOpenAIGPTInput
  extends Omit<OpenAIInput, "modelName" | "openAIApiKey" | "streaming">,
  CustomBaseLLMParameters<CustomOpenAIGPTTextModel>,
    BaseLLMParams {}

export interface CustomBaseLLMParameters<T extends string> {
        deployment_id: T;
}
export type CustomOpenAIGPTTextModel = "text-davinci-003" | "code-davinci-002" | "gpt-35-turbo-instruct";

export class CustomChatOpenAI extends ChatOpenAI {

  constructor(fields?: Partial<CustomOpenAIGPTInput>) {
    super({ ...fields, modelName: "gpt-3.5-turbo-instruct", openAIApiKey: "dummy" });
  }

  override async _generate(
    messages: BaseMessage[],
    options: this["ParsedCallOptions"],
    runManager?: CallbackManagerForLLMRun
  ): Promise<ChatResult> {
    // add custom logic here with custom authentication and custom inference url
  }
}

export const CustomOpenAI = CustomChatOpenAI;

The langchain version that i use in my package.json is "langchain": "^0.1.4"

And when I try to build with the custom class in my project I get the following error image

jacoblee93 commented 8 months ago

Maybe try setting skipLibCheck in your tsconfig?

https://www.typescriptlang.org/tsconfig#skipLibCheck

mdnazim5 commented 8 months ago

@jacoblee93 : Worked with your suggestion.

bryantpa commented 8 months ago

You can also leave it at your old version and just change model name to gpt-3.5-turbo-instruct.

This is what I did to fix except used a newer model. Don't want to do skiplibcheck with prod. Confused as to why this happens though. Using ts 5.0.4 in a node18 docker container

jacoblee93 commented 8 months ago

Yeah not sure either @bryantpa - one thing that stands out in your tsconfig is that "moduleResolution": "node" is quite old:

https://www.typescriptlang.org/tsconfig#moduleResolution

Maybe bump to nodenext?

mdnazim5 commented 8 months ago

@jacoblee93 : I agree with @bryantpa. The skipLibCheck is a temporary hack to unblock. For productive releases it is a problem. We do also use node 18 in our project (typescript version used is ^4.8.2). Could it be an compatibility issue with Node 18?

jacoblee93 commented 8 months ago

Can you give me your tsconfig + package.json @mdnazim5?

mdnazim5 commented 8 months ago

@jacoblee93 : Below you can find a zip file with lean project setup using which I could reproduce the issue. I have also attached the package.json and tsconfig.json file

package.json tsconfig.json langchain-build-error.zip

Fgabz commented 8 months ago

Hey I'm facing the exact same issue on a new project using Firebase cloud functions

package.json:

{
  "name": "functions",
  "scripts": {
    "lint": "eslint --ext .js,.ts .",
    "build": "tsc",
    "build:watch": "tsc --watch",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "18"
  },
  "main": "lib/index.js",
  "dependencies": {
    "@langchain/community": "^0.0.26",
    "@langchain/core": "^0.1.25",
    "@langchain/openai": "^0.0.14",
    "firebase-admin": "^11.8.0",
    "firebase-functions": "^4.3.1",
    "langchain": "^0.1.17"
  },
  "type": "commonjs",
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.12.0",
    "@typescript-eslint/parser": "^5.12.0",
    "eslint": "^8.9.0",
    "eslint-config-google": "^0.14.0",
    "eslint-plugin-import": "^2.25.4",
    "firebase-functions-test": "^3.1.0",
    "typescript": "^4.9.0"
  },
  "resolutions": {
    "@langchain/core": "0.1.25"
  },
  "private": true
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

funtion.ts

import { onCall } from "firebase-functions/v2/https"
import { ChatOpenAI } from "@langchain/openai"

export const createStory = onCall(
  { secrets: ["OPENAI_API_KEY"], region: "REGION" },
  async (request) => {
    const OPEN_AI_API_KEY = "HELLO_WORLD"

    const chatModel = new ChatOpenAI({
      openAIApiKey: OPEN_AI_API_KEY
    })

    return await chatModel.invoke("what is LangSmith?")
  })
jacoblee93 commented 7 months ago

I notice you're both on TypeScript 4 - could you try bumping to 5?

mdnazim5 commented 7 months ago

@jacoblee93 : With typescript version 5 the issue no longer is observable.

dehmlowm commented 6 months ago

@Fgabz @bryantpa Curious if you found a way to resolve this issue or just went with directly implementing the vendor api.

Seeing this on 0.1.28

I've boiled this down to a pretty tight example: package.json

{
  "name": "lanfgtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "tsc",
    "tsversion": "tsc -v",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^5.4.2"
  },
  "dependencies": {
    "langchain": "^0.1.28"
  }
}

tsconfig.json

{

  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "ES2020",
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

index.ts:

import {ChatOpenAI} from "@langchain/openai";
console.log(ChatOpenAI);

result:

node_modules/@langchain/openai/dist/utils/openai.d.ts:6:103 - error TS2724: '"~/Development/langchainjs/lanfgtest/node_modules/openai/resources/beta/beta".Beta' has no exported member named 'AssistantCreateParams'. Did you mean 'AssistantUpdateParams'?

6 export declare function formatToOpenAIAssistantTool(tool: StructuredToolInterface): OpenAIClient.Beta.AssistantCreateParams.AssistantToolsFunction;
                                                                                                        ~~~~~~~~~~~~~~~~~~~~~

Found 1 error in node_modules/@langchain/openai/dist/utils/openai.d.ts:6

ZIP: lanfgtest.zip

  1. npm install
  2. npm run build
dehmlowm commented 6 months ago

Alright so this issue started in release 0.204 Forcing the version back to 0.0.203 produces no error:

{
  "name": "lanfgtest",
  "version": "1.0.0",
  "description": "",
  "main": "lib/index.js",
  "scripts": {
    "build": "tsc",
    "tsversion": "tsc -v",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "engines": {
    "node": "20"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^5.4.2"
  },
  "dependencies": {
    "langchain": "0.0.203",
    "typescript": "^5.4.2"
  }
}

Forcing issue to 0.0.204 or higher will produce the .Beta' has no exported member named 'AssistantCreateParams issue:

{
  "name": "lanfgtest",
  "version": "1.0.0",
  "description": "",
  "main": "lib/index.js",
  "scripts": {
    "build": "tsc",
    "tsversion": "tsc -v",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "engines": {
    "node": "20"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^5.4.2"
  },
  "dependencies": {
    "langchain": "0.0.204",
    "typescript": "^5.4.2"
  }
}
jacoblee93 commented 6 months ago

Hmm that was removed from the OpenAI SDK a while ago - what if you update to the latest LangChain?

dehmlowm commented 6 months ago

Okay very interesting if I run on the latest version without cleaning my npm_modules or package_lock.json then it will build. However if clean everything and start fresh I get this error: With: "langchain": "^0.1.28"

node_modules/@langchain/openai/dist/utils/openai.d.ts:6:103 - error TS2724: '"~/Development/langchainjs/lanfgtest/node_modules/openai/resources/beta/beta".Beta' has no exported member named 'AssistantCreateParams'. Did you mean 'AssistantUpdateParams'?

6 export declare function formatToOpenAIAssistantTool(tool: StructuredToolInterface): OpenAIClient.Beta.AssistantCreateParams.AssistantToolsFunction;
                                                                                                        ~~~~~~~~~~~~~~~~~~~~~

Found 1 error in node_modules/@langchain/openai/dist/utils/openai.d.ts:6

The issue of course is on my build server I start fresh every time. This behavior occurs in the sample i provided if you just upgrade to ^0.1.28 and: npm install npm run build

dev@local lanfgtest % npm run build

> lanfgtest@1.0.0 build
> tsc
dev@local lanfgtest % rm -rf ./node_modules
…
dev@local lanfgtest % rm ./package_lock.json

dev@local lanfgtest % npm i        

added 71 packages, and audited 72 packages in 40s

9 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
dev@local lanfgtest % npm run build

> lanfgtest@1.0.0 build
> tsc

node_modules/@langchain/openai/dist/utils/openai.d.ts:6:103 - error TS2724: ‘”~/Development/langchainjs/lanfgtest/node_modules/openai/resources/beta/beta".Beta' has no exported member named 'AssistantCreateParams'. Did you mean 'AssistantUpdateParams'?

6 export declare function formatToOpenAIAssistantTool(tool: StructuredToolInterface): OpenAIClient.Beta.AssistantCreateParams.AssistantToolsFunction;
                                                                                                        ~~~~~~~~~~~~~~~~~~~~~

Found 1 error in node_modules/@langchain/openai/dist/utils/openai.d.ts:6

dev@local lanfgtest % 
williamwinkler commented 6 months ago

I'm also getting the same error

node_modules/@langchain/openai/node_modules/openai/resources/beta/beta".Beta' has no exported member named 'AssistantCreateParams'. Did you mean 'AssistantUpdateParams'?

I'm running on typescript 5.4.2 with package.json

 "dependencies": {
    "@langchain/openai": "^0.0.23",
dehmlowm commented 6 months ago

@williamwinkler I was able to get around it by adding the following to my tsconf.json>compilerOptions:
"skipLibCheck": true,

This has been creeping in since v 0.0.94 depending on what modules you use. Looks like core broke about 3 months ago with 0.0.204.

Heres my entire build file for the example (this deploys and launches on firebase functions):

{

  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,  
    "outDir": "lib",
    "sourceMap": true,
    "target": "es2022",
    "esModuleInterop": true,
    "strict": true,
    "declaration": false,
    "skipLibCheck": true,

    "resolveJsonModule": true,
  },
  "include": [
    "src"
  ]
}
jacoblee93 commented 6 months ago

Let me give this another look today.

JAEHOON-1993 commented 6 months ago

@williamwinkler I was able to get around it by adding the following to my tsconf.json>compilerOptions: "skipLibCheck": true,

This has been creeping in since v 0.0.94 depending on what modules you use. Looks like core broke about 3 months ago with 0.0.204.

Heres my entire build file for the example (this deploys and launches on firebase functions):

{

  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,  
    "outDir": "lib",
    "sourceMap": true,
    "target": "es2022",
    "esModuleInterop": true,
    "strict": true,
    "declaration": false,
    "skipLibCheck": true,

    "resolveJsonModule": true,
  },
  "include": [
    "src"
  ]
}

I love you. It works for me.

bradleat commented 6 months ago

this issue is tracking the problem.

'node_modules/openai/resources/beta/beta".Beta' has no exported member named 'AssistantCreateParams'. Did you mean 'AssistantUpdateParams'?

export declare function formatToOpenAIAssistantTool(tool: StructuredToolInterface): OpenAIClient.Beta.AssistantCreateParams.AssistantToolsFunction;

https://github.com/langchain-ai/langchainjs/issues/4850

jacoblee93 commented 6 months ago

Hey, I think I've identified the issue - has to do with some of our OpenAI assistant typing. I think something got removed in a minor version (CC @rattrayalex)

I'm removing the types, which should hopefully fix it.

jacoblee93 commented 6 months ago

Bumping to latest langchain@0.1.31 and @langchain/openai@0.0.26 should fix the most recent iteration of this - apologies for the delay!

pstern-sl commented 6 months ago

@jacoblee93 Hi, I have been working on the openai-node package. I am catching up on this and I think perhaps the underlying issue here was renamed some of tools types in the beta namespace? Could you point me to the change you made on your side to resolve this so I can better track down what may have happened here? Thank you!

jacoblee93 commented 6 months ago

Hey @pstern-sl! Thanks for checking in. Yes, it appears this was the most recent issue:

https://github.com/langchain-ai/langchainjs/pull/4972/files#diff-c53a80ec7ebf0687a7d98fd20e35a51cac5473a9585eaac7e54360255c9e0d16L12

The original issue was something different that was fixed previously - the issue thread got hijacked.

pstern-sl commented 6 months ago

@jacoblee93, ok great! I reviewed the change and confirmed the issue here was we renamed some Tool types as part of the Assistant helper streaming release. This was intentional, and we were aware this could cause some friction, but felt comfortable doing this in the beta namespace (ideally we get everything sorted while in beta and then there should be no changes like this when it is promoted). That said, if you have any feedback or thoughts on what stainless could have done better please let us know! I will also flag internally for us to discuss.

jacoblee93 commented 6 months ago

Yeah fair enough - in the future would be nice to keep the old types around in minor/patch releases but we can be more wary of beta types as well!

pstern-sl commented 6 months ago

Noted, thank you!