agent1.ts:
import {createAgent} from 'langchain';
import 'dotenv/config'const agent = createAgent({model: 'claude-sonnet-4-5-20250929'}
);const response = await agent.invoke({messages: [{role: 'user', content: 'what is sum of 2+2'}]});
console.log(response);
.env:
ANTHROPIC_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
In the agent1.ts file I didn't use ANTHROPIC_API_KEY, how did it know the API key?
Ah! This is a subtle but important behavior in Node.js/TypeScript with environment variables. Let me break it down carefully.
1. How environment variables work
When you do:
-
The
dotenvpackage automatically loads variables from your.envfile intoprocess.env. -
process.envis a global object in Node.js that any module can access. -
So after
import 'dotenv/config', any code in your project can access environment variables like this:
2. Why your code “knows” the API key
-
createAgent(fromlangchain) internally reads the environment variableANTHROPIC_API_KEYfromprocess.env) when you create the agent. -
You didn’t have to pass it explicitly, because
langchainlooks for it automatically.
So even though your code doesn’t mention the API key, langchain uses:
✅ Key takeaway
ANTHROPIC_API_KEY is implicitly passed through the environment, not as a function argument. This is a common pattern for API keys in Node.js libraries — it avoids hardcoding secrets in code.
ChatGPT said: