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

feat(anthropic): langchain-anthropic support custom create anthropic client #6615

Merged
merged 5 commits into from
Sep 4, 2024

Conversation

rxliuli
Copy link
Contributor

@rxliuli rxliuli commented Aug 23, 2024

Support for custom Anthropic clients using @langchain/anthropic, which will allow the use of @anthropic-ai/vertex-sdk and @anthropic-ai/bedrock-sdk, and also support custom Anthropic, such as supporting a modified version of the edge runtime.

import { expect, it } from 'vitest'
import { authenticate } from '../authenticate'
import { ChatAnthropic } from '@langchain/anthropic'
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk'
import { GoogleAuth } from 'google-auth-library'
import { AnthropicVertexWeb } from '../AnthropicVertex'

it('Call Anthropic Vertex on nodejs', async () => {
  const client = new AnthropicVertex({
    region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
    projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
    googleAuth: new GoogleAuth({
      credentials: {
        client_email: import.meta.env
          .VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
        private_key: import.meta.env
          .VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
      },
      scopes: ['https://www.googleapis.com/auth/cloud-platform'],
    }),
  })
  const chat = new ChatAnthropic({
    apiKey: 'test',
    model: import.meta.env.VITE_VERTEX_ANTROPIC_MODEL,
    createClient: (() => client) as any,
  })
  const response = await chat.invoke([['human', 'Hello!']])
  console.log(response)
  expect(response).not.undefined
})
it('Call Anthropic Vertex on edge runtime', async () => {
  const token = await authenticate({
    clientEmail: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
    privateKey: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
  })
  const client = new AnthropicVertexWeb({
    region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
    projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
    accessToken: token.access_token,
  })
  const chat = new ChatAnthropic({
    apiKey: 'test',
    model: import.meta.env.VITE_VERTEX_ANTROPIC_MODEL,
    createClient: (() => client) as any,
  })
  const response = await chat.invoke([['human', 'Hello!']])
  console.log(response)
  expect(response).not.undefined
}, 10_000)

Fixes #5196

@dosubot dosubot bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Aug 23, 2024
Copy link

vercel bot commented Aug 23, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
langchainjs-docs ✅ Ready (Inspect) Visit Preview Sep 4, 2024 7:53pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
langchainjs-api-refs ⬜️ Ignored (Inspect) Sep 4, 2024 7:53pm

@dosubot dosubot bot added the auto:enhancement A large net-new component, integration, or chain. Use sparingly. The largest features label Aug 23, 2024
@jacoblee93
Copy link
Collaborator

Ah very nice!

@dosubot dosubot bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Aug 27, 2024
@dosubot dosubot bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Sep 4, 2024
@jacoblee93
Copy link
Collaborator

Thank you for this!

@jacoblee93 jacoblee93 changed the title feat: langchain-anthropic support custom create anthropic client feat(anthropic): langchain-anthropic support custom create anthropic client Sep 4, 2024
@dosubot dosubot bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Sep 4, 2024
@dosubot dosubot bot added the lgtm PRs that are ready to be merged as-is label Sep 4, 2024
@jacoblee93 jacoblee93 merged commit 42f2463 into langchain-ai:main Sep 4, 2024
37 checks passed
@jacoblee93
Copy link
Collaborator

This is live in @langchain/[email protected]!

@rossanodr
Copy link

Support for custom Anthropic clients using @langchain/anthropic, which will allow the use of @anthropic-ai/vertex-sdk and @anthropic-ai/bedrock-sdk, and also support custom Anthropic, such as supporting a modified version of the edge runtime.

import { expect, it } from 'vitest'
import { authenticate } from '../authenticate'
import { ChatAnthropic } from '@langchain/anthropic'
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk'
import { GoogleAuth } from 'google-auth-library'
import { AnthropicVertexWeb } from '../AnthropicVertex'

it('Call Anthropic Vertex on nodejs', async () => {
  const client = new AnthropicVertex({
    region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
    projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
    googleAuth: new GoogleAuth({
      credentials: {
        client_email: import.meta.env
          .VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
        private_key: import.meta.env
          .VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
      },
      scopes: ['https://www.googleapis.com/auth/cloud-platform'],
    }),
  })
  const chat = new ChatAnthropic({
    apiKey: 'test',
    model: import.meta.env.VITE_VERTEX_ANTROPIC_MODEL,
    createClient: (() => client) as any,
  })
  const response = await chat.invoke([['human', 'Hello!']])
  console.log(response)
  expect(response).not.undefined
})
it('Call Anthropic Vertex on edge runtime', async () => {
  const token = await authenticate({
    clientEmail: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
    privateKey: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
  })
  const client = new AnthropicVertexWeb({
    region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
    projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
    accessToken: token.access_token,
  })
  const chat = new ChatAnthropic({
    apiKey: 'test',
    model: import.meta.env.VITE_VERTEX_ANTROPIC_MODEL,
    createClient: (() => client) as any,
  })
  const response = await chat.invoke([['human', 'Hello!']])
  console.log(response)
  expect(response).not.undefined
}, 10_000)

Fixes #5196

Hey, I'm a little nooby.
How should I use it to make it owrk with vertex ai?
Can you help me? thanks

@jacoblee93
Copy link
Collaborator

@rossanodr
Copy link

Hey @rossanodr, do these docs help?

https://js.langchain.com/v0.2/docs/integrations/chat/anthropic/#custom-clients

Thanks, but I can't seem to find a way to make it work with Vertex. I'm still getting the error:
Error: Unable to verify model params: {"lc":1,"type":"constructor","id":["langchain","chat_models","chat_integration","ChatVertexAI"],
even though I've configured access in the Vertex dashboard.

@rxliuli
Copy link
Contributor Author

rxliuli commented Sep 7, 2024

Hey @rossanodr, do these docs help?
https://js.langchain.com/v0.2/docs/integrations/chat/anthropic/#custom-clients

Thanks, but I can't seem to find a way to make it work with Vertex. I'm still getting the error: Error: Unable to verify model params: {"lc":1,"type":"constructor","id":["langchain","chat_models","chat_integration","ChatVertexAI"], even though I've configured access in the Vertex dashboard.

The model name should be similar to claude-3-5-sonnet@20240620 rather than claude-3-5-sonnet-20240620, refer to https://docs.anthropic.com/en/docs/about-claude/models#model-names

image

Additionally, you should first create an AnthropicVertex client and test it without using langchain to determine if the error is caused by langchain. For your reference, I also encountered many authentication-related errors when I initially used AnthropicVertex.

const client = new AnthropicVertex({
  region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
  projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
  googleAuth: new GoogleAuth({
    credentials: {
      client_email: import.meta.env
        .VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
      private_key: import.meta.env
        .VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
    },
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
})
const chat = new ChatAnthropic({
  apiKey: 'test',
  model: 'claude-3-5-sonnet@20240620',
  createClient: (() => client) as any,
})
const response = await chat.invoke([['human', 'Hello!']])
console.log(response)

Strange, I just noticed that I've been passing a fake apiKey to ChatAnthropic all along. I will submit another PR to handle ignoring the check for API key existence when createClient exists.

@rossanodr
Copy link

Hey @rossanodr, do these docs help?
https://js.langchain.com/v0.2/docs/integrations/chat/anthropic/#custom-clients

Thanks, but I can't seem to find a way to make it work with Vertex. I'm still getting the error: Error: Unable to verify model params: {"lc":1,"type":"constructor","id":["langchain","chat_models","chat_integration","ChatVertexAI"], even though I've configured access in the Vertex dashboard.

The model name should be similar to claude-3-5-sonnet@20240620 rather than claude-3-5-sonnet-20240620, refer to https://docs.anthropic.com/en/docs/about-claude/models#model-names

image Additionally, you should first create an AnthropicVertex client and test it without using langchain to determine if the error is caused by langchain. For your reference, I also encountered many authentication-related errors when I initially used AnthropicVertex.
const client = new AnthropicVertex({
  region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
  projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
  googleAuth: new GoogleAuth({
    credentials: {
      client_email: import.meta.env
        .VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
      private_key: import.meta.env
        .VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
    },
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
})
const chat = new ChatAnthropic({
  apiKey: 'test',
  model: 'claude-3-5-sonnet@20240620',
  createClient: (() => client) as any,
})
const response = await chat.invoke([['human', 'Hello!']])
console.log(response)

Strange, I just noticed that I've been passing a fake apiKey to ChatAnthropic all along. I will submit another PR to handle ignoring the check for API key existence when createClient exists.

I am having authentication issues [llm/error] [1:llm
] [96.96s] LLM run errored with error: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.\n\nError: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.\n
Probably because it is a Next.js application.
I usually use "@langchain/google-vertexai-web", but here there isn't a similar option available.

@rxliuli
Copy link
Contributor Author

rxliuli commented Sep 9, 2024

I am having authentication issues [llm/error] [1:llm ] [96.96s] LLM run errored with error: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.\n\nError: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.\n Probably because it is a Next.js application. I usually use "@langchain/google-vertexai-web", but here there isn't a similar option available.

Similarly, for testing, I suggest using only NodeJS instead of Edge runtime, as they have some annoying inconsistencies. You can try to complete basic examples in NodeJS first, then consider Edge Runtime, otherwise you may run into issues where you don't know where the error is coming from (in fact, Google cloud services' authentication method itself is very complex, and compared to the original LLM provider that only needs an API_KEY, it's downright nasty). Additionally, I've also submitted a PR for @anthropic-ai/vertex-sdk to support edge runtime (in my scenario, it's cloudflare workers), but it hasn't been merged yet. Reference: anthropics/anthropic-sdk-typescript#509

@rossanodr
Copy link

I am having authentication issues [llm/error] [1:llm ] [96.96s] LLM run errored with error: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.\n\nError: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.\n Probably because it is a Next.js application. I usually use "@langchain/google-vertexai-web", but here there isn't a similar option available.

Similarly, for testing, I suggest using only NodeJS instead of Edge runtime, as they have some annoying inconsistencies. You can try to complete basic examples in NodeJS first, then consider Edge Runtime, otherwise you may run into issues where you don't know where the error is coming from (in fact, Google cloud services' authentication method itself is very complex, and compared to the original LLM provider that only needs an API_KEY, it's downright nasty). Additionally, I've also submitted a PR for @anthropic-ai/vertex-sdk to support edge runtime (in my scenario, it's cloudflare workers), but it hasn't been merged yet. Reference: anthropics/anthropic-sdk-typescript#509

Unfortunately, I can't opt for the NodeJS environment at the moment. I hope it will be possible to use it in the edge environment soon.
Thank you for the assistance.

CarterMorris pushed a commit to CarterMorris/langchainjs that referenced this pull request Nov 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auto:enhancement A large net-new component, integration, or chain. Use sparingly. The largest features lgtm PRs that are ready to be merged as-is size:M This PR changes 30-99 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Unable to use non-Gemini models through ChatVertexAI
3 participants