Pinecone init: unexpected keyword argument 'api_key'

I’m getting the error: TypeError: Pinecone.init() got an unexpected keyword argument ‘api_key’ with the following code:

from langchain.document_loaders import DirectoryLoader
from langchain.text_splitter import CharacterTextSplitter
import os
from pinecone import Pinecone, ServerlessSpec
import pinecone
from langchain.vectorstores import Pinecone
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.chains import RetrievalQA
from langchain.chat_models import ChatOpenAI
import streamlit as st
from dotenv import load_dotenv

load_dotenv()

PINECONE_API_KEY = os.getenv(‘PINECONE_API_KEY’)
PINECONE_ENV = os.getenv(‘PINECONE_ENV’)
OPENAI_API_KEY = os.getenv(‘OPENAI_API_KEY’)

os.environ[‘OPENAI_API_KEY’] = OPENAI_API_KEY

def doc_preprocessing():
loader = DirectoryLoader(
‘/thgPDFs’,
glob=‘**/*.pdf’, # only the PDFs
show_progress=True
)
docs = loader.load()
text_splitter = CharacterTextSplitter(
chunk_size=1000,
chunk_overlap=0
)
docs_split = text_splitter.split_documents(docs)
return docs_split

@st.cache_resource
def embedding_db():
# we use the openAI embedding model
embeddings = OpenAIEmbeddings()
pc = Pinecone(
api_key=os.environ.get(“PINECONE_API_KEY”)
)

if 'ask-thg' not in pc.list_indexes().names():
    pc.create_index(
        name='ask-thg', 
        dimension=1536, 
        metric='euclidean',
        spec=ServerlessSpec(
            cloud='aws',
            region='us-east-1'
        )
    )
    
docs_split = doc_preprocessing()
doc_db = Pinecone.from_documents(
    docs_split, 
    embeddings, 
    index_name='ask-thg'
)
return doc_db

llm = ChatOpenAI()
doc_db = embedding_db()

def retrieval_answer(query):
qa = RetrievalQA.from_chain_type(
llm=llm,
chain_type=‘stuff’,
retriever=doc_db.as_retriever(),
)
query = query
result = qa.run(query)
return result

def main():
st.title(“Question and Answering App powered by LLM and Pinecone”)

text_input = st.text_input("Ask your query...") 
if st.button("Ask Query"):
    if len(text_input)>0:
        st.info("Your Query: " + text_input)
        answer = retrieval_answer(text_input)
        st.success(answer)

if name == “main”:
main()

The complete log:

Traceback (most recent call last):
File “/Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/venv/lib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.py”, line 600, in _run_script
exec(code, module.dict)
File “/Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/src/app.py”, line 65, in
doc_db = embedding_db()
^^^^^^^^^^^^^^
File “/Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/venv/lib/python3.11/site-packages/streamlit/runtime/caching/cache_utils.py”, line 165, in wrapper
return cached_func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/venv/lib/python3.11/site-packages/streamlit/runtime/caching/cache_utils.py”, line 194, in call
return self._get_or_create_cached_value(args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/venv/lib/python3.11/site-packages/streamlit/runtime/caching/cache_utils.py”, line 221, in _get_or_create_cached_value
return self._handle_cache_miss(cache, value_key, func_args, func_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/venv/lib/python3.11/site-packages/streamlit/runtime/caching/cache_utils.py”, line 277, in _handle_cache_miss
computed_value = self._info.func(*func_args, **func_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/src/app.py”, line 41, in embedding_db
pc = Pinecone(
^^^^^^^^^
File “/Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/venv/lib/python3.11/site-packages/langchain_core/_api/deprecation.py”, line 183, in warn_if_direct_instance
return wrapped(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Pinecone.init() got an unexpected keyword argument ‘api_key’

Any thoughts?

Hi @docharker and welcome to the Pinecone forums! Thank you for your question.

I really appreciate you sharing all your code up front - that makes things a lot easier on us.

One clarifying question, could you please confirm which version of the Pinecone python client you’re currently running?

Thank you for your reply. It’s appreciated:

Name: pinecone-client
Version: 4.0.0
Summary: Pinecone client and SDK
Home-page: https://www.pinecone.io
Author: Pinecone Systems, Inc.
Author-email: support@pinecone.io
License: Apache-2.0
Location: /Users/gharker/Desktop/dev-playground/devNinjaIndy/askDocs/venv/lib/python3.11/site-packages
Requires: certifi, tqdm, typing-extensions, urllib3

Hi @docharker,

Thanks for your prompt reply!

These lines:

from pinecone import Pinecone, ServerlessSpec
import pinecone
from langchain.vectorstores import Pinecone

look suspect to me.

In your code, there are two conflicting uses of the Pinecone identifier, leading to the unexpected keyword argument error.

  1. The Pinecone module is imported from the pinecone package.
  2. Later, you import Pinecone from langchain.vectorstores, which is a different class with its own initialization requirements that doesn’t expect an api_key argument.

This is a classic case of a namespace collision where two different objects are referred to by the same name. To resolve this issue, you can alias at least one of the imports to differentiate between them. Here’s how you can adjust your imports:

from pinecone import Pinecone as PineconeClient
from langchain.vectorstores import Pinecone

Then, use PineconeClient for initializing and interacting with the Pinecone vector database:

pc = PineconeClient(
    api_key=os.environ.get("PINECONE_API_KEY")
)

This change should clear up the confusion for Python about which Pinecone class you’re referring to in each part of your code.

That all said, you may want to reference our official guide on using Langchain here

One of the benefits of using LangChain is that it does management of vectorstores and indexes under the hood for you, so it should pick up your PINECONE_API_KEY from your environment variable. You can also check out LangChain’s own python docs for interacting with Pinecone here to see what I mean.

Hope this helps!

Best,
Zack

Thank-you! Your help is valued and appreciated. I’ll give it a try. I especially appreciate references to the documentation. That will help when I refactor the app.

cheers,
gene

Awesome - so glad it was helpful, Gene!

Good luck and let us know how you get on.

Best,
Zack

It’s working great! Your were extremely helpful. Thx!

1 Like

Woot! So glad to hear that!