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

Uncaught AnthropicError: running in a browser-like environment #6662

Closed
5 tasks done
QAInsights opened this issue Aug 30, 2024 · 5 comments · Fixed by #6796
Closed
5 tasks done

Uncaught AnthropicError: running in a browser-like environment #6662

QAInsights opened this issue Aug 30, 2024 · 5 comments · Fixed by #6796
Labels
auto:bug Related to a bug, vulnerability, unexpected error with an existing feature

Comments

@QAInsights
Copy link

Checked other resources

  • I added a very descriptive title to this issue.
  • I searched the LangChain.js documentation with the integrated search.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain.js rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).

Example Code

import { ChatAnthropic } from "@langchain/anthropic";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";

console.log("Anthropic API Key is:", import.meta.env.VITE_ANTHROPIC_API_KEY);

const calculatorSchema = z.object({
  operation: z
    .enum(["add", "subtract", "multiply", "divide", "average"])
    .describe("The type of operation to execute."),
  numbers: z.array(z.number()).describe("The numbers to operate on."),
});

const weatherSchema = z
  .object({
    location: z.string().describe("The name of city to get the weather for."),
  })
  .describe(
    "Get the weather of a specific location and return the temperature in Celsius."
  );

const tools = [
  {
    name: "calculator",
    description: "A simple calculator tool.",
    input_schema: zodToJsonSchema(calculatorSchema),
  },
  {
    name: "get_weather",
    description: "Get the weather of a location",
    input_schema: zodToJsonSchema(weatherSchema),
  },
];

const model = new ChatAnthropic({
  apiKey: import.meta.env.VITE_ANTHROPIC_API_KEY,
  model: "claude-3-opus-20240229",
}).bind({
  tools,
});

const prompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "You are a helpful assistant who always uses tools to ensure you provide accurate, up to date information.",
  ],
  ["human", "{input}"],
]);

// Chain your prompt and model together
const chain = prompt.pipe(model);

const response = await chain.invoke({
  input:
    "What is the current weather in new york, and san francisco? Also, what is the average of these numbers: 2273,7192,272,92737?",
});

console.log(JSON.stringify(response, null, 2));
const App: React.FC = () => {
  return (
    <>
      <h1>Anthropic API</h1>
      <div>App Component {JSON.stringify(response, null, 2)}</div>
    </>
  );
};

export default App;

Error Message and Stack Trace (if applicable)

chunk-QMHROIDE.js?v=6aec3b6c:2214 Uncaught AnthropicError: It looks like you're running in a browser-like environment, which is disabled to protect your secret API credentials from attackers. If you have a strong business need for client-side use of this API, please open a GitHub issue with your use-case and security mitigations.
    at new Anthropic (chunk-QMHROIDE.js?v=6aec3b6c:2214:13)
    at ChatAnthropic.completionWithRetry (chunk-QMHROIDE.js?v=6aec3b6c:5709:26)
    at ChatAnthropic._generateNonStreaming (chunk-QMHROIDE.js?v=6aec3b6c:5634:33)
    at ChatAnthropic._generate (chunk-QMHROIDE.js?v=6aec3b6c:5672:19)
    at chunk-QMHROIDE.js?v=6aec3b6c:3167:90
    at Array.map (<anonymous>)
    at ChatAnthropic._generateUncached (chunk-QMHROIDE.js?v=6aec3b6c:3167:61)
    at async ChatAnthropic.invoke (chunk-QMHROIDE.js?v=6aec3b6c:3056:20)
    at async _RunnableSequence.invoke (chunk-MNCD2AJQ.js?v=6aec3b6c:12814:21)
    at async App.tsx:54:18

Description

I am following a simple example as shown above. I have configured the API key in the vite config. When I run the program, the API key is displayed in the console. However, I'm getting an error when trying to make a request to the Anthropic endpoint. OpenAI's requests are functioning well.

Recently, Anthropic implemented CORS feature as mentioned here. So, is this error potentially due to the missing property in the interface? Please clarify.

System Info

macOS mini Apple M2 14.6.1 (23G93)
node v22.7.0
[email protected]

Copy link

dosubot bot commented Aug 30, 2024

Hey there, @QAInsights! 👋 I'm here to help you with bugs, questions, and becoming a contributor. Let's squash those bugs together!

The error you're encountering, Uncaught AnthropicError: running in a browser-like environment, indicates that the ChatAnthropic class is not designed to be used in a browser environment due to security concerns. This is to protect your API credentials from being exposed to potential attackers.

The LangChain.js documentation does not specify any restrictions or guidelines for using the ChatAnthropic class in a browser environment, but it is clear from the error message that this usage is intentionally disabled.

To resolve this issue, you should move the API call to a server-side environment where your API key can be securely stored and accessed. You can then make requests to your server from your React application, which will in turn call the Anthropic API.

Here is a basic example of how you might set this up:

  1. Create a server endpoint (e.g., using Express.js):
// server.js
const express = require('express');
const { ChatAnthropic } = require('@langchain/anthropic');
const app = express();
const port = 3000;

app.use(express.json());

app.post('/api/chat', async (req, res) => {
  const { input } = req.body;

  const model = new ChatAnthropic({
    apiKey: process.env.ANTHROPIC_API_KEY,
    model: 'claude-3-opus-20240229',
  });

  const response = await model.invoke({ input });
  res.json(response);
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
  1. Call the server endpoint from your React application:
// App.tsx
import React, { useState } from 'react';

const App: React.FC = () => {
  const [response, setResponse] = useState(null);

  const fetchChatResponse = async () => {
    const res = await fetch('/api/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        input: 'What is the current weather in New York, and San Francisco? Also, what is the average of these numbers: 2273,7192,272,92737?',
      }),
    });
    const data = await res.json();
    setResponse(data);
  };

  return (
    <>
      <h1>Anthropic API</h1>
      <button onClick={fetchChatResponse}>Fetch Response</button>
      <div>App Component {JSON.stringify(response, null, 2)}</div>
    </>
  );
};

export default App;

This way, your API key remains secure on the server, and your React application can still interact with the Anthropic API indirectly.

To continue talking to Dosu, mention @dosu.

@dosubot dosubot bot added the auto:bug Related to a bug, vulnerability, unexpected error with an existing feature label Aug 30, 2024
@jacoblee93
Copy link
Collaborator

Yes, we should set this field - if you're up for a PR we'd love that, otherwise, will have a look 👍

@rootCircle
Copy link
Contributor

I believe that this will just require a dependency upgrade, as Anthropic SDK itself provides dangerouslyAllowBrowser Option in ClientOptions field, which langchain uses!

I have a small diff ready at https://github.com/rootCircle/langchainjs/tree/deps/%40anthropic-ai/sdk, passed all the tests locally, should I proceed?

@jacoblee93
Copy link
Collaborator

Yes please!

@rootCircle
Copy link
Contributor

Thanks! Did it in #6796!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auto:bug Related to a bug, vulnerability, unexpected error with an existing feature
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants