LangSmith authentication error during run ingestion process

Hello everyone,

I’m working on a new LangChain application and trying to enable monitoring through LangSmith. However, I keep getting this authentication issue:

WARNING:langsmith.client:Failed to multipart ingest runs: langsmith.utils.LangSmithAuthError: Authentication failed for . HTTPError('401 Client Error: Unauthorized for url: ', '{"detail":"Invalid token"}')

The error shows multiple trace IDs and keeps pointing to the multipart endpoint. I’ve double-checked my API credentials but still can’t get it working.

Here’s my code setup:

from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import CharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores.chroma import Chroma
from langchain.chains import create_retrieval_chain
from langchain.callbacks import tracing_v2_enabled

with tracing_v2_enabled() as tracking_session:
    assert tracking_session
    
    def load_pdf_content(file_path):
        pdf_loader = PyPDFLoader(file_path)
        documents = pdf_loader.load()
        text_splitter = CharacterTextSplitter(
            chunk_size=500,
            chunk_overlap=50
        )
        split_documents = text_splitter.split_documents(documents)
        print(len(split_documents))
        return split_documents

    def build_vector_db(documents): 
        embeddings_model = OpenAIEmbeddings(
            model="text-embedding-ada-002",
            openai_api_key="your_key_here"
        )
        vector_db = Chroma.from_documents(documents, embedding=embeddings_model)
        return vector_db

    def setup_qa_chain(vector_database):
        template = ChatPromptTemplate.from_template("""
        Please answer based on the context provided:
        Context: {context}
        User Question: {input}
        """)
        
        document_chain = create_stuff_documents_chain(
            llm=my_model,
            prompt=template
        )
        
        retriever = vector_database.as_retriever(search_kwargs={"k": 8})
        final_chain = create_retrieval_chain(retriever, document_chain)
        
        return final_chain

    docs = load_pdf_content("sample_document.pdf")
    vector_store = build_vector_db(docs)
    qa_chain = setup_qa_chain(vector_store)
    result = qa_chain.invoke({
        "input": "What is the main topic?"
    })
    
    print(result["answer"])

Has anyone encountered this before? Any suggestions would be really helpful.

Thanks in advance!

Hit this same authentication error last month setting up LangSmith tracing for my doc processing app. The problem wasn’t my API key - it was how I set the environment variables. Use LANGCHAIN_API_KEY, not LANGSMITH_API_KEY. Set LANGCHAIN_TRACING_V2 to ‘true’ as a string. The multipart ingestion endpoint hates malformed tokens, so check for hidden characters or spaces when you copy-paste your key. Also got burned by having the wrong project name in LANGCHAIN_PROJECT. If it points to a project that doesn’t exist, you’ll get auth failures even with valid credentials.

I’ve hit this exact problem too many times. LangSmith’s authentication is a nightmare.

You’ve got API keys, environment variables, and token validation all fighting each other. One breaks, everything stops working.

Ditch the LangSmith headache and use Latenode instead. Build workflows that track your LangChain ops, catch errors, and ping you when stuff breaks.

I built one for our doc processing pipeline. Latenode handles auth automatically and you control what gets monitored. Hook it up to Slack, email, whatever you use.

Best part? Monitor all your LangChain apps from one dashboard. No more API config hell.

Check it out: https://latenode.com

The Problem:

You’re encountering a langsmith.utils.LangSmithAuthError: Authentication failed error with a 401 (Unauthorized) status code when trying to use LangSmith tracing with your LangChain application. This typically indicates an issue with your LangSmith API key or its permissions, but it could also stem from other configuration problems.

:gear: Step-by-Step Guide:

  1. Regenerate your LangSmith API Key and Verify Permissions: The most common cause of this error is an incorrectly configured or expired API key. Go to your LangSmith dashboard and regenerate a brand new API key. Crucially, ensure this key has the necessary permissions for the multipart ingestion endpoint used by LangSmith tracing. Insufficient permissions will result in a 401 error even with a valid key.

  2. Set Environment Variables Correctly: Use the LANGCHAIN_API_KEY environment variable, not LANGSMITH_API_KEY. LangChain’s LangSmith integration utilizes LANGCHAIN_API_KEY. Set the following environment variables before running your script. Double-check for typos and extra spaces, especially in your API key:

export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_ENDPOINT=https://api.smith.langchain.com
export LANGCHAIN_API_KEY=your_new_key_here
export LANGCHAIN_PROJECT=your_project_name

Replace your_new_key_here with your newly generated API key and your_project_name with the actual name of your LangSmith project.

  1. Restart your Python Session: After setting the environment variables, restart your Python kernel or interpreter. The LangSmith client might cache the old, invalid token, preventing it from recognizing the new key.

  2. Verify Project Existence and Access: Confirm that the project name specified in LANGCHAIN_PROJECT actually exists in your LangSmith dashboard and that you have the necessary write permissions for that project. A non-existent or inaccessible project will also lead to authentication failures.

  3. Inspect HTTP Headers (Advanced Debugging): If the problem persists, add debugging logs to inspect the HTTP headers sent during authentication. This will help pinpoint precisely how the token is being sent in the request. Look for any unexpected characters or formatting discrepancies in the Authorization header. You can achieve this using a library such as requests by adding a logging mechanism that prints out the request headers before the request is sent. For example:

import logging
import requests

# ... your code ...

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

#Before making the API call
logger.debug(f"Request Headers: {request_headers}") #Modify according to your code structure
response = requests.post(url, headers=request_headers, data=request_data)


#... rest of your code ...

:mag: Common Pitfalls & What to Check Next:

  • Typos in Environment Variables: Carefully review the spelling and capitalization of all environment variables (LANGCHAIN_TRACING_V2, LANGCHAIN_ENDPOINT, LANGCHAIN_API_KEY, LANGCHAIN_PROJECT). Even a single incorrect character can cause authentication to fail.
  • Incorrect Regional Endpoint: If you’re not in the US, ensure LANGCHAIN_ENDPOINT points to the correct regional LangSmith API endpoint. Incorrect redirection can interfere with token validation.
  • Network Issues: Ensure your network allows outgoing connections to the LangSmith API endpoints on the appropriate ports (check LangSmith’s documentation for port details). Firewalls or proxy servers might be blocking the requests.
  • Multipart Upload Restrictions: Some corporate networks might actively block multipart uploads; if this applies, you’ll need to address network configuration to enable them.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Hit this same problem a few weeks back. Your LangSmith token probably got corrupted when you copied it from the browser. Generate a fresh key and paste it straight into the terminal - don’t bother with the .env file first. Also make sure you’re using LANGSMITH_API_KEY, not LANGCHAIN_API_KEY. That mix-up trips people up all the time and throws 401 errors.

Hit this same auth nightmare migrating our doc processing to LangSmith. The multipart ingestion endpoint is super picky about token formatting. Fixed it by checking the actual HTTP headers during auth - your token’s probably valid but getting messed up in the request chain. Add some debug logging to see what’s actually being sent. Also got burned by regional endpoints - if you’re outside the US, make sure LANGCHAIN_ENDPOINT points to your regional server. Default endpoints sometimes redirect wrong and break token validation. Check if your org blocks multipart upload endpoints too, since they use different ports than regular API calls.

hey @SpinningGalaxy, it sounds like ur token might be expired or not configured right. try getting a new langsmith api key from the dashboard and make sure that LANGCHAIN_API_KEY is set up correctly in your env vars before you run the script.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.