langchain-ai / langchainjs

πŸ¦œπŸ”— Build context-aware reasoning applications πŸ¦œπŸ”—
https://js.langchain.com/docs/
MIT License
12.64k stars 2.17k forks source link

TS Error: Cannot find name 'this' #5233

Closed Dranaxel closed 6 months ago

Dranaxel commented 6 months ago

Checked other resources

Example Code

import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'
import * as OpenAI from 'openai'
import * as logger from 'firebase-functions/logger'
import mustache = require('mustache')
import { ChatAnthropicMessages } from '@langchain/anthropic'
import firebase, { getFunctions } from 'firebase/functions'
import { getApp, getApps, initializeApp } from 'firebase/app'

// Firebase Admin SDK to access Firestore.
admin.initializeApp()

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
}

// Initialize Firebase for SSR
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp()

const db = admin.firestore()
const openai = new OpenAI.OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
})

const anthropic = new ChatAnthropicMessages({
  temperature: 1,
  model: 'claude-3-haiku-20240307',
  apiKey: process.env.ANTHROPIC_API_KEY,
})

/**
 * Create the story entry
 */
export const createStoryReference = functions.https.onCall(
  async (data, context) => {
    const owner = context.auth?.uid

    const doc = await db.collection('stories').add({
      owner: owner,
      inputs: data,
    })
    const createTitle = firebase.httpsCallable(getFunctions(app), 'createTitle')
    createTitle({ id: doc.id })
    return doc.id
  }
)

/**
 * Create a story title and store informations in the story
 */
export const createTitle = functions.https.onCall(async (data, context) => {
  const template = `write a short title for a story about {{animals}} and {{places}}`
  const doc = db.doc(`story/${data.id}`)
  console.log(doc)
  const prompt = mustache.render(template, { ...(await doc.get()).data }) //eslint-disable-next-line
  const response = anthropic.invoke(prompt)
  doc.update({ title: response })
})

Error Message and Stack Trace (if applicable)

└─(20:03:05 on main ✹ ✭)──> firebase deploy --only functions ; tput bell                                              ──(sam.,avril27)β”€β”˜

=== Deploying to 'milleunenuits-b2f19'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> lint
> eslint --ext .js,.ts .

Pages directory cannot be found at /home/alexandre/Development/mySaaS/functions/pages or /home/alexandre/Development/mySaaS/functions/src/pages. If using a custom path, please configure with the `no-html-link-for-pages` rule in your eslint config file.
Running command: npm --prefix "$RESOURCE_DIR" run build

> build
> tsc

node_modules/@langchain/anthropic/node_modules/@langchain/core/dist/language_models/chat_models.d.ts:75:129 - error TS2304: Cannot find name 'this'.

75     _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions, }: ChatModelGenerateCachedParameters<typeof this>): Promise<LLMResult & {
                                                                                                                                   ~~~~

Found 1 error in node_modules/@langchain/anthropic/node_modules/@langchain/core/dist/language_models/chat_models.d.ts:75

Error: functions predeploy error: Command terminated with non-zero exit code 2

Description

I'm trying to edploy my function to firebase with langchain inside and I'm encountering issue i'm not really understand...

System Info

Ubuntu 22.04 - node: 19.9 - 1.22.19 info.txt

dosubot[bot] commented 6 months ago

The error you're encountering seems to be related to TypeScript's handling of types within the LangChain.js library. To address this issue, consider the following steps:

  1. Update Your tsconfig.json: Ensure it includes "skipLibCheck": true to skip type checking of all declaration files (*.d.ts). This can help bypass the error without affecting your code's runtime behavior. Here's an example configuration that might work for you:

    {
     "compilerOptions": {
       "lib": ["ESNext", "DOM"],
       "module": "commonjs",
       "target": "ES6",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "forceConsistentCasingInFileNames": true,
       "strictNullChecks": true,
       "allowSyntheticDefaultImports": true,
       "noImplicitReturns": true,
       "noImplicitAny": true,
       "resolveJsonModule": true
     },
     "include": ["src"],
     "exclude": ["node_modules", "./husky"]
    }
  2. Review Import Syntax: Make sure you're using the correct import syntax for LangChain.js and other libraries. Incorrect imports can sometimes lead to unexpected errors.

  3. Check TypeScript Version: Compatibility issues may arise from the TypeScript version. Ensure you're using a version compatible with both Firebase and LangChain.js.

  4. Consult Documentation: Review the LangChain.js documentation for any specific setup or configuration steps required for Firebase Functions.

If these steps do not resolve your issue, consider reaching out to the LangChain.js support or community forums with a minimal reproducible example for more targeted assistance.

#### Details **Sources** - [build error in typescript and expressJS](https://github.com/langchain-ai/langchainjs/issues/1293) - [langchain/package.json](https://github.com/langchain-ai/langchainjs/blob/main/langchain/package.json) - [package.json](https://github.com/langchain-ai/langchainjs/blob/main/package.json) - [libs/langchain-community/src/stores/tests/firestore.int.test.ts](https://github.com/langchain-ai/langchainjs/blob/main/libs/langchain-community/src/stores/tests/firestore.int.test.ts) - [langchain-core/src/language_models/llms.ts](https://github.com/langchain-ai/langchainjs/blob/main/langchain-core/src/language_models/llms.ts) - [langchain-core/tsconfig.json](https://github.com/langchain-ai/langchainjs/blob/main/langchain-core/tsconfig.json) - [libs/langchain-cohere/tsconfig.json](https://github.com/langchain-ai/langchainjs/blob/main/libs/langchain-cohere/tsconfig.json) - [libs/langchain-mongodb/tsconfig.json](https://github.com/langchain-ai/langchainjs/blob/main/libs/langchain-mongodb/tsconfig.json)
**About Dosu** 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.

To continue the conversation, mention @dosu.

Dranaxel commented 6 months ago

Worked, thanks you :)