# I am using Azure openai ,but it shows me an error like this ,please help me to sort out this

**URL:** <https://forum.weaviate.io/t/i-am-using-azure-openai-but-it-shows-me-an-error-like-this-please-help-me-to-sort-out-this/9975>\
**Category:** General\
**Created:** [January 31, 2025, 7:32am UTC](https://forum.weaviate.io/t/i-am-using-azure-openai-but-it-shows-me-an-error-like-this-please-help-me-to-sort-out-this/9975 "2025-01-31T07:32:22Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![DhanushKumar\_R](https://yyz1.discourse-cdn.com/flex027/user_avatar/forum.weaviate.io/dhanushkumar_r/32/3310_2.png) [@DhanushKumar\_R](https://forum.weaviate.io/u/DhanushKumar_R)\
**Post date:** [January 31, 2025, 7:32am UTC](https://forum.weaviate.io/t/i-am-using-azure-openai-but-it-shows-me-an-error-like-this-please-help-me-to-sort-out-this/9975/1 "2025-01-31T07:32:22Z")

</div>

WeaviateQueryError: Query call with protocol GRPC search failed with message \<AioRpcError of RPC that terminated with:  
status = StatusCode.UNKNOWN  
details = "remote client vectorize: connection to: OpenAI API failed with status: 401 request-id: req\_0cb7e7eb20daa21a19b592b59e46cc02 error: Incorrect API key provided: 02j8yI53**4ocs. You can find your API key at [https://platform.openai.com/account/api-keys.](https://platform.openai.com/account/api-keys.)"  
debug\_error\_string = "UNKNOWN:Error received from peer {created\_time:“2025-01-31T07:30:27.4262198+00:00”, grpc\_status:2, grpc\_message:"remote client vectorize: connection to: OpenAI API failed with status: 401 request-id: req\_0cb7e7eb20daa21a19b592b59e46cc02 error: Incorrect API key provided: 02j8yI53**4ocs. You can find your API key at [https://platform.openai.com/account/api-keys.“}”](https://platform.openai.com/account/api-keys.%22%7D%22)

> .

---

<div class="post-metadata">

**Author:** ![Shahin](https://yyz1.discourse-cdn.com/flex027/user_avatar/forum.weaviate.io/shahin/32/7944_2.png) [@Shahin](https://forum.weaviate.io/u/Shahin)\
**Post date:** [January 31, 2025, 8:42am UTC](https://forum.weaviate.io/t/i-am-using-azure-openai-but-it-shows-me-an-error-like-this-please-help-me-to-sort-out-this/9975/2 "2025-01-31T08:42:28Z")

</div>

Hi @DhanushKumar_R,

This issue is related to your **OpenAI API Key**! Please check your OpenAI account to ensure the key is valid and correctly provided in the headers when connecting. Once that’s done, it should work fine.

Regards,  
Mohamed Shahin  
Support Engineer

---

<div class="post-metadata">

**Author:** ![DhanushKumar\_R](https://yyz1.discourse-cdn.com/flex027/user_avatar/forum.weaviate.io/dhanushkumar_r/32/3310_2.png) [@DhanushKumar\_R](https://forum.weaviate.io/u/DhanushKumar_R)\
**Post date:** [January 31, 2025, 9:29am UTC](https://forum.weaviate.io/t/i-am-using-azure-openai-but-it-shows-me-an-error-like-this-please-help-me-to-sort-out-this/9975/3 "2025-01-31T09:29:31Z")

</div>

actually when i use azure openai key for basic chat completion ,it is working but when I work with weaviate ,it returns me an error

Will you please share me a resources for this

---

<div class="post-metadata">

**Author:** ![Shahin](https://yyz1.discourse-cdn.com/flex027/user_avatar/forum.weaviate.io/shahin/32/7944_2.png) [@Shahin](https://forum.weaviate.io/u/Shahin)\
**Post date:** [January 31, 2025, 9:35am UTC](https://forum.weaviate.io/t/i-am-using-azure-openai-but-it-shows-me-an-error-like-this-please-help-me-to-sort-out-this/9975/4 "2025-01-31T09:35:13Z")

</div>

Hi @DhanushKumar_R,

🤔

Would you mind sharing details about your **server setup** , **schema** , and the specific **operation** you’re attempting that triggers this error?

I’d like to try replicating it on my side to dig deeper and let’s find out together.

Regards,  
Mohamed Shahin  
Support Engineer

---

<div class="post-metadata">

**Author:** ![DhanushKumar\_R](https://yyz1.discourse-cdn.com/flex027/user_avatar/forum.weaviate.io/dhanushkumar_r/32/3310_2.png) [@DhanushKumar\_R](https://forum.weaviate.io/u/DhanushKumar_R)\
**Post date:** [January 31, 2025, 12:35pm UTC](https://forum.weaviate.io/t/i-am-using-azure-openai-but-it-shows-me-an-error-like-this-please-help-me-to-sort-out-this/9975/5 "2025-01-31T12:35:28Z")

</div>

thank you so much ,here are my code

import os

import io

import boto3

import weaviate

from pypdf import PdfReader

from typing import List, Dict

from openai import AzureOpenAI

from weaviate.auth import AuthApiKey

from langchain\_text\_splitters import RecursiveCharacterTextSplitter  
def get\_weaviate\_client():  
“”“Connects to Weaviate”“”  
return weaviate.connect\_to\_wcs(  
cluster\_url=WEAVIATE\_CONFIG[“url”],  
auth\_credentials=AuthApiKey(WEAVIATE\_CONFIG[“api\_key”])  
)

def initialize\_weaviate\_schema(client):  
“”“Creates the Weaviate schema if it does not exist.”“”  
if not client.collections.exists(WEAVIATE\_CONFIG[“class\_name”]):  
client.collections.create(  
name=WEAVIATE\_CONFIG[“class\_name”],  
vectorizer\_config=weaviate.classes.config.Configure.Vectorizer.none(),  
properties=[  
weaviate.classes.config.Property(name=“source”, data\_type=weaviate.classes.config.DataType.TEXT),  
weaviate.classes.config.Property(name=“text”, data\_type=weaviate.classes.config.DataType.TEXT),  
weaviate.classes.config.Property(name=“page”, data\_type=weaviate.classes.config.DataType.INT),  
weaviate.classes.config.Property(name=“chunk\_index”, data\_type=weaviate.classes.config.DataType.INT)  
]  
)

def get\_azure\_embeddings(client: AzureOpenAI, text: str) → List[float]:  
“”“Generates embeddings using Azure OpenAI”“”  
response = client.embeddings.create(  
input=text,  
model=AZURE\_CONFIG[“embedding\_deployment”]  
)  
return response.data[0].embedding

def process\_pdf(content: bytes, source\_key: str, weaviate\_client, aoai\_client):  
“”“Processes a PDF file, extracts text, and stores it in Weaviate.”“”  
pdf\_reader = PdfReader(io.BytesIO(content))  
text\_splitter = RecursiveCharacterTextSplitter(chunk\_size=1000, chunk\_overlap=200, length\_function=len)  
collection = weaviate\_client.collections.get(WEAVIATE\_CONFIG[“class\_name”])

```
for page_num, page in enumerate(pdf_reader.pages, start=1):
    text = page.extract_text()
    if text:
        chunks = text_splitter.split_text(text)
        for chunk_idx, chunk in enumerate(chunks):
            try:
                vector = get_azure_embeddings(aoai_client, chunk)
                collection.data.insert(
                    properties={
                        "source": source_key,
                        "text": chunk,
                        "page": page_num,
                        "chunk_index": chunk_idx
                    },
                    vector=vector
                )
            except Exception as e:
                print(f"Error inserting chunk: {str(e)}")

```

s3 = boto3.client(‘s3’, \*\*AWS\_CREDENTIALS)  
w\_client = get\_weaviate\_client()  
aoai\_client = AzureOpenAI(  
api\_key=AZURE\_CONFIG[“api\_key”],  
api\_version=AZURE\_CONFIG[“api\_version”],  
azure\_endpoint=AZURE\_CONFIG[“endpoint”]  
)

initialize\_weaviate\_schema(w\_client)

paginator = s3.get\_paginator(‘list\_objects\_v2’)  
pages = paginator.paginate(Bucket=AWS\_BUCKET\_INFO[“bucket\_name”], Prefix=AWS\_BUCKET\_INFO[“prefix”])  
for page in pages:  
for obj in page.get(‘Contents’, ):  
if obj[‘Key’].lower().endswith(‘.pdf’):  
try:  
response = s3.get\_object(Bucket=AWS\_BUCKET\_INFO[“bucket\_name”], Key=obj[‘Key’])  
content = response[‘Body’].read()  
process\_pdf(content, obj[‘Key’], w\_client, aoai\_client)  
print(f"Processed {obj[‘Key’]} successfully")  
except Exception as e:  
print(f"Error processing {obj[‘Key’]}: {str(e)}")

def retrieve\_and\_generate(query: str, weaviate\_client, aoai\_client):  
“”“Retrieves relevant documents and generates a response using RAG.”“”

```
# Generate embedding for the query using Azure OpenAI
vector = get_azure_embeddings(aoai_client, query)

# Perform vector search in Weaviate
results = (
    weaviate_client.query
    .get(WEAVIATE_CONFIG["class_name"], ["text"])
    .with_near_vector({"vector": vector})
    .with_limit(5)
    .do()
)

# Extract relevant text from retrieved documents
if 'data' in results and 'Get' in results['data'] and WEAVIATE_CONFIG["class_name"] in results['data']['Get']:
    context = "\n".join([obj['text'] for obj in results['data']['Get'][WEAVIATE_CONFIG["class_name"]]])
else:
    context = "No relevant context found."

# Construct a RAG prompt
prompt = f"""
You are an AI assistant. Use the following retrieved context to answer the question.
Context: {context}
Question: {query}
"""

# Generate response using Azure OpenAI
response = aoai_client.completions.create(
    model=AZURE_CONFIG["model"],
    prompt=prompt,
    max_tokens=300
)

return response.choices[0].text.strip()

```

user\_query = “What are the main credit card policies?”

response = retrieve\_and\_generate(user\_query, w\_client, aoai\_client)

print(“\nGenerated Response:\n”, response)

AttributeError: ‘WeaviateClient’ object has no attribute ‘query’

help me to sort this issue

---

<div class="post-metadata">

**Author:** ![Shahin](https://yyz1.discourse-cdn.com/flex027/user_avatar/forum.weaviate.io/shahin/32/7944_2.png) [@Shahin](https://forum.weaviate.io/u/Shahin)\
**Post date:** [January 31, 2025, 3:08pm UTC](https://forum.weaviate.io/t/i-am-using-azure-openai-but-it-shows-me-an-error-like-this-please-help-me-to-sort-out-this/9975/8 "2025-01-31T15:08:46Z")

</div>

Hi @DhanushKumar_R,

The query structure is not correctly formatted. You are using the Weaviate Python client v4. Here’s how you can perform a **near\_vector** query:

```auto
from weaviate.classes.query import MetadataQuery

jeopardy = client.collections.get("JeopardyQuestion")
response = jeopardy.query.near_vector(
    near_vector=query_vector, # Your query vector goes here
    limit=2,
    return_metadata=MetadataQuery(distance=True)
)

for o in response.objects:
    print(o.properties)
    print(o.metadata.distance)

```

Please update your query search following the documentation here:

![](https://canada1.discourse-cdn.com/flex027/uploads/weaviate/original/2X/e/e04c554482fc3043835ddcdb980eef75facb212c.png)[weaviate.io](https://weaviate.io/developers/weaviate/search/similarity#search-with-a-vector)

 ![](https://canada1.discourse-cdn.com/flex027/uploads/weaviate/original/2X/d/dbadd4628ad2eb1a26ba2790e26a390d64743044.jpeg)

### [Vector similarity search | Weaviate](https://weaviate.io/developers/weaviate/search/similarity#search-with-a-vector)

Vector search returns the objects with most similar vectors to that of the query.

Could you try this and let me know how it goes?

Regards,  
Mohamed Shahin  
Support Engineer
