Please help I copied the LangChain agent creation code, but it is throwing an error

# pip install -qU “langchain[anthropic]” to call the model

from langchain.agents import create_agent

def get_weather(city: str) → str:

"""Get weather for a given city."""

return f"It's always sunny in {city}!"

agent = create_agent(

model="claude-sonnet-4-5-20250929",

tools=\[get_weather\],

system_prompt="You are a helpful assistant",

)

# Run the agent

agent.invoke(

{"messages": \[{"role": "user", "content": "what is the weather in sf"}\]}

)

I get this issue:

 File "C:\ProgramData\miniconda3\envs\math_tutor_new\Lib\site-packages\anthropic\_base_client.py", line 1035, in request
    request = self._build_request(options, retries_taken=retries_taken)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\ProgramData\miniconda3\envs\math_tutor_new\Lib\site-packages\anthropic\_base_client.py", line 506, in _build_request
    headers = self._build_headers(options, retries_taken=retries_taken)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\ProgramData\miniconda3\envs\math_tutor_new\Lib\site-packages\anthropic\_base_client.py", line 447, in _build_headers
    self._validate_headers(headers_dict, custom_headers)
  File "C:\ProgramData\miniconda3\envs\math_tutor_new\Lib\site-packages\anthropic\_client.py", line 196, in _validate_headers
    raise TypeError(
TypeError: "Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted"
During task with name 'model' and id '7f6855a3-7fad-124d-5820-c47ed29d3e8b'

Hi @zxptian

have you generated your API key on claude platform?

you need either an .env file and python-dotenv installed with load_dotenv() invocation (from dotenv import load_dotenv) or directly in your code os.environ["ANTHROPIC_API_KEY"] = "your_api_key"

  1. with `python-dotenv`` package

.env

ANTHROPIC_API_KEY=your_api_key_here

then in your file:

from dotenv import load_dotenv

load_dotenv()
  1. direct approach in your file
os.environ["ANTHROPIC_API_KEY"] = "your_api_key"