请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

SemanticSimilarityExampleSelector 及 MaxMarginalRelevanceExampleSelector 使用报错

example_selector = SemanticSimilarityExampleSelector.from_examples(
# 传入示例组.
# Pass in the example group.
examples,
# 使用 openAI 嵌入来做相似性搜索
# Use openAI embeddings for similarity search
OpenAIEmbeddings(openai_api_key=api_key,openai_api_base=api_base),
# 使用 Chroma 向量数据库来实现对相似结果的过程存储
# Use the Chroma vector database to implement the process storage of similar results
Chroma,
# 结果条数
# Number of results
k=2,
)

报错:

TypeError Traceback (most recent call last)
File ~/anaconda3/envs/alx/lib/python3.10/site-packages/langchain_core/example_selectors/semantic_similarity.py:171, in SemanticSimilarityExampleSelector.from_examples(cls, examples, embeddings, vectorstore_cls, k, input_keys, example_keys, vectorstore_kwargs, **vectorstore_cls_kwargs)
151 “”"Create k-shot example selector using example list and embeddings.
152
153 Reshuffles examples dynamically based on query similarity.
(…)
168 The ExampleSelector instantiated, backed by a vector store.
169 “”"
170 string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
–> 171 vectorstore = vectorstore_cls.from_texts(
172 string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
173 )
174 return cls(
175 vectorstore=vectorstore,
176 k=k,
(…)
179 vectorstore_kwargs=vectorstore_kwargs,
180 )

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/langchain_chroma/vectorstores.py:1187, in Chroma.from_texts(cls, texts, embedding, metadatas, ids, collection_name, persist_directory, client_settings, client, collection_metadata, **kwargs)
1179 from chromadb.utils.batch_utils import create_batches
1181 for batch in create_batches(
1182 api=chroma_collection._client,
1183 ids=ids,
1184 metadatas=metadatas, # type: ignore
1185 documents=texts,
1186 ):
-> 1187 chroma_collection.add_texts(
1188 texts=batch[3] if batch[3] else [],
1189 metadatas=batch[2] if batch[2] else None, # type: ignore
1190 ids=batch[0],
1191 )
1192 else:
1193 chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids)

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/langchain_chroma/vectorstores.py:527, in Chroma.add_texts(self, texts, metadatas, ids, **kwargs)
525 texts = list(texts)
526 if self._embedding_function is not None:
–> 527 embeddings = self._embedding_function.embed_documents(texts)
528 if metadatas:
529 # fill metadatas with empty dicts if somebody
530 # did not specify metadata for all texts
531 length_diff = len(texts) - len(metadatas)

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/langchain_openai/embeddings/base.py:590, in OpenAIEmbeddings.embed_documents(self, texts, chunk_size, **kwargs)
587 # NOTE: to keep things simple, we assume the list may contain texts longer
588 # than the maximum context and use length-safe embedding function.
589 engine = cast(str, self.deployment)
–> 590 return self._get_len_safe_embeddings(
591 texts, engine=engine, chunk_size=chunk_size, **kwargs
592 )

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/langchain_openai/embeddings/base.py:478, in OpenAIEmbeddings._get_len_safe_embeddings(self, texts, engine, chunk_size, **kwargs)
476 batched_embeddings: list[list[float]] = []
477 for i in _iter:
–> 478 response = self.client.create(
479 input=tokens[i : i + _chunk_size], **client_kwargs
480 )
481 if not isinstance(response, dict):
482 response = response.model_dump()

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/openai/resources/embeddings.py:129, in Embeddings.create(self, input, model, dimensions, encoding_format, user, extra_headers, extra_query, extra_body, timeout)
123 embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call]
124 base64.b64decode(data), dtype="float32"
125 ).tolist()
127 return obj
–> 129 return self._post(
130 “/embeddings”,
131 body=maybe_transform(params, embedding_create_params.EmbeddingCreateParams),
132 options=make_request_options(
133 extra_headers=extra_headers,
134 extra_query=extra_query,
135 extra_body=extra_body,
136 timeout=timeout,
137 post_parser=parser,
138 ),
139 cast_to=CreateEmbeddingResponse,
140 )

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/openai/_base_client.py:1239, in SyncAPIClient.post(self, path, cast_to, body, options, files, stream, stream_cls)
1225 def post(
1226 self,
1227 path: str,
(…)
1234 stream_cls: type[_StreamT] | None = None,
1235 ) -> ResponseT | _StreamT:
1236 opts = FinalRequestOptions.construct(
1237 method=“post”, url=path, json_data=body, files=to_httpx_files(files), **options
1238 )
-> 1239 return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/openai/_base_client.py:1039, in SyncAPIClient.request(self, cast_to, options, stream, stream_cls)
1036 break
1038 assert response is not None, “could not resolve response (should never happen)”
-> 1039 return self._process_response(
1040 cast_to=cast_to,
1041 options=options,
1042 response=response,
1043 stream=stream,
1044 stream_cls=stream_cls,
1045 retries_taken=retries_taken,
1046 )

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/openai/_base_client.py:1121, in SyncAPIClient._process_response(self, cast_to, options, response, stream, stream_cls, retries_taken)
1118 if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
1119 return cast(ResponseT, api_response)
-> 1121 return api_response.parse()

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/openai/_response.py:325, in APIResponse.parse(self, to)
323 parsed = self._parse(to=to)
324 if is_given(self._options.post_parser):
–> 325 parsed = self._options.post_parser(parsed)
327 if isinstance(parsed, BaseModel):
328 add_request_id(parsed, self.request_id)

File ~/anaconda3/envs/alx/lib/python3.10/site-packages/openai/resources/embeddings.py:115, in Embeddings.create..parser(obj)
111 if is_given(encoding_format):
112 # don’t modify the response object if a user explicitly asked for a format
113 return obj
–> 115 for embedding in obj.data:
116 data = cast(object, embedding.embedding)
117 if not isinstance(data, str):

TypeError: ‘NoneType’ object is not iterable

如何解决呢?其中 测试过 OpenAIEmbeddings(openai_api_key=api_key,openai_api_base=api_base)  没有问题,但还是报上述错误。望解答

正在回答 回答被采纳积分+3

1回答

tomiezhang 2025-06-03 11:57:08

使用的是哪个嵌入模型?

# 确保明确指定模型名称
embeddings = OpenAIEmbeddings(
    openai_api_key=api_key,
    openai_api_base=api_base,
    model="text-embedding-ada-002"  # 明确指定嵌入模型
)


0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号