issue_owner_repo
listlengths
2
2
issue_body
stringlengths
0
261k
issue_title
stringlengths
1
925
issue_comments_url
stringlengths
56
81
issue_comments_count
int64
0
2.5k
issue_created_at
stringlengths
20
20
issue_updated_at
stringlengths
20
20
issue_html_url
stringlengths
37
62
issue_github_id
int64
387k
2.46B
issue_number
int64
1
127k
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_community.document_loaders.recursive_url_loader import RecursiveUrlLoader from bs4 import BeautifulSoup as Soup url = "https://www.example.com/" loader = RecursiveUrlLoader( url=url, max_depth=2, extractor=lambda x: Soup(x, "html.parser").text ) docs = loader.load() ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description I'm trying to use "Recursive URL" Document loaders from "langchain_community.document_loaders.recursive_url_loader" to process load all URLs under a root directory but css or js links are also processed ### System Info System Information ------------------ > OS: Linux > OS Version: #1 SMP Tue Dec 19 13:14:11 UTC 2023 > Python Version: 3.10.13 | packaged by conda-forge | (main, Dec 23 2023, 15:36:39) [GCC 12.3.0] Package Information ------------------- > langchain_core: 0.1.48 > langchain: 0.1.17 > langchain_community: 0.0.36 > langsmith: 0.1.52 > langchain_cohere: 0.1.4 > langchain_text_splitters: 0.0.1
"Recursive URL" Document loader load useless documents
https://api.github.com/repos/langchain-ai/langchain/issues/21204/comments
2
2024-05-02T15:43:26Z
2024-08-10T16:08:20Z
https://github.com/langchain-ai/langchain/issues/21204
2,275,857,410
21,204
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code - ### Error Message and Stack Trace (if applicable) httpx.HTTPStatusError: Error response 400 while fetching https://api.mistral.ai/v1/chat/completions: {"object":"error","message":"Assistant message must have either content or tool_calls, but not both.","type":"invalid_request_error","param":null,"code":null} ### Description I'm trying to send a chat completion request to MistralAI API. However, when I send multiple messages with a chat history persitence, the api returns an error saying that it is impossible to include tool_calls AND content in the request. It is probably related to `_convert_message_to_mistral_chat_message` in the chat_models.py in langchain_mistrail package. We shouldn't the `tool_calls` variable if it is empty or we shouldn't return the `content` variable if we're using tools. I am going to fix this with a PR asap ### System Info -
ChatMistralAI with chat history : Assistant message must have either content or tool_calls error
https://api.github.com/repos/langchain-ai/langchain/issues/21196/comments
8
2024-05-02T14:39:44Z
2024-07-16T16:51:15Z
https://github.com/langchain-ai/langchain/issues/21196
2,275,715,007
21,196
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python class FastEmbedEmbeddings(BaseModel, Embeddings): """Qdrant FastEmbedding models. FastEmbed is a lightweight, fast, Python library built for embedding generation. See more documentation at: * https://github.com/qdrant/fastembed/ * https://qdrant.github.io/fastembed/ To use this class, you must install the `fastembed` Python package. `pip install fastembed` Example: from langchain_community.embeddings import FastEmbedEmbeddings fastembed = FastEmbedEmbeddings() """ model_name: str = "BAAI/bge-small-en-v1.5" """Name of the FastEmbedding model to use Defaults to "BAAI/bge-small-en-v1.5" Find the list of supported models at https://qdrant.github.io/fastembed/examples/Supported_Models/ """ max_length: int = 512 """The maximum number of tokens. Defaults to 512. Unknown behavior for values > 512. """ cache_dir: Optional[str] """The path to the cache directory. Defaults to `local_cache` in the parent directory """ threads: Optional[int] """The number of threads single onnxruntime session can use. Defaults to None """ doc_embed_type: Literal["default", "passage"] = "default" """Type of embedding to use for documents The available options are: "default" and "passage" """ _model: Any # : :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that FastEmbed has been installed.""" model_name = values.get("model_name") max_length = values.get("max_length") cache_dir = values.get("cache_dir") threads = values.get("threads") # ----------- the below is the problem ----------- # try: # >= v0.2.0 from fastembed import TextEmbedding values["_model"] = TextEmbedding( model_name=model_name, max_length=max_length, cache_dir=cache_dir, threads=threads, ) except ImportError as ie: try: # < v0.2.0 from fastembed.embedding import FlagEmbedding values["_model"] = FlagEmbedding( model_name=model_name, max_length=max_length, cache_dir=cache_dir, threads=threads, ) except ImportError: raise ImportError( "Could not import 'fastembed' Python package. " "Please install it with `pip install fastembed`." ) from ie return values ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description ### Problem FastEmbedEmbeddings does not work without internet, even if the model is already present locally. This is despite providing `cache_dir`. This is because under the hood it calls huggingface api, which then makes a network call to check the repo before checking if the model exists locally. This behavior can be fixed if you specify `local_files_only` to True. However, this was not previously allowed in fastembed. This issue was raised in the FastEmbed library here: https://github.com/qdrant/fastembed/issues/218 and was fixed with a pull request here https://github.com/qdrant/fastembed/pull/223 The langchain abstraction also needs to be updated to reflect this change. ### Solution I dont see why we limit the params that can be passed on to fastembed. There are min params yes, but the others should be passed along as well. `TextEmbedding` allows kwargs. The abstraction should too. ### System Info System Information ------------------ > OS: Linux > OS Version: #1 SMP Thu Oct 5 21:02:42 UTC 2023 > Python Version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] Package Information ------------------- > langchain_core: 0.1.48 > langchain: 0.1.17 > langchain_community: 0.0.36 > langsmith: 0.1.52 > langchain_experimental: 0.0.57 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
FastEmbedEmbeddings Abstraction has limited params, unable to set important params which then causes a timeout
https://api.github.com/repos/langchain-ai/langchain/issues/21193/comments
0
2024-05-02T14:23:02Z
2024-08-08T16:08:33Z
https://github.com/langchain-ai/langchain/issues/21193
2,275,675,101
21,193
[ "langchain-ai", "langchain" ]
### Privileged issue - [X] I am a LangChain maintainer, or was asked directly by a LangChain maintainer to create an issue here. ### Issue Content - [ ] Implement chunking to given texts. - [ ] Test DeepInfraEmbeddings with a large batch of texts.
Unprocessable Entity error while requesting with batches larger than 1024 using DeepInfraEmbeddings
https://api.github.com/repos/langchain-ai/langchain/issues/21188/comments
0
2024-05-02T12:45:07Z
2024-08-08T16:08:28Z
https://github.com/langchain-ai/langchain/issues/21188
2,275,452,326
21,188
[ "langchain-ai", "langchain" ]
Hi, I got this error when trying to use mmr: `ValueError: `max_marginal_relevance_search` is not supported for index with Databricks-managed embeddings.` _Originally posted by @reslleygabriel in https://github.com/langchain-ai/langchain/issues/16829#issuecomment-2083459918_
`max_marginal_relevance_search` is not supported for index with Databricks-managed embeddings.`
https://api.github.com/repos/langchain-ai/langchain/issues/21175/comments
0
2024-05-02T02:09:29Z
2024-08-08T16:08:23Z
https://github.com/langchain-ai/langchain/issues/21175
2,274,462,076
21,175
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` import weaviate from langchain_community.retrievers import ( WeaviateHybridSearchRetriever, ) from langchain_core.documents import Document from config import OPENAI_API_KEY, WEAVIATE_HOST, WEAVIATE_PORT headers = { "X-Openai-Api-Key": OPENAI_API_KEY, } client = weaviate.connect_to_local(headers=headers) retriever = WeaviateHybridSearchRetriever( client=client, index_name="LangChain", text_key="text", attributes=[], create_schema_if_missing=True, ) docs = [ Document( metadata={ "title": "Embracing The Future: AI Unveiled", "author": "Dr. Rebecca Simmons", }, page_content="A comprehensive analysis of the evolution of artificial intelligence, from its inception to its future prospects. Dr. Simmons covers ethical considerations, potentials, and threats posed by AI.", ) ] retriever.add_documents(docs) answer = retriever.invoke("the ethical implications of AI") print(answer) ``` ### Error Message and Stack Trace (if applicable) ``` Traceback (most recent call last): File "main.py", line 17, in <module> retriever = WeaviateHybridSearchRetriever( File "venv\lib\site-packages\langchain_core\load\serializable.py", line 120, in __init__ super().__init__(**kwargs) File "venv\lib\site-packages\pydantic\v1\main.py", line 341, in __init__ raise validation_error pydantic.v1.error_wrappers.ValidationError: 1 validation error for WeaviateHybridSearchRetriever __root__ client should be an instance of weaviate.Client, got <class 'weaviate.client.WeaviateClient'> (type=value_error) sys:1: ResourceWarning: unclosed <socket.socket fd=880, family=AddressFamily.AF_INET6, type=SocketKind.SOCK_STREAM, proto=0, laddr=('::1', 64509, 0, 0), raddr=('::1', 8080, 0, 0)> ``` ### Description windows 11, I'm trying to use `WeaviateHybridSearchRetriever` with Weaviate client v4 since v3 is deprecated. ### System Info ``` aiohttp==3.9.5 aiosignal==1.3.1 annotated-types==0.6.0 anyio==4.3.0 async-timeout==4.0.3 attrs==23.2.0 Authlib==1.3.0 certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 cryptography==42.0.5 dataclasses-json==0.6.5 exceptiongroup==1.2.1 frozenlist==1.4.1 greenlet==3.0.3 grpcio==1.63.0 grpcio-health-checking==1.63.0 grpcio-tools==1.63.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.0 idna==3.7 jsonpatch==1.33 jsonpointer==2.4 langchain==0.1.17 langchain-community==0.0.36 langchain-core==0.1.48 langchain-text-splitters==0.0.1 langsmith==0.1.52 marshmallow==3.21.1 multidict==6.0.5 mypy-extensions==1.0.0 numpy==1.26.4 orjson==3.10.2 packaging==23.2 protobuf==5.26.1 pycparser==2.22 pydantic==2.7.1 pydantic_core==2.18.2 PyYAML==6.0.1 requests==2.31.0 sniffio==1.3.1 SQLAlchemy==2.0.29 tenacity==8.2.3 typing-inspect==0.9.0 typing_extensions==4.11.0 urllib3==2.2.1 validators==0.28.1 weaviate-client==4.5.7 yarl==1.9.4 ````
`WeaviateHybridSearchRetriever` isn't working with weaviate cliient v4
https://api.github.com/repos/langchain-ai/langchain/issues/21147/comments
5
2024-05-01T16:39:23Z
2024-07-09T18:34:27Z
https://github.com/langchain-ai/langchain/issues/21147
2,273,803,408
21,147
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from operator import itemgetter from langchain_community.vectorstores import FAISS from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI, OpenAIEmbeddings vectorstore = FAISS.from_texts( ["harrison worked at kensho"], embedding=OpenAIEmbeddings() ) retriever = vectorstore.as_retriever() template = """Answer the question based only on the following context: {context} Question: {question} Answer in the following language: {language} """ prompt = ChatPromptTemplate.from_template(template) chain = ( { "context": itemgetter("question") | retriever, "question": itemgetter("question"), "language": itemgetter("language"), } | prompt ) chain.invoke({"question": "where did harrison work", "language": "italian"}) ### Error Message and Stack Trace (if applicable) ChatPromptValue(messages=[HumanMessage(content="Answer the question based only on the following context:\n[Document(page_content='harrison worked at kensho')]\n\nQuestion: where did harrison work\n\nAnswer in the following language: italian\n")]) ### Description * When I build a prompt the content property of HumanMessage includes the serialized form of the Document * Instead I expect only the page_content to be included as context information, such as ChatPromptValue(messages=[HumanMessage(content="Answer the question based only on the following context:\n"""\nharrison worked at kensho\n"""\n\nQuestion: where did harrison work\n\nAnswer in the following language: italian\n")]) * I wonder if this behaviour is on purpose (can the LLM read the serialized object well, is it of any help for the answer) or is it a bug? ### System Info pip install --upgrade --quiet langchain langchain-openai
ChatPromptTemplate.from_template returns serialized object from vectorstore retriever
https://api.github.com/repos/langchain-ai/langchain/issues/21140/comments
0
2024-05-01T08:47:07Z
2024-08-07T16:07:44Z
https://github.com/langchain-ai/langchain/issues/21140
2,273,165,344
21,140
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python embeddings = AzureOpenAIEmbeddings( model="text-embedding-3-small", azure_deployment="text-embedding-3-small", openai_api_version="2024-02-01", ) vectorstore = Chroma( collection_name="cv_collection", embedding_function=embeddings, ) st.session_state.record_manager = SQLRecordManager( db_url="sqlite:///:memory:", namespace="chroma/cv_collection", ) def add_document_to_vectorStore(vectorStore, document, record_manager): # Index the new document in the vector store with incremental cleanup index( [document], # Pass a list of documents record_manager, vectorStore, cleanup="incremental", source_id_key="source", ) ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description Hi, im trying to embed a document in a Chroma vector store, my issue is that when i call the Index function it does index it but it adds it as documents and not their corresponding embeddings, also when i call the function i can see the Embeddings request to openAI going out, but then the dump returns and "embeddings": null followed by the whole document like this: ```json { "ids": [ "a68dbda2-06bf-50df-b460-f2d1cd8dc8c0" ], "embeddings": null, "metadatas": [ { "departamento": "Artigas", "idioma": "Inglés, Portugues", "nivel_educativo": "TERCERIA_SUPERIOR", "source": "Laura Texeira._.pdf" } ], "documents": [ "Text" ], "uris": null, "data": null } ``` I have tried from creating a small proyect with only this to already reading all the chromadb and langchain indexing documentation, to changing from embeddings to the client for AzureOpenAI and the embeddings are being computed perfectly everytime, i also can see the request coming back as 200 OK, so i dont really know where else to look outside de Index function and thats why i think is a bug. ### System Info Im in a docker container with the latest versions of this packages: - streamlit - pdfplumber - openai - pydantic - langchain - langchain-community - langchain-core - langchain-openai - chromadb - pysqlite3-binary - lark and a base image of python:3.9-slim-buster
Empty Embeddings propertie when returning from Indexing a document
https://api.github.com/repos/langchain-ai/langchain/issues/21119/comments
2
2024-04-30T20:24:12Z
2024-05-02T12:28:46Z
https://github.com/langchain-ai/langchain/issues/21119
2,272,391,380
21,119
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from langchain.storage import LocalFileStore ### Error Message and Stack Trace (if applicable) from langchain.storage import LocalFileStore /usr/local/lib/python3.11/site-packages/langchain/storage/__init__.py:15: in <module> from langchain.storage.file_system import LocalFileStore /usr/local/lib/python3.11/site-packages/langchain/storage/file_system.py:8: in <module> from langchain.storage.exceptions import InvalidKeyException /usr/local/lib/python3.11/site-packages/langchain/storage/exceptions.py:1: in <module> from langchain_community.storage.exceptions import InvalidKeyException /usr/local/lib/python3.11/site-packages/langchain_community/storage/exceptions.py:1: in <module> from langchain_core.stores import InvalidKeyException E ImportError: cannot import name 'InvalidKeyException' from 'langchain_core.stores' ### Description I had 0.1.16 version of langchain installed and this morning pulled up fresh docker to re-install my environment, found out a back compatibility issue. Langchain depends on langchain_community, which a few days ago was using 0.0.34, now that it updated to 0.0.35. langchain's import of LocalFileStore would fail. ### System Info OS: Linux Python: 3.11 Langchain: 0.1.16
InvalidKeyException found installing library for deployment.
https://api.github.com/repos/langchain-ai/langchain/issues/21111/comments
7
2024-04-30T19:07:22Z
2024-05-01T17:08:46Z
https://github.com/langchain-ai/langchain/issues/21111
2,272,262,675
21,111
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_community.chat_models import BedrockChat from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain.schema import SystemMessage bedrock_client = boto3.client(service_name="bedrock-runtime") bedrock_model = BedrockChat( client=bedrock_client, model_id="anthropic.claude-3-sonnet-20240229-v1:0", model_kwargs={"temperature": 0}, guardrails={"id": "<ModelID>", "version": "1", "trace": True} ) prompt = ChatPromptTemplate.from_messages(messages) human_message_template = HumanMessagePromptTemplate.from_template( "Input: ```{activity_note_input}```\nOutput: " ) messages = [ SystemMessage(content="<Prompt>"), human_message_template, ] activity_note_input = "FOOBAR" chain = prompt | bedrock_model | StrOutputParser() response = chain.invoke({"activity_note_input": activity_note_input}) ``` ### Error Message and Stack Trace (if applicable) 2024-04-30 14:06:46,160 ERROR:request:Traceback (most recent call last): File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_community/llms/bedrock.py", line 546, in _prepare_input_and_invoke response = self.client.invoke_model(**request_options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/botocore/client.py", line 565, in _api_call return self._make_api_call(operation_name, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/botocore/client.py", line 974, in _make_api_call request_dict = self._convert_to_request_dict( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/botocore/client.py", line 1048, in _convert_to_request_dict request_dict = self._serializer.serialize_to_request( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/botocore/validate.py", line 381, in serialize_to_request raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed: Unknown parameter in input: "guardrail", must be one of: body, contentType, accept, modelId, trace, guardrailIdentifier, guardrailVersion During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/flask/app.py", line 1484, in full_dispatch_request rv = self.dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/flask/app.py", line 1469, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/flask/views.py", line 109, in view return current_app.ensure_sync(self.dispatch_request)(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/flask/views.py", line 190, in dispatch_request return current_app.ensure_sync(meth)(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/lasagna/clients/artichoke.py", line 28, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/lasagna/clients/launchdarkly.py", line 29, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/lasagna/api/v3/activity_summary.py", line 79, in post resp = retry_with_backoff( ^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/lasagna/utilities/retry.py", line 25, in retry_with_backoff raise last_exception File "/Users/girishnanda/Code/python-mono/lasagna/lasagna/utilities/retry.py", line 18, in retry_with_backoff return func(*args) ^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/lasagna/api/v3/activity_summary.py", line 139, in fetch_activity_summary response = chain.invoke({"activity_note_input": activity_note_input}) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2499, in invoke input = step.invoke( ^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 158, in invoke self.generate_prompt( File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 560, in generate_prompt return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 421, in generate raise e File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 411, in generate self._generate_with_cache( File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_core/language_models/chat_models.py", line 632, in _generate_with_cache result = self._generate( ^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_community/chat_models/bedrock.py", line 294, in _generate completion, usage_info = self._prepare_input_and_invoke( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/girishnanda/Code/python-mono/lasagna/venv/lib/python3.12/site-packages/langchain_community/llms/bedrock.py", line 553, in _prepare_input_and_invoke raise ValueError(f"Error raised by bedrock service: {e}") ValueError: Error raised by bedrock service: Parameter validation failed: Unknown parameter in input: "guardrail", must be one of: body, contentType, accept, modelId, trace, guardrailIdentifier, guardrailVersion ### Description I am trying to use AWS Bedrock Guardrails with the BedrockChat model. If i set the guardrails parameter when instantiating the BedrockChat model I get a ValueError when the chain is invoked. ### System Info langchain==0.1.17rc1 langchain-community==0.0.34 langchain-core==0.1.47 langchain-openai==0.0.8 langchain-text-splitters==0.0.1 openinference-instrumentation-langchain==0.1.14
When BedrockChat model is initialized with guardrails argument, _prepare_input_and_invoke raises "Unknown parameter in input: "guardrail" exception"
https://api.github.com/repos/langchain-ai/langchain/issues/21107/comments
2
2024-04-30T18:22:10Z
2024-05-02T15:27:50Z
https://github.com/langchain-ai/langchain/issues/21107
2,272,191,216
21,107
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code tool_n = [BingSearchAPIWrapper()] system_prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful assistant. Make sure to use the tavily_search_results_json tool for information.", ), ("placeholder", "{chat_history}"), ("human", "{input}"), ("placeholder", "{agent_scratchpad}"), ] ) # Construct the Tools agent agent = create_tool_calling_agent(llm=llm_langchain_ChatOpenAI, tools = tool_n, prompt = system_prompt) agent_executor = AgentExecutor(agent=agent,tools=tools,verbose=True) agent_executor.invoke({"input":"What is 2*2"}) ### Error Message and Stack Trace (if applicable) --------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) [<ipython-input-12-fe75faac265c>](https://localhost:8080/#) in <cell line: 18>() 16 17 ---> 18 agent = create_tool_calling_agent(llm=llm_langchain_ChatOpenAI, 19 tools = tool_n, 20 prompt = system_prompt) 1 frames [/usr/local/lib/python3.10/dist-packages/langchain_core/language_models/chat_models.py](https://localhost:8080/#) in bind_tools(self, tools, **kwargs) 910 **kwargs: Any, 911 ) -> Runnable[LanguageModelInput, BaseMessage]: --> 912 raise NotImplementedError() 913 914 NotImplementedError: ### Description I am trying to use create_tool_calling_agent ### System Info google colab : !pip install -q langchain
NotImplementedError where using LangChain create_tool_calling_agent without further details
https://api.github.com/repos/langchain-ai/langchain/issues/21102/comments
3
2024-04-30T16:58:29Z
2024-05-02T15:04:36Z
https://github.com/langchain-ai/langchain/issues/21102
2,272,054,021
21,102
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code conda install langchain -c conda-forge ### Error Message and Stack Trace (if applicable) Collecting package metadata: done Solving environment: failed PackagesNotFoundError: The following packages are not available from current channels: - langchain Current channels: - https://conda.anaconda.org/conda-forge/linux-64 - https://conda.anaconda.org/conda-forge/noarch - https://repo.anaconda.com/pkgs/main/linux-64 - https://repo.anaconda.com/pkgs/main/noarch - https://repo.anaconda.com/pkgs/free/linux-64 - https://repo.anaconda.com/pkgs/free/noarch - https://repo.anaconda.com/pkgs/r/linux-64 - https://repo.anaconda.com/pkgs/r/noarch To search for alternate channels that may provide the conda package you're looking for, navigate to https://anaconda.org and use the search bar at the top of the page. ### Description Installation problem ### System Info pip freeze | grep langchain as expected none Python 3.7.3 miniconda on linux
Installation of langchain on miniconda with the conda install langchain -c conda-forge fails
https://api.github.com/repos/langchain-ai/langchain/issues/21084/comments
2
2024-04-30T14:25:21Z
2024-04-30T14:44:19Z
https://github.com/langchain-ai/langchain/issues/21084
2,271,619,900
21,084
[ "langchain-ai", "langchain" ]
### Privileged issue - [X] I am a LangChain maintainer, or was asked directly by a LangChain maintainer to create an issue here. ### Issue Content No help is required here. Creating an issue to link associated PRs.
Convert imports in langchain to langchain community to use optional imports
https://api.github.com/repos/langchain-ai/langchain/issues/21080/comments
3
2024-04-30T13:27:59Z
2024-05-23T00:39:09Z
https://github.com/langchain-ai/langchain/issues/21080
2,271,482,094
21,080
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code Using a ConversationSummaryBufferMemory generates an error: ``` chat_history_for_chain = ConversationSummaryBufferMemory(llm=self.model, memory_key="history", input_key="input",max_token_limit=200, return_messages=False) self.chain_with_message_history = RunnableWithMessageHistory( self.chain_with_chat_history, lambda session_id: chat_history_for_chain, input_messages_key="input", history_messages_key="history", ) ``` The code works fine if replaced with another type of memory ### Error Message and Stack Trace (if applicable) AttributeError: 'ConversationSummaryBufferMemory' object has no attribute 'aget_messages'. Did you mean: 'return_messages'? ### Description Using a ConversationSummaryBufferMemory generates an error: The code works fine if replaced with another type of memory ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:11:08 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T8122 > Python Version: 3.10.14 (main, Mar 21 2024, 11:21:31) [Clang 14.0.6 ] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.48 > langchain_chroma: 0.1.0 > langchain_experimental: 0.0.57 > langchain_groq: 0.1.2 > langchain_openai: 0.1.3 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 > langserve: 0.1.0 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found:
RunnableWithMessageHistory and ConversationSummaryBufferMemory
https://api.github.com/repos/langchain-ai/langchain/issues/21069/comments
1
2024-04-30T09:59:07Z
2024-05-28T15:56:21Z
https://github.com/langchain-ai/langchain/issues/21069
2,271,032,796
21,069
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` llm = VLLMOpenAI( max_tokens=10000, temperature=0.7, openai_api_key="EMPTY", openai_api_base="http://xx.xx.xx.xx:8080/v1", # xx indicates my IP address, which I cannot disclose due to privacy concerns model_name="/data/models/Qwen1.5-72B-Chat/" ) blobpath = "https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken" cache_key = hashlib.sha1(blobpath.encode()).hexdigest() tiktoken_cache_dir = "/app/api" os.environ["TIKTOKEN_CACHE_DIR"] = tiktoken_cache_dir assert os.path.exists(os.path.join(tiktoken_cache_dir, cache_key)) if not pdfs_folder: return self.create_text_message('Please input pdfs_folder') def summarize_pdfs_from_folder(pdfs_folder): summaries = [] for pdf_file in glob.glob(pdfs_folder + "/*.pdf"): loader = PyPDFLoader(pdf_file) docs = loader.load_and_split() prompt_template = """Write a concise summary of the following: {text} CONCISE SUMMARY IN CHINESE:""" PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"]) chain = load_summarize_chain(llm, chain_type="map_reduce", return_intermediate_steps=False, map_prompt=PROMPT, combine_prompt=PROMPT) summary = chain.run(docs) summaries.append(summary) return summaries summaries = summarize_pdfs_from_folder("/home/user/mytest") ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description When I use the map_reduce mode of load_summarize_chain in version 0.1.16 of langchain, I encounter output_text being occasionally empty. ① I am a summary of pdf documents, and each pdf document is divided by page. So I printed intermediate_steps, and I found that intermediate_steps has a summary of the parts that are divided, but not all of them. For example, a pdf has ten pages, while intermediate_steps has only a summary of one page, sometimes six or ten. ③ And I have made it clear IN my prompt that CONSIE IN CHINESE, but this will be the case in every summary of intermediate_steps, a Chinese abstract +CONCISE IN ENGLISH: English abstract. ### System Info System Information ------------------ > OS: Ubuntu 22.04 > Python Version: 3.12.3 Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.52 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
Using the map_reduce mode load_summarize_chain in version 0.1.16 of langchain, I occasionally ran into situations where output_text was empty.
https://api.github.com/repos/langchain-ai/langchain/issues/21068/comments
0
2024-04-30T09:47:11Z
2024-05-08T07:08:18Z
https://github.com/langchain-ai/langchain/issues/21068
2,271,009,424
21,068
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` import json from langchain_text_splitters import RecursiveJsonSplitter print('json 1: ') json_1 = '{"position": 2, "song": {"song_id": 1729856953, "name": "Whatever She Wants", "artist_name": "Bryson Tiller", "present_in_top": true, "rating": "explicit", "artists_slugs": [{"artist_name": "Bryson Tiller", "artist_slug": "bryson-tiller"}], "artwork_url_small": "https://is1-ssl.mzstatic.com/image/thumb/Music116/v4/6d/c3/0c/6dc30cf7-86ee-5e87-8703-d0eb4fbddbdd/196871828352.jpg/60x60bb.jpg", "artwork_url_large": "https://is1-ssl.mzstatic.com/image/thumb/Music116/v4/6d/c3/0c/6dc30cf7-86ee-5e87-8703-d0eb4fbddbdd/196871828352.jpg/170x170bb.jpg", "release": null, "apple_music_view_url": "https://geo.music.apple.com/de/album/whatever-she-wants/1729856932?i=1729856953&app=music&mt=1&at=11l64h&ct=top-charts", "itunes_view_url": "https://geo.music.apple.com/de/album/whatever-she-wants/1729856932?i=1729856953&app=itunes&mt=1&at=11l64h&ct=top-charts", "preview_url": "https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview116/v4/2c/59/69/2c59694d-674b-f702-8d7d-010c32d86d72/mzaf_13580580607794748358.plus.aac.p.m4a", "slug": "whatever-she-wants-bryson-tiller"}}' json_1_dict = json.loads(json_1) print(f'before split: {json_1_dict}') print('# ----- do the split!!') json_splitter_1 = RecursiveJsonSplitter(max_chunk_size=1000) split_json_1 = json_splitter_1.split_text(json_data=json.loads(json_1)) print(f'after split: ') for sp in split_json_1: print(sp) print('# --- each split') print('') print('json 2: ') json_2 = '{"position": 3, "song": {"song_id": 1724494724, "name": "redrum", "artist_name": "21 Savage", "present_in_top": true, "rating": "explicit", "artists_slugs": [{"artist_name": "21 Savage", "artist_slug": "21-savage"}], "artwork_url_small": "https://is1-ssl.mzstatic.com/image/thumb/Music116/v4/de/82/b9/de82b98d-56a1-e27b-10ea-46964f4585e4/196871714549.jpg/60x60bb.jpg", "artwork_url_large": "https://is1-ssl.mzstatic.com/image/thumb/Music116/v4/de/82/b9/de82b98d-56a1-e27b-10ea-46964f4585e4/196871714549.jpg/170x170bb.jpg", "release": "2024-01-12", "apple_music_view_url": "https://geo.music.apple.com/ca/album/redrum/1724494274?i=1724494724&app=music&mt=1&at=11l64h&ct=top-charts", "itunes_view_url": "https://geo.music.apple.com/ca/album/redrum/1724494274?i=1724494724&app=itunes&mt=1&at=11l64h&ct=top-charts", "preview_url": "https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview126/v4/9f/f3/4e/9ff34eab-0ba1-3490-982d-1d761a415d0e/mzaf_170736944635699700.plus.aac.p.m4a", "slug": "redrum-21-savage"}}' json_2_dict = json.loads(json_2) print(f'before split: {json_2_dict}') print('# ----- do the split!!') json_splitter_2 = RecursiveJsonSplitter(max_chunk_size=1000) split_json_2 = json_splitter_2.split_text(json_data=json.loads(json_2)) print(f'after split: ') for sp in split_json_2: print(sp) print('# --- each split') ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description I found the bug with RecursiveJsonSplitter using the following code: different RecursiveJsonSplitter instances have mixed other input's output. Is it a singleton instance and cached previous split results? print results with the above code: <img width="1336" alt="image" src="https://github.com/langchain-ai/langchain/assets/5728396/6b6afde8-dc2d-4812-a853-427cdd31d508"> ### System Info pip packages version: ``` # pip freeze | grep langchain langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.46 langchain-text-splitters==0.0.1 ``` ``` # python -m langchain_core.sys_info System Information ------------------ > OS: Linux > OS Version: #101-Ubuntu SMP Tue Nov 14 13:30:08 UTC 2023 > Python Version: 3.10.8 (main, Nov 24 2022, 14:13:03) [GCC 11.2.0] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.52 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve ```
[BUG] RecursiveJsonSplitter split result has mixed other input's cached output with different input json_data
https://api.github.com/repos/langchain-ai/langchain/issues/21066/comments
1
2024-04-30T09:26:43Z
2024-08-05T16:07:11Z
https://github.com/langchain-ai/langchain/issues/21066
2,270,968,999
21,066
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from langchain_core.prompts import ChatPromptTemplate from langchain_groq import ChatGroq chat = ChatGroq( temperature=0, api_key="xxxxxxxxxx", model="llama3-70b-8192" ) system = "You are a helpful assistant." human = "{text}" prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)]) chain = prompt | chat result = chain.invoke({"text": "Explain the importance of low latency LLMs."}) print(result.content) ### Error Message and Stack Trace (if applicable) Traceback (most recent call last): File "D:\AIGC\idataai_py\test\groq.py", line 7, in <module> chat = ChatGroq( ^^^^^^^^^ File "D:\AIGC\idataai_py\venv\Lib\site-packages\langchain_core\load\serializable.py", line 120, in __init__ super().__init__(**kwargs) File "D:\AIGC\idataai_py\venv\Lib\site-packages\pydantic\v1\main.py", line 339, in __init__ values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\AIGC\idataai_py\venv\Lib\site-packages\pydantic\v1\main.py", line 1100, in validate_model values = validator(cls_, values) ^^^^^^^^^^^^^^^^^^^^^^^ File "D:\AIGC\idataai_py\venv\Lib\site-packages\langchain_groq\chat_models.py", line 190, in validate_environment import groq File "D:\AIGC\idataai_py\test\groq.py", line 7, in <module> chat = ChatGroq( ^^^^^^^^^ File "D:\AIGC\idataai_py\venv\Lib\site-packages\langchain_core\load\serializable.py", line 120, in __init__ super().__init__(**kwargs) File "D:\AIGC\idataai_py\venv\Lib\site-packages\pydantic\v1\main.py", line 339, in __init__ values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\AIGC\idataai_py\venv\Lib\site-packages\pydantic\v1\main.py", line 1100, in validate_model values = validator(cls_, values) ^^^^^^^^^^^^^^^^^^^^^^^ File "D:\AIGC\idataai_py\venv\Lib\site-packages\langchain_groq\chat_models.py", line 193, in validate_environment values["client"] = groq.Groq(**client_params).chat.completions ^^^^^^^^^ AttributeError: partially initialized module 'groq' has no attribute 'Groq' (most likely due to a circular import) ### Description I am testing groq with langchain ### System Info win10 python 3.11
Groq can not work
https://api.github.com/repos/langchain-ai/langchain/issues/21061/comments
1
2024-04-30T09:09:25Z
2024-04-30T12:58:33Z
https://github.com/langchain-ai/langchain/issues/21061
2,270,933,479
21,061
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` python from langchain_community.chat_models.azureml_endpoint import AzureMLChatOnlineEndpoint, CustomOpenAIChatContentFormatter, AzureMLEndpointApiType from langchain_core.messages import HumanMessage chat = AzureMLChatOnlineEndpoint(endpoint_url="https://Meta-Llama-3-70B-Instruct-pixvc-serverless.swedencentral.inference.ai.azure.com", deployment_name="Meta-Llama-3-70B-Instruct-pixvc", endpoint_api_type=AzureMLEndpointApiType.serverless, endpoint_api_key="<your-api-key>", content_formatter=CustomOpenAIChatContentFormatter()) response = chat.invoke([HumanMessage("Hello, how are you?")]) print(response) ``` ### Error Message and Stack Trace (if applicable) ``` console ValidationError: 2 validation errors for AzureMLOnlineEndpoint endpoint_api_type Endpoints of type `serverless` should follow the format `[https://<your-endpoint>.<your_region>.inference.ml.azure.com/v1/chat/completions`](https://%3Cyour-endpoint%3E.%3Cyour_region%3E.inference.ml.azure.com/v1/chat/completions%60) or `[https://<your-endpoint>.<your_region>.inference.ml.azure.com/v1/chat/completions`](https://%3Cyour-endpoint%3E.%3Cyour_region%3E.inference.ml.azure.com/v1/chat/completions%60) (type=value_error) content_formatter Content formatter f<class 'langchain_community.chat_models.azureml_endpoint.CustomOpenAIChatContentFormatter'> is not supported by this endpoint. Supported types are [<AzureMLEndpointApiType.dedicated: 'dedicated'>, <AzureMLEndpointApiType.serverless: 'serverless'>] but endpoint is None. (type=value_error) ``` ### Description I'm attempting to use the llama3 70B model via Azure AI Studio with langchain. However, the target I receive from Azure AI Studio for the model is https://Meta-Llama-3-70B-Instruct-pixvc-serverless.swedencentral.inference.ai.azure.com. I encounter an error stating that my endpoint is not in the correct format. ### System Info ``` System Information ------------------ > OS: Linux > OS Version: #29-Ubuntu SMP PREEMPT_DYNAMIC Thu Mar 28 23:46:48 UTC 2024 > Python Version: 3.11.6 (main, Oct 8 2023, 05:06:43) [GCC 13.2.0] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.51 > langchain_openai: 0.1.4 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve ```
Azure AI Studio Llama3 Models incompatible with `AzureMLChatOnlineEndpoint`
https://api.github.com/repos/langchain-ai/langchain/issues/21060/comments
3
2024-04-30T08:15:19Z
2024-04-30T14:16:40Z
https://github.com/langchain-ai/langchain/issues/21060
2,270,812,726
21,060
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python import httpx from langchain_core.output_parsers import StrOutputParser from langchain_mistralai import ChatMistralAI prompt = PromptTemplate(input_variables=["alpha", "beta"], template=("""lorem ipsum sit amet dolor: '{alpha}', generate additional lorem ipsum {beta} times. For example: if there are alpha lorem ipsum, the final lorem ipsum must be beta. Output: """)) chain = ( prompt | ChatMistralAI(temperature=0, model="mixtral-8x7b-instruct-v01", endpoint='https://some-openai-compatible-endpoint.com/v1', api_key="whatever", client=httpx.Client(verify=False), max_tokens=8000, safe_mode=True, streaming=True) | StrOutputParser() | (lambda x: x.split("\n")) ) alpha = "lorem ipsum" beta = 4 output = chain.invoke({"alpha": alpha, "beta": beta}) output ``` ### Error Message and Stack Trace (if applicable) ``` { "name": "UnsupportedProtocol", "message": "Request URL is missing an 'http://' or 'https://' protocol.", "stack": "--------------------------------------------------------------------------- UnsupportedProtocol Traceback (most recent call last) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_transports\\default.py:69, in map_httpcore_exceptions() 68 try: ---> 69 yield 70 except Exception as exc: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_transports\\default.py:233, in HTTPTransport.handle_request(self, request) 232 with map_httpcore_exceptions(): --> 233 resp = self._pool.handle_request(req) 235 assert isinstance(resp.stream, typing.Iterable) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpcore\\_sync\\connection_pool.py:167, in ConnectionPool.handle_request(self, request) 166 if scheme == \"\": --> 167 raise UnsupportedProtocol( 168 \"Request URL is missing an 'http://' or 'https://' protocol.\" 169 ) 170 if scheme not in (\"http\", \"https\", \"ws\", \"wss\"): UnsupportedProtocol: Request URL is missing an 'http://' or 'https://' protocol. The above exception was the direct cause of the following exception: UnsupportedProtocol Traceback (most recent call last) Cell In[7], line 3 1 alpha = \"lorem ipsum\" 2 beta = 4 ----> 3 output = chain.invoke({\"alpha\": alpha, \"beta\": beta}) 4 output File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\runnables\\base.py:2499, in RunnableSequence.invoke(self, input, config) 2497 try: 2498 for i, step in enumerate(self.steps): -> 2499 input = step.invoke( 2500 input, 2501 # mark each step as a child run 2502 patch_config( 2503 config, callbacks=run_manager.get_child(f\"seq:step:{i+1}\") 2504 ), 2505 ) 2506 # finish the root run 2507 except BaseException as e: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:158, in BaseChatModel.invoke(self, input, config, stop, **kwargs) 147 def invoke( 148 self, 149 input: LanguageModelInput, (...) 153 **kwargs: Any, 154 ) -> BaseMessage: 155 config = ensure_config(config) 156 return cast( 157 ChatGeneration, --> 158 self.generate_prompt( 159 [self._convert_input(input)], 160 stop=stop, 161 callbacks=config.get(\"callbacks\"), 162 tags=config.get(\"tags\"), 163 metadata=config.get(\"metadata\"), 164 run_name=config.get(\"run_name\"), 165 run_id=config.pop(\"run_id\", None), 166 **kwargs, 167 ).generations[0][0], 168 ).message File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:560, in BaseChatModel.generate_prompt(self, prompts, stop, callbacks, **kwargs) 552 def generate_prompt( 553 self, 554 prompts: List[PromptValue], (...) 557 **kwargs: Any, 558 ) -> LLMResult: 559 prompt_messages = [p.to_messages() for p in prompts] --> 560 return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:421, in BaseChatModel.generate(self, messages, stop, callbacks, tags, metadata, run_name, run_id, **kwargs) 419 if run_managers: 420 run_managers[i].on_llm_error(e, response=LLMResult(generations=[])) --> 421 raise e 422 flattened_outputs = [ 423 LLMResult(generations=[res.generations], llm_output=res.llm_output) # type: ignore[list-item] 424 for res in results 425 ] 426 llm_output = self._combine_llm_outputs([res.llm_output for res in results]) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:411, in BaseChatModel.generate(self, messages, stop, callbacks, tags, metadata, run_name, run_id, **kwargs) 408 for i, m in enumerate(messages): 409 try: 410 results.append( --> 411 self._generate_with_cache( 412 m, 413 stop=stop, 414 run_manager=run_managers[i] if run_managers else None, 415 **kwargs, 416 ) 417 ) 418 except BaseException as e: 419 if run_managers: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:632, in BaseChatModel._generate_with_cache(self, messages, stop, run_manager, **kwargs) 630 else: 631 if inspect.signature(self._generate).parameters.get(\"run_manager\"): --> 632 result = self._generate( 633 messages, stop=stop, run_manager=run_manager, **kwargs 634 ) 635 else: 636 result = self._generate(messages, stop=stop, **kwargs) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_mistralai\\chat_models.py:454, in ChatMistralAI._generate(self, messages, stop, run_manager, stream, **kwargs) 450 if should_stream: 451 stream_iter = self._stream( 452 messages, stop=stop, run_manager=run_manager, **kwargs 453 ) --> 454 return generate_from_stream(stream_iter) 456 message_dicts, params = self._create_message_dicts(messages, stop) 457 params = {**params, **kwargs} File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:67, in generate_from_stream(stream) 64 \"\"\"Generate from a stream.\"\"\" 66 generation: Optional[ChatGenerationChunk] = None ---> 67 for chunk in stream: 68 if generation is None: 69 generation = chunk File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_mistralai\\chat_models.py:501, in ChatMistralAI._stream(self, messages, stop, run_manager, **kwargs) 498 params = {**params, **kwargs, \"stream\": True} 500 default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk --> 501 for chunk in self.completion_with_retry( 502 messages=message_dicts, run_manager=run_manager, **params 503 ): 504 if len(chunk[\"choices\"]) == 0: 505 continue File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_mistralai\\chat_models.py:366, in ChatMistralAI.completion_with_retry.<locals>._completion_with_retry.<locals>.iter_sse() 365 def iter_sse() -> Iterator[Dict]: --> 366 with connect_sse( 367 self.client, \"POST\", \"/chat/completions\", json=kwargs 368 ) as event_source: 369 _raise_on_error(event_source.response) 370 for event in event_source.iter_sse(): File ~\\scoop\\persist\\rye\\py\\cpython@3.11.8\\Lib\\contextlib.py:137, in _GeneratorContextManager.__enter__(self) 135 del self.args, self.kwds, self.func 136 try: --> 137 return next(self.gen) 138 except StopIteration: 139 raise RuntimeError(\"generator didn't yield\") from None File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx_sse\\_api.py:54, in connect_sse(client, method, url, **kwargs) 51 headers[\"Accept\"] = \"text/event-stream\" 52 headers[\"Cache-Control\"] = \"no-store\" ---> 54 with client.stream(method, url, headers=headers, **kwargs) as response: 55 yield EventSource(response) File ~\\scoop\\persist\\rye\\py\\cpython@3.11.8\\Lib\\contextlib.py:137, in _GeneratorContextManager.__enter__(self) 135 del self.args, self.kwds, self.func 136 try: --> 137 return next(self.gen) 138 except StopIteration: 139 raise RuntimeError(\"generator didn't yield\") from None File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:870, in Client.stream(self, method, url, content, data, files, json, params, headers, cookies, auth, follow_redirects, timeout, extensions) 847 \"\"\" 848 Alternative to `httpx.request()` that streams the response body 849 instead of loading it into memory at once. (...) 855 [0]: /quickstart#streaming-responses 856 \"\"\" 857 request = self.build_request( 858 method=method, 859 url=url, (...) 868 extensions=extensions, 869 ) --> 870 response = self.send( 871 request=request, 872 auth=auth, 873 follow_redirects=follow_redirects, 874 stream=True, 875 ) 876 try: 877 yield response File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:914, in Client.send(self, request, stream, auth, follow_redirects) 906 follow_redirects = ( 907 self.follow_redirects 908 if isinstance(follow_redirects, UseClientDefault) 909 else follow_redirects 910 ) 912 auth = self._build_request_auth(request, auth) --> 914 response = self._send_handling_auth( 915 request, 916 auth=auth, 917 follow_redirects=follow_redirects, 918 history=[], 919 ) 920 try: 921 if not stream: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:942, in Client._send_handling_auth(self, request, auth, follow_redirects, history) 939 request = next(auth_flow) 941 while True: --> 942 response = self._send_handling_redirects( 943 request, 944 follow_redirects=follow_redirects, 945 history=history, 946 ) 947 try: 948 try: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:979, in Client._send_handling_redirects(self, request, follow_redirects, history) 976 for hook in self._event_hooks[\"request\"]: 977 hook(request) --> 979 response = self._send_single_request(request) 980 try: 981 for hook in self._event_hooks[\"response\"]: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:1015, in Client._send_single_request(self, request) 1010 raise RuntimeError( 1011 \"Attempted to send an async request with a sync Client instance.\" 1012 ) 1014 with request_context(request=request): -> 1015 response = transport.handle_request(request) 1017 assert isinstance(response.stream, SyncByteStream) 1019 response.request = request File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_transports\\default.py:232, in HTTPTransport.handle_request(self, request) 218 assert isinstance(request.stream, SyncByteStream) 220 req = httpcore.Request( 221 method=request.method, 222 url=httpcore.URL( (...) 230 extensions=request.extensions, 231 ) --> 232 with map_httpcore_exceptions(): 233 resp = self._pool.handle_request(req) 235 assert isinstance(resp.stream, typing.Iterable) File ~\\scoop\\persist\\rye\\py\\cpython@3.11.8\\Lib\\contextlib.py:158, in _GeneratorContextManager.__exit__(self, typ, value, traceback) 156 value = typ() 157 try: --> 158 self.gen.throw(typ, value, traceback) 159 except StopIteration as exc: 160 # Suppress StopIteration *unless* it's the same exception that 161 # was passed to throw(). This prevents a StopIteration 162 # raised inside the \"with\" statement from being suppressed. 163 return exc is not value File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_transports\\default.py:86, in map_httpcore_exceptions() 83 raise 85 message = str(exc) ---> 86 raise mapped_exc(message) from exc UnsupportedProtocol: Request URL is missing an 'http://' or 'https://' protocol." } ``` ### Description I just need the response as the output but instead even after passing the endpoint which is prefixed with `https://` I still get the issue mentioned above. I suspect the issue is how the parameters in the constructor are currently being parsed. ### System Info System Information ------------------ > OS: Windows > OS Version: 10.0.22621 > Python Version: 3.11.8 (main, Feb 25 2024, 03:41:44) [MSC v.1929 64 bit (AMD64)] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.52 > langchain_mistralai: 0.1.5 > langchain_openai: 0.1.4 > langchain_postgres: 0.0.3 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 > langgraph: 0.0.32 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langserve
mistralai: throws UnsupportedProtocol error even if the endpoint argument contains 'https://'
https://api.github.com/repos/langchain-ai/langchain/issues/21055/comments
2
2024-04-30T06:36:31Z
2024-04-30T11:20:32Z
https://github.com/langchain-ai/langchain/issues/21055
2,270,621,792
21,055
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python import os from dotenv import load_dotenv load_dotenv() db_user = os.getenv("db_user") db_password = os.getenv("db_password") db_host = os.getenv("db_host") db_name = os.getenv("db_name") port = os.getenv("port") OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY") OPENAI_DEPLOYMENT_NAME = os.getenv("OPENAI_DEPLOYMENT_NAME") OPENAI_MODEL_NAME = os.getenv("OPENAI_MODEL_NAME") # LANGCHAIN_TRACING_V2 = os.getenv("LANGCHAIN_TRACING_V2") # LANGCHAIN_API_KEY = os.getenv("LANGCHAIN_API_KEY") from langchain_community.utilities.sql_database import SQLDatabase from langchain.chains import create_sql_query_chain # from langchain_openai import ChatOpenAI # from langchain.llms import AzureOpenAI # from langchain_community.llms import AzureOpenAI from langchain_openai import AzureOpenAI from langchain.sql_database import SQLDatabase from langchain_community.tools.sql_database.tool import QuerySQLDataBaseTool from langchain.memory import ChatMessageHistory from operator import itemgetter from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough # from langchain_openai import ChatOpenAI from table_details import table_chain as select_table from prompts import final_prompt, answer_prompt from sqlalchemy import create_engine import streamlit as st @st.cache_resource def get_chain(): print("Creating chain") # db = SQLDatabase.from_uri(f"redshift+psycopg2://{db_user}:{db_password}@{db_host}:{port}/{db_name}") engine = create_engine(f"redshift+psycopg2://{db_user}:{db_password}@{db_host}:{port}/{db_name}") db = SQLDatabase(engine, schema = 'poc_ai_sql_chat') print("Connected to DB") # llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0) llm = AzureOpenAI(deployment_name=OPENAI_DEPLOYMENT_NAME, model_name=OPENAI_MODEL_NAME, temperature=0) generate_query = create_sql_query_chain(llm, db, final_prompt) execute_query = QuerySQLDataBaseTool(db=db) rephrase_answer = answer_prompt | llm | StrOutputParser() # chain = generate_query | execute_query chain = ( RunnablePassthrough.assign(table_names_to_use=select_table) | RunnablePassthrough.assign(query=generate_query).assign( result=itemgetter("query") | execute_query ) | rephrase_answer ) return chain def create_history(messages): history = ChatMessageHistory() for message in messages: if message["role"] == "user": history.add_user_message(message["content"]) else: history.add_ai_message(message["content"]) return history def invoke_chain(question,messages): chain = get_chain() history = create_history(messages) response = chain.invoke({"question": question,"top_k":3,"messages":history.messages}) history.add_user_message(question) history.add_ai_message(response) return response ``` ### Error Message and Stack Trace (if applicable) file "C:\Users\jyang29\Desktop\work\Generative_AI_POC\chatwithredshift\main.py", line 40, in response = invoke_chain(prompt,st.session_state.messages) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Desktop\work\Generative_AI_POC\chatwithredshift\langchain_utils.py", line 73, in invoke_chain response = chain.invoke({"question": question,"top_k":3,"messages":history.messages}) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\base.py", line 2499, in invoke input = step.invoke( ^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\passthrough.py", line 470, in invoke return self._call_with_config(self._invoke, input, config, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\base.py", line 1626, in _call_with_config context.run( File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\config.py", line 347, in call_func_with_variable_args return func(input, **kwargs) # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\passthrough.py", line 457, in _invoke **self.mapper.invoke( ^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\base.py", line 3142, in invoke output = {key: future.result() for key, future in zip(steps, futures)} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\base.py", line 3142, in output = {key: future.result() for key, future in zip(steps, futures)} ^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\concurrent\futures_base.py", line 456, in result return self.__get_result() ^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\concurrent\futures_base.py", line 401, in __get_result raise self._exception File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\concurrent\futures\thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\base.py", line 2499, in invoke input = step.invoke( ^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\runnables\base.py", line 4525, in invoke return self.bound.invoke( ^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\language_models\llms.py", line 276, in invoke self.generate_prompt( File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\language_models\llms.py", line 633, in generate_prompt return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\language_models\llms.py", line 803, in generate output = self._generate_helper( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\language_models\llms.py", line 670, in _generate_helper raise e File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_core\language_models\llms.py", line 657, in _generate_helper self._generate( File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_community\llms\openai.py", line 460, in _generate response = completion_with_retry( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\langchain_community\llms\openai.py", line 115, in completion_with_retry return llm.client.create(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\jyang29\Anaconda3\envs\langchainwithsql\Lib\site-packages\openai_utils_utils.py", line 277, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ TypeError: Completions.create() got an unexpected keyword argument 'tools' ### Description I am trying to build a streamlit chatbot to talk with redshift database using LangChain sql chain, Azure LLM gpt-35-turbo and ada002 model for text embedding from Azure. ### System Info Python 3.11 on windows OS with the following most-recent package versions: aiohttp 3.9.5 aiosignal 1.3.1 altair 5.3.0 annotated-types 0.6.0 anyio 4.3.0 asgiref 3.8.1 attrs 23.2.0 backoff 2.2.1 bcrypt 4.1.2 blinker 1.7.0 build 1.2.1 cachetools 5.3.3 certifi 2024.2.2 charset-normalizer 3.3.2 chroma-hnswlib 0.7.3 chromadb 0.5.0 click 8.1.7 colorama 0.4.6 coloredlogs 15.0.1 dataclasses-json 0.6.4 Deprecated 1.2.14 distro 1.9.0 fastapi 0.110.2 filelock 3.13.4 flatbuffers 24.3.25 frozenlist 1.4.1 fsspec 2024.3.1 gitdb 4.0.11 GitPython 3.1.43 google-auth 2.29.0 googleapis-common-protos 1.63.0 greenlet 3.0.3 grpcio 1.62.2 h11 0.14.0 httpcore 1.0.5 httptools 0.6.1 httpx 0.27.0 huggingface-hub 0.22.2 humanfriendly 10.0 idna 3.7 importlib-metadata 7.0.0 importlib_resources 6.4.0 Jinja2 3.1.3 jsonpatch 1.33 jsonpointer 2.4 jsonschema 4.21.1 jsonschema-specifications 2023.12.1 kubernetes 29.0.0 langchain 0.1.16 langchain-community 0.0.34 langchain-core 0.1.46 langchain-openai 0.1.4 langchain-text-splitters 0.0.1 langsmith 0.1.50 markdown-it-py 3.0.0 MarkupSafe 2.1.5 marshmallow 3.21.1 mdurl 0.1.2 mmh3 4.1.0 monotonic 1.6 mpmath 1.3.0 multidict 6.0.5 mypy-extensions 1.0.0 numpy 1.26.4 oauthlib 3.2.2 onnxruntime 1.17.3 openai 1.23.2 opentelemetry-api 1.24.0 opentelemetry-exporter-otlp-proto-common 1.24.0 opentelemetry-exporter-otlp-proto-grpc 1.24.0 opentelemetry-instrumentation 0.45b0 opentelemetry-instrumentation-asgi 0.45b0 opentelemetry-instrumentation-fastapi 0.45b0 opentelemetry-proto 1.24.0 opentelemetry-sdk 1.24.0 opentelemetry-semantic-conventions 0.45b0 opentelemetry-util-http 0.45b0 orjson 3.10.1 overrides 7.7.0 packaging 23.2 pandas 2.2.2 pillow 10.3.0 pip 23.3.1 posthog 3.5.0 protobuf 4.25.3 psycopg2-binary 2.9.9 pyarrow 16.0.0 pyasn1 0.6.0 pyasn1_modules 0.4.0 pydantic 2.7.0 pydantic_core 2.18.1 pydeck 0.8.1b0 Pygments 2.17.2 PyPika 0.48.9 pyproject_hooks 1.0.0 pyreadline3 3.4.1 python-dateutil 2.9.0.post0 python-dotenv 1.0.1 pytz 2024.1 PyYAML 6.0.1 referencing 0.34.0 regex 2024.4.16 requests 2.31.0 requests-oauthlib 2.0.0 rich 13.7.1 rpds-py 0.18.0 rsa 4.9 setuptools 68.2.2 shellingham 1.5.4 six 1.16.0 smmap 5.0.1 sniffio 1.3.1 SQLAlchemy 1.4.52 sqlalchemy-redshift 0.8.14 starlette 0.37.2 streamlit 1.33.0 sympy 1.12 tenacity 8.2.3 tiktoken 0.6.0 tokenizers 0.19.1 toml 0.10.2 toolz 0.12.1 tornado 6.4 tqdm 4.66.2 typer 0.12.3 typing_extensions 4.11.0 typing-inspect 0.9.0 tzdata 2024.1 urllib3 2.2.1 uvicorn 0.29.0 watchdog 4.0.0 watchfiles 0.21.0 websocket-client 1.8.0 websockets 12.0 wheel 0.41.2 wrapt 1.16.0 yarl 1.9.4 zipp 3.18.1
TypeError: Completions.create() got an unexpected keyword argument 'tools'
https://api.github.com/repos/langchain-ai/langchain/issues/21047/comments
2
2024-04-30T01:09:47Z
2024-08-04T16:06:16Z
https://github.com/langchain-ai/langchain/issues/21047
2,270,299,116
21,047
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from langchain_community.tools import DuckDuckGoSearchRun search_tool = DuckDuckGoSearchRun() ### Error Message and Stack Trace (if applicable) raise validation_error pydantic.v1.error_wrappers.ValidationError: 1 validation error for DuckDuckGoSearchAPIWrapper __root__ deprecated() got an unexpected keyword argument 'name' (type=type_error) ### Description trying to use with crewai ### System Info can't
Problem with using DDG as search tool
https://api.github.com/repos/langchain-ai/langchain/issues/21045/comments
5
2024-04-29T22:50:51Z
2024-08-10T16:06:42Z
https://github.com/langchain-ai/langchain/issues/21045
2,270,123,145
21,045
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain.chains import LLMChain from langchain.prompts import HumanMessagePromptTemplate from langchain.prompts.chat import ChatPromptTemplate from langchain_community.chat_models import BedrockChat import langchain langchain.debug = True def get_llama3_bedrock( model_id="meta.llama3-70b-instruct-v1:0", max_gen_len=2048, top_p=0.0, temperature=0.0, ): model_kwargs = { "top_p": top_p, "max_gen_len": max_gen_len, "temperature": temperature, } return BedrockChat(model_id=model_id, model_kwargs=model_kwargs) prompt_poem = """ This is a poem by William Blake ============ Never seek to tell thy love Love that never told can be For the gentle wind does move Silently invisibly I told my love I told my love I told her all my heart Trembling cold in ghastly fears Ah she doth depart Soon as she was gone from me A traveller came by Silently invisibly O was no deny ============ What did the lady do? """ langchain_prompt = ChatPromptTemplate.from_messages([ HumanMessagePromptTemplate.from_template(prompt_poem) ] ) print("Response 1:", LLMChain(llm=get_llama3_bedrock(), prompt=langchain_prompt).run(dict())) #Responds: '' prompt_simple_question = """What is the capital of China?""" langchain_prompt = ChatPromptTemplate.from_messages([ HumanMessagePromptTemplate.from_template(prompt_simple_question) ] ) print("Response 2:", LLMChain(llm=get_llama3_bedrock(), prompt=langchain_prompt).run(dict())) #Responds: 'Beijing.' ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description I am trying to use `BedrockChat` to call Llama3 on our AWS account. Here is the issue: - I try to pass a long-ish (multiline) prompt and it returns an empty string. - Passing the same long-ish prompt directly on the AWS Console generate the expected answer. <img width="1676" alt="image" src="https://github.com/langchain-ai/langchain/assets/145778824/7722a55d-cd00-4885-86ab-c652e6f5f792"> - Passing a single line questions like `What is the capital of China?` return the expected answer `Beijing.` ### System Info platform: mac python version: 3.11.7 langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.46 langchain-text-splitters==0.0.1
Querying Llama3 70b using BedrockChat returns empty response if prompt is long
https://api.github.com/repos/langchain-ai/langchain/issues/21037/comments
1
2024-04-29T17:55:01Z
2024-05-13T10:26:14Z
https://github.com/langchain-ai/langchain/issues/21037
2,269,620,697
21,037
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` vectorstore = WeaviateVectorStore( self.client, index_name=self.index_name, embedding=self.embeddings, text_key=self.text_key, by_text=False, ) # Create the record manager namespace = f"weaviate/{self.index_name}" record_manager = SQLRecordManager( namespace, db_url=self.db_url ) # Add the summaries to the docs list if summaries: docs.extend(summaries) record_manager.create_schema() # Index the documents to Weaviate with the record manager result_dict = index( docs, record_manager, vectorstore, cleanup="incremental", source_id_key="source", ) ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description When indexing a list of documents utilizing the record manager in incremental deletion mode, with each document assigned a unique identifier (UUID) as the source, I encounter an unexpected behavior. The record manager deletes and re-indexes a subset of documents even though there have been no changes to those documents. Upon rerunning the same code with identical documents, the output is `{'num_added': 80, 'num_updated': 0, 'num_skipped': 525, 'num_deleted': 80}`. Furthermore, I am using a recursive text splitter to segment the documents; also I am generating a summary for each document and I change the summary metadata to add the source of the original document so it is considered as a chunk of the original document. Finally, please note that I tried the same code on different sets of documents and the issue is not consistent. ### System Info System Information ------------------ > OS: Linux > OS Version: #29~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Thu Apr 4 14:39:20 UTC 2 > Python Version: 3.11.6 (main, Oct 4 2023, 18:31:23) [GCC 11.4.0] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.12 > langchain_community: 0.0.28 > langsmith: 0.1.31 > langchain_openai: 0.1.4 > langchain_text_splitters: 0.0.1 > langchain_weaviate: 0.0.1rc5 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
Record manager considers some of the documents as updated while they are not changed
https://api.github.com/repos/langchain-ai/langchain/issues/21028/comments
9
2024-04-29T16:20:56Z
2024-05-08T12:25:06Z
https://github.com/langchain-ai/langchain/issues/21028
2,269,451,589
21,028
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code This is the code I execute, but without my db it will be hard to reproduce.... ```python from cx_Oracle import makedsn from langchain.sql_database import SQLDatabase dsn_tns = makedsn(host=host, port=port, service_name=service_name) connection_string = f"oracle+cx_oracle://{usr}:{pwd}@{dsn_tns}?encoding=UTF-8&nencoding=UTF-8" db = SQLDatabase.from_uri(connection_string, schema=schema, include_tables=include_tables) print("Dialect:", db.dialect) from langchain.agents import create_sql_agent from langchain.agents.agent_toolkits import SQLDatabaseToolkit toolkit = SQLDatabaseToolkit(db=db, llm=chat_client) agent_executor = create_sql_agent(llm=chat_client, toolkit=toolkit, agent_type="openai-tools", verbose=True, return_intermediate_steps=True) ``` ### Error Message and Stack Trace (if applicable) No error message, because no error is being raised. ### Description # Description When using LangChain for NL2SQL, there is a discrepancy between the displayed SQL in the intermediate steps and the actual SQL that is executed. The executed SQL seems to mishandle umlauts (ä, ö, ü), using escape sequences (e.g., \\u00fc for ü) instead of the actual umlaut characters. This results in incorrect query execution, as the database does not recognize the conditions specified due to encoding errors. # Expected Behavior The SQL query should be executed exactly as shown in the intermediate steps, preserving the correct encoding for special characters such as umlauts. The conditions in the WHERE clause should correctly filter the records based on the given values. # Actual Behavior The executed SQL does not correctly handle the encoding of umlauts, leading to no matches in conditions that involve these characters, even when appropriate records exist in the database. # Output of invoke() ```python Invoking: `sql_db_query_checker` with `{'query': "SELECT COUNT(*) AS open_cancellation_orders FROM auftraege WHERE type = 'K\\u00fcndigung erfassen' AND status = 'offener K\\u00fcndigungsvorgang'"}` ``sql SELECT COUNT(*) AS open_cancellation_orders FROM auftraege WHERE type = 'Kündigung erfassen' AND status = 'offener Kündigungsvorgang' `` Invoking: `sql_db_query` with `{'query': "SELECT COUNT(*) AS open_cancellation_orders FROM auftraege WHERE type = 'K\\u00fcndigung erfassen' AND status = 'offener K\\u00fcndigungsvorgang'"}` [(0,)]Es gibt derzeit keine offenen Kündigungsaufträge in der Datenbank. ``` The SQL statement in the middle is correct (including the special characters), this is what **should** be executed. And if I execute this SQL statement in another tool, I get the correct result. However, the SQL statement at the top and the bottom (with wrong speacial character representation) seems to be what is **actually** executed. Since the value in the where-clause is wrong, the query does not return any row, which is wrong. What surprises me is that even within the same output two different versions of the SQL statement are displayed, one correct and one incorrect, and that unfortunately the wrong one is executed. ### System Info System Information ------------------ > OS: Windows > OS Version: 10.0.19045 > Python Version: 3.11.9 (tags/v3.11.9:de54cf5, Apr 2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)] Package Information ------------------- > langchain_core: 0.1.42 > langchain: 0.1.16 > langchain_community: 0.0.32 > langsmith: 0.1.31 > langchain_openai: 0.1.3 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
Encoding Issue: Incorrect Umlaut (Speacial Character) Handling in SQL Execution Leading to Wrong Query Results
https://api.github.com/repos/langchain-ai/langchain/issues/21018/comments
0
2024-04-29T12:48:44Z
2024-08-05T16:09:21Z
https://github.com/langchain-ai/langchain/issues/21018
2,268,958,064
21,018
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code * It works properly when accessed using curl. ```bash ! curl http://127.0.0.1:3000/v1/embeddings \ -H "Content-Type: application/json" \ -H "Authorization: Bearer Aw31nIfa2ONFI5dBeD59bFfB04194917fF1A15f5286F3" \ -d '{ \ "input": "Your text string goes here", \ "model": "bge-small-zh" \ }' ``` * I can also be properly called using the openai API ```python from openai import OpenAI client = OpenAI(api_key="Aw31nIfa2ONFI5dBeD59bFfB04194917fF1A15f5286F3", base_url = "http://127.0.0.1:3000/v1") def get_embedding(text_or_tokens, model="bge-small-zh"): return client.embeddings.create(input=text_or_tokens, model=model).data[0].embedding ``` * but,I am unable to get langchain's OpenAIEmbeddings to work ```python from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings( model="bge-small-zh", openai_api_base="http://127.0.0.1:3000/v1", openai_api_key="Aw31nIfa2ONFI5dBeD59bFfB04194917fF1A15f5286F3" ) ``` ### Error Message and Stack Trace (if applicable) --------------------------------------------------------------------------- InternalServerError Traceback (most recent call last) Cell In[7], line 1 ----> 1 query_result = embeddings.embed_query("haha") File /data/miniconda3/lib/python3.12/site-packages/langchain_openai/embeddings/base.py:573, in OpenAIEmbeddings.embed_query(self, text) 564 def embed_query(self, text: str) -> List[float]: 565 """Call out to OpenAI's embedding endpoint for embedding query text. 566 567 Args: (...) 571 Embedding for the text. 572 """ --> 573 return self.embed_documents([text])[0] File /data/miniconda3/lib/python3.12/site-packages/langchain_openai/embeddings/base.py:532, in OpenAIEmbeddings.embed_documents(self, texts, chunk_size) 529 # NOTE: to keep things simple, we assume the list may contain texts longer 530 # than the maximum context and use length-safe embedding function. 531 engine = cast(str, self.deployment) --> 532 return self._get_len_safe_embeddings(texts, engine=engine) File /data/miniconda3/lib/python3.12/site-packages/langchain_openai/embeddings/base.py:336, in OpenAIEmbeddings._get_len_safe_embeddings(self, texts, engine, chunk_size) 334 batched_embeddings: List[List[float]] = [] 335 for i in _iter: --> 336 response = self.client.create( 337 input=tokens[i : i + _chunk_size], **self._invocation_params 338 ) 339 if not isinstance(response, dict): 340 response = response.model_dump() File /data/miniconda3/lib/python3.12/site-packages/openai/resources/embeddings.py:114, in Embeddings.create(self, input, model, dimensions, encoding_format, user, extra_headers, extra_query, extra_body, timeout) 108 embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] 109 base64.b64decode(data), dtype="float32" 110 ).tolist() 112 return obj --> 114 return self._post( 115 "/embeddings", 116 body=maybe_transform(params, embedding_create_params.EmbeddingCreateParams), 117 options=make_request_options( 118 extra_headers=extra_headers, 119 extra_query=extra_query, 120 extra_body=extra_body, 121 timeout=timeout, 122 post_parser=parser, 123 ), 124 cast_to=CreateEmbeddingResponse, 125 ) File /data/miniconda3/lib/python3.12/site-packages/openai/_base_client.py:1232, in SyncAPIClient.post(self, path, cast_to, body, options, files, stream, stream_cls) 1218 def post( 1219 self, 1220 path: str, (...) 1227 stream_cls: type[_StreamT] | None = None, 1228 ) -> ResponseT | _StreamT: 1229 opts = FinalRequestOptions.construct( 1230 method="post", url=path, json_data=body, files=to_httpx_files(files), **options 1231 ) -> 1232 return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) File /data/miniconda3/lib/python3.12/site-packages/openai/_base_client.py:921, in SyncAPIClient.request(self, cast_to, options, remaining_retries, stream, stream_cls) 912 def request( 913 self, 914 cast_to: Type[ResponseT], (...) 919 stream_cls: type[_StreamT] | None = None, 920 ) -> ResponseT | _StreamT: --> 921 return self._request( 922 cast_to=cast_to, 923 options=options, 924 stream=stream, 925 stream_cls=stream_cls, 926 remaining_retries=remaining_retries, 927 ) File /data/miniconda3/lib/python3.12/site-packages/openai/_base_client.py:997, in SyncAPIClient._request(self, cast_to, options, remaining_retries, stream, stream_cls) 995 if retries > 0 and self._should_retry(err.response): 996 err.response.close() --> 997 return self._retry_request( 998 options, 999 cast_to, 1000 retries, 1001 err.response.headers, 1002 stream=stream, 1003 stream_cls=stream_cls, 1004 ) 1006 # If the response is streamed then we need to explicitly read the response 1007 # to completion before attempting to access the response text. 1008 if not err.response.is_closed: File /data/miniconda3/lib/python3.12/site-packages/openai/_base_client.py:1045, in SyncAPIClient._retry_request(self, options, cast_to, remaining_retries, response_headers, stream, stream_cls) 1041 # In a synchronous context we are blocking the entire thread. Up to the library user to run the client in a 1042 # different thread if necessary. 1043 time.sleep(timeout) -> 1045 return self._request( 1046 options=options, 1047 cast_to=cast_to, 1048 remaining_retries=remaining, 1049 stream=stream, 1050 stream_cls=stream_cls, 1051 ) File /data/miniconda3/lib/python3.12/site-packages/openai/_base_client.py:997, in SyncAPIClient._request(self, cast_to, options, remaining_retries, stream, stream_cls) 995 if retries > 0 and self._should_retry(err.response): 996 err.response.close() --> 997 return self._retry_request( 998 options, 999 cast_to, 1000 retries, 1001 err.response.headers, 1002 stream=stream, 1003 stream_cls=stream_cls, 1004 ) 1006 # If the response is streamed then we need to explicitly read the response 1007 # to completion before attempting to access the response text. 1008 if not err.response.is_closed: File /data/miniconda3/lib/python3.12/site-packages/openai/_base_client.py:1045, in SyncAPIClient._retry_request(self, options, cast_to, remaining_retries, response_headers, stream, stream_cls) 1041 # In a synchronous context we are blocking the entire thread. Up to the library user to run the client in a 1042 # different thread if necessary. 1043 time.sleep(timeout) -> 1045 return self._request( 1046 options=options, 1047 cast_to=cast_to, 1048 remaining_retries=remaining, 1049 stream=stream, 1050 stream_cls=stream_cls, 1051 ) File /data/miniconda3/lib/python3.12/site-packages/openai/_base_client.py:1012, in SyncAPIClient._request(self, cast_to, options, remaining_retries, stream, stream_cls) 1009 err.response.read() 1011 log.debug("Re-raising status error") -> 1012 raise self._make_status_error_from_response(err.response) from None 1014 return self._process_response( 1015 cast_to=cast_to, 1016 options=options, (...) 1019 stream_cls=stream_cls, 1020 ) InternalServerError: Error code: 500 - {'error': {'message': 'bad response status code 500 (request id: 20240429183824796230302KI7yGPut)', 'type': 'upstream_error', 'param': '500', 'code': 'bad_response_status_code'}} ### Description I would like langchain's OpenAIEmbeddings to work properly, just like the openai API ### System Info DEPRECATION: Loading egg at /data/miniconda3/lib/python3.12/site-packages/sacremoses-0.0.43-py3.8.egg is deprecated. pip 24.3 will enforce this behaviour change. A possible replacement is to use pip for package installation.. Discussion can be found at https://github.com/pypa/pip/issues/12330 DEPRECATION: Loading egg at /data/miniconda3/lib/python3.12/site-packages/huggingface_hub-0.22.2-py3.8.egg is deprecated. pip 24.3 will enforce this behaviour change. A possible replacement is to use pip for package installation.. Discussion can be found at https://github.com/pypa/pip/issues/12330 langchain @ file:///home/conda/feedstock_root/build_artifacts/langchain_1712896599223/work langchain-community @ file:///home/conda/feedstock_root/build_artifacts/langchain-community_1713569638904/work langchain-core==0.1.46 langchain-openai==0.1.4 langchain-text-splitters @ file:///home/conda/feedstock_root/build_artifacts/langchain-text-splitters_1709389732771/work
When I use langchain's OpenAIEmbeddings to access my deployed like openai service, it's not working properly
https://api.github.com/repos/langchain-ai/langchain/issues/21015/comments
0
2024-04-29T10:52:26Z
2024-08-05T16:09:16Z
https://github.com/langchain-ai/langchain/issues/21015
2,268,709,371
21,015
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` vectorstore = FAISS.load_local(f"./faiss_index", load_embeddings(), allow_dangerous_deserialization=True) store = LocalFileStore(root_path=f"./store") store = create_kv_docstore(store) retriever = ParentDocumentRetriever( vectorstore=vectorstore, docstore=store, child_splitter=child_splitter, parent_splitter=parent_splitter, search_kwargs={"k": 5} ) rag_chain_from_docs = ( RunnablePassthrough.assign(context=(lambda x: format_docs(x["context"]))) | prompt | llm | StrOutputParser() ) rag_chain_with_source = RunnableParallel( {"context": retriever, "question": RunnablePassthrough()} # compression_retriever ).assign(answer=rag_chain_from_docs) llm_response = rag_chain_with_source.invoke(query) print(llm_response ) ``` The above is the code for me to load the local vectorstore and docstore and build a retriever. Using this code to query the query cannot find any information, and the large language model only answers based on its own abilities without receiving any chunks from the knowledge base. ### Error Message and Stack Trace (if applicable) _No response_ ### Description The above is the code for me to load the local vectorstore and docstore and build a retriever. Using this code to query the query cannot find any information, and the large language model only answers based on its own abilities without receiving any chunks from the knowledge base. ### System Info python==3.10 langchain 0.1.16 langchain-community 0.0.34 langchain-core 0.1.46 langchain-openai 0.1.4 langchain-text-splitters 0.0.1 langchainhub 0.1.15 langdetect 1.0.9 langsmith 0.1.33
How to Load vectorstore and store Locally and Build a retriever for RAG
https://api.github.com/repos/langchain-ai/langchain/issues/21012/comments
0
2024-04-29T09:20:10Z
2024-04-29T16:50:07Z
https://github.com/langchain-ai/langchain/issues/21012
2,268,525,583
21,012
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python import httpx from langchain_core.output_parsers import StrOutputParser from langchain_mistralai import ChatMistralAI prompt = PromptTemplate(input_variables=["alpha", "beta"], template=("""lorem ipsum sit amet dolor: '{alpha}', generate additional lorem ipsum {beta} times. For example: if there are alpha lorem ipsum, the final lorem ipsum must be beta. Output: """)) chain = ( prompt | ChatMistralAI(temperature=0, model="mixtral-8x7b-instruct-v01", endpoint='https://some-openai-compatible-endpoint.com/v1', api_key="whatever", client=httpx.Client(verify=False), max_tokens=8000, safe_mode=True, streaming=True) | StrOutputParser() | (lambda x: x.split("\n")) ) alpha = "lorem ipsum" beta = 4 output = chain.invoke({"alpha": alpha, "beta": beta}) output ``` ### Error Message and Stack Trace (if applicable) ``` { "name": "ConnectError", "message": "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain (_ssl.c:1006)", "stack": "--------------------------------------------------------------------------- ConnectError Traceback (most recent call last) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_transports\\default.py:69, in map_httpcore_exceptions() 68 try: ---> 69 yield 70 except Exception as exc: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_transports\\default.py:233, in HTTPTransport.handle_request(self, request) 232 with map_httpcore_exceptions(): --> 233 resp = self._pool.handle_request(req) 235 assert isinstance(resp.stream, typing.Iterable) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpcore\\_sync\\connection_pool.py:216, in ConnectionPool.handle_request(self, request) 215 self._close_connections(closing) --> 216 raise exc from None 218 # Return the response. Note that in this case we still have to manage 219 # the point at which the response is closed. File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpcore\\_sync\\connection_pool.py:196, in ConnectionPool.handle_request(self, request) 194 try: 195 # Send the request on the assigned connection. --> 196 response = connection.handle_request( 197 pool_request.request 198 ) 199 except ConnectionNotAvailable: 200 # In some cases a connection may initially be available to 201 # handle a request, but then become unavailable. 202 # 203 # In this case we clear the connection and try again. File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpcore\\_sync\\connection.py:99, in HTTPConnection.handle_request(self, request) 98 self._connect_failed = True ---> 99 raise exc 101 return self._connection.handle_request(request) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpcore\\_sync\\connection.py:76, in HTTPConnection.handle_request(self, request) 75 if self._connection is None: ---> 76 stream = self._connect(request) 78 ssl_object = stream.get_extra_info(\"ssl_object\") File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpcore\\_sync\\connection.py:154, in HTTPConnection._connect(self, request) 153 with Trace(\"start_tls\", logger, request, kwargs) as trace: --> 154 stream = stream.start_tls(**kwargs) 155 trace.return_value = stream File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpcore\\_backends\\sync.py:152, in SyncStream.start_tls(self, ssl_context, server_hostname, timeout) 148 exc_map: ExceptionMapping = { 149 socket.timeout: ConnectTimeout, 150 OSError: ConnectError, 151 } --> 152 with map_exceptions(exc_map): 153 try: File ~\\scoop\\persist\\rye\\py\\cpython@3.11.8\\Lib\\contextlib.py:158, in _GeneratorContextManager.__exit__(self, typ, value, traceback) 157 try: --> 158 self.gen.throw(typ, value, traceback) 159 except StopIteration as exc: 160 # Suppress StopIteration *unless* it's the same exception that 161 # was passed to throw(). This prevents a StopIteration 162 # raised inside the \"with\" statement from being suppressed. File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpcore\\_exceptions.py:14, in map_exceptions(map) 13 if isinstance(exc, from_exc): ---> 14 raise to_exc(exc) from exc 15 raise ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain (_ssl.c:1006) The above exception was the direct cause of the following exception: ConnectError Traceback (most recent call last) Cell In[7], line 3 1 alpha = \"lorem ipsum\" 2 beta = 4 ----> 3 output = chain.invoke({\"alpha\": alpha, \"beta\": beta}) 4 output File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\runnables\\base.py:2499, in RunnableSequence.invoke(self, input, config) 2497 try: 2498 for i, step in enumerate(self.steps): -> 2499 input = step.invoke( 2500 input, 2501 # mark each step as a child run 2502 patch_config( 2503 config, callbacks=run_manager.get_child(f\"seq:step:{i+1}\") 2504 ), 2505 ) 2506 # finish the root run 2507 except BaseException as e: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:158, in BaseChatModel.invoke(self, input, config, stop, **kwargs) 147 def invoke( 148 self, 149 input: LanguageModelInput, (...) 153 **kwargs: Any, 154 ) -> BaseMessage: 155 config = ensure_config(config) 156 return cast( 157 ChatGeneration, --> 158 self.generate_prompt( 159 [self._convert_input(input)], 160 stop=stop, 161 callbacks=config.get(\"callbacks\"), 162 tags=config.get(\"tags\"), 163 metadata=config.get(\"metadata\"), 164 run_name=config.get(\"run_name\"), 165 run_id=config.pop(\"run_id\", None), 166 **kwargs, 167 ).generations[0][0], 168 ).message File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:560, in BaseChatModel.generate_prompt(self, prompts, stop, callbacks, **kwargs) 552 def generate_prompt( 553 self, 554 prompts: List[PromptValue], (...) 557 **kwargs: Any, 558 ) -> LLMResult: 559 prompt_messages = [p.to_messages() for p in prompts] --> 560 return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:421, in BaseChatModel.generate(self, messages, stop, callbacks, tags, metadata, run_name, run_id, **kwargs) 419 if run_managers: 420 run_managers[i].on_llm_error(e, response=LLMResult(generations=[])) --> 421 raise e 422 flattened_outputs = [ 423 LLMResult(generations=[res.generations], llm_output=res.llm_output) # type: ignore[list-item] 424 for res in results 425 ] 426 llm_output = self._combine_llm_outputs([res.llm_output for res in results]) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:411, in BaseChatModel.generate(self, messages, stop, callbacks, tags, metadata, run_name, run_id, **kwargs) 408 for i, m in enumerate(messages): 409 try: 410 results.append( --> 411 self._generate_with_cache( 412 m, 413 stop=stop, 414 run_manager=run_managers[i] if run_managers else None, 415 **kwargs, 416 ) 417 ) 418 except BaseException as e: 419 if run_managers: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:632, in BaseChatModel._generate_with_cache(self, messages, stop, run_manager, **kwargs) 630 else: 631 if inspect.signature(self._generate).parameters.get(\"run_manager\"): --> 632 result = self._generate( 633 messages, stop=stop, run_manager=run_manager, **kwargs 634 ) 635 else: 636 result = self._generate(messages, stop=stop, **kwargs) File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_mistralai\\chat_models.py:452, in ChatMistralAI._generate(self, messages, stop, run_manager, stream, **kwargs) 448 if should_stream: 449 stream_iter = self._stream( 450 messages, stop=stop, run_manager=run_manager, **kwargs 451 ) --> 452 return generate_from_stream(stream_iter) 454 message_dicts, params = self._create_message_dicts(messages, stop) 455 params = {**params, **kwargs} File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_core\\language_models\\chat_models.py:67, in generate_from_stream(stream) 64 \"\"\"Generate from a stream.\"\"\" 66 generation: Optional[ChatGenerationChunk] = None ---> 67 for chunk in stream: 68 if generation is None: 69 generation = chunk File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_mistralai\\chat_models.py:499, in ChatMistralAI._stream(self, messages, stop, run_manager, **kwargs) 496 params = {**params, **kwargs, \"stream\": True} 498 default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk --> 499 for chunk in self.completion_with_retry( 500 messages=message_dicts, run_manager=run_manager, **params 501 ): 502 if len(chunk[\"choices\"]) == 0: 503 continue File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\langchain_mistralai\\chat_models.py:366, in ChatMistralAI.completion_with_retry.<locals>._completion_with_retry.<locals>.iter_sse() 365 def iter_sse() -> Iterator[Dict]: --> 366 with connect_sse( 367 self.client, \"POST\", \"/chat/completions\", json=kwargs 368 ) as event_source: 369 _raise_on_error(event_source.response) 370 for event in event_source.iter_sse(): File ~\\scoop\\persist\\rye\\py\\cpython@3.11.8\\Lib\\contextlib.py:137, in _GeneratorContextManager.__enter__(self) 135 del self.args, self.kwds, self.func 136 try: --> 137 return next(self.gen) 138 except StopIteration: 139 raise RuntimeError(\"generator didn't yield\") from None File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx_sse\\_api.py:54, in connect_sse(client, method, url, **kwargs) 51 headers[\"Accept\"] = \"text/event-stream\" 52 headers[\"Cache-Control\"] = \"no-store\" ---> 54 with client.stream(method, url, headers=headers, **kwargs) as response: 55 yield EventSource(response) File ~\\scoop\\persist\\rye\\py\\cpython@3.11.8\\Lib\\contextlib.py:137, in _GeneratorContextManager.__enter__(self) 135 del self.args, self.kwds, self.func 136 try: --> 137 return next(self.gen) 138 except StopIteration: 139 raise RuntimeError(\"generator didn't yield\") from None File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:870, in Client.stream(self, method, url, content, data, files, json, params, headers, cookies, auth, follow_redirects, timeout, extensions) 847 \"\"\" 848 Alternative to `httpx.request()` that streams the response body 849 instead of loading it into memory at once. (...) 855 [0]: /quickstart#streaming-responses 856 \"\"\" 857 request = self.build_request( 858 method=method, 859 url=url, (...) 868 extensions=extensions, 869 ) --> 870 response = self.send( 871 request=request, 872 auth=auth, 873 follow_redirects=follow_redirects, 874 stream=True, 875 ) 876 try: 877 yield response File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:914, in Client.send(self, request, stream, auth, follow_redirects) 906 follow_redirects = ( 907 self.follow_redirects 908 if isinstance(follow_redirects, UseClientDefault) 909 else follow_redirects 910 ) 912 auth = self._build_request_auth(request, auth) --> 914 response = self._send_handling_auth( 915 request, 916 auth=auth, 917 follow_redirects=follow_redirects, 918 history=[], 919 ) 920 try: 921 if not stream: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:942, in Client._send_handling_auth(self, request, auth, follow_redirects, history) 939 request = next(auth_flow) 941 while True: --> 942 response = self._send_handling_redirects( 943 request, 944 follow_redirects=follow_redirects, 945 history=history, 946 ) 947 try: 948 try: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:979, in Client._send_handling_redirects(self, request, follow_redirects, history) 976 for hook in self._event_hooks[\"request\"]: 977 hook(request) --> 979 response = self._send_single_request(request) 980 try: 981 for hook in self._event_hooks[\"response\"]: File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_client.py:1015, in Client._send_single_request(self, request) 1010 raise RuntimeError( 1011 \"Attempted to send an async request with a sync Client instance.\" 1012 ) 1014 with request_context(request=request): -> 1015 response = transport.handle_request(request) 1017 assert isinstance(response.stream, SyncByteStream) 1019 response.request = request File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_transports\\default.py:232, in HTTPTransport.handle_request(self, request) 218 assert isinstance(request.stream, SyncByteStream) 220 req = httpcore.Request( 221 method=request.method, 222 url=httpcore.URL( (...) 230 extensions=request.extensions, 231 ) --> 232 with map_httpcore_exceptions(): 233 resp = self._pool.handle_request(req) 235 assert isinstance(resp.stream, typing.Iterable) File ~\\scoop\\persist\\rye\\py\\cpython@3.11.8\\Lib\\contextlib.py:158, in _GeneratorContextManager.__exit__(self, typ, value, traceback) 156 value = typ() 157 try: --> 158 self.gen.throw(typ, value, traceback) 159 except StopIteration as exc: 160 # Suppress StopIteration *unless* it's the same exception that 161 # was passed to throw(). This prevents a StopIteration 162 # raised inside the \"with\" statement from being suppressed. 163 return exc is not value File c:\\Users\\Sachin_Bhat\\Documents\\dev\\package\\.venv\\Lib\\site-packages\\httpx\\_transports\\default.py:86, in map_httpcore_exceptions() 83 raise 85 message = str(exc) ---> 86 raise mapped_exc(message) from exc ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain (_ssl.c:1006)" } ``` ### Description I just need the response as the output but instead even after passing the client I still see SSL verification issues. I had a look at langchain-openai and the ChatOpenAI defines two parameters. http_client and http_async_client apart from client and async_client: ```python client: Any = Field(default=None, exclude=True) #: :meta private: async_client: Any = Field(default=None, exclude=True) #: :meta private: http_client: Union[Any, None] = None """Optional httpx.Client. Only used for sync invocations. Must specify http_async_client as well if you'd like a custom client for async invocations. """ http_async_client: Union[Any, None] = None """Optional httpx.AsyncClient. Only used for async invocations. Must specify http_client as well if you'd like a custom client for sync invocations.""" ``` ### System Info System Information ------------------ > OS: Windows > OS Version: 10.0.22621 > Python Version: 3.11.8 (main, Feb 25 2024, 03:41:44) [MSC v.1929 64 bit (AMD64)] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.51 > langchain_mistralai: 0.1.4 > langchain_openai: 0.1.4 > langchain_postgres: 0.0.3 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 > langgraph: 0.0.32 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langserve
langchain-mistralai: client attribute not recognized
https://api.github.com/repos/langchain-ai/langchain/issues/21007/comments
2
2024-04-29T07:37:39Z
2024-04-29T23:30:10Z
https://github.com/langchain-ai/langchain/issues/21007
2,268,335,960
21,007
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code No particular code. ### Error Message and Stack Trace (if applicable) _No response_ ### Description copy.deepcopy is known to be extremely slow. When we create complex agents in langgraph, it slows things down a lot. A solution is to define a function to copy only what necessary. https://github.com/langchain-ai/langchain/blob/804390ba4bcc306b90cb6d75b7f01a4231ab6463/libs/core/langchain_core/tracers/log_stream.py#L105 https://github.com/langchain-ai/langchain/blob/804390ba4bcc306b90cb6d75b7f01a4231ab6463/libs/core/langchain_core/tracers/log_stream.py#L590 ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.2.0: Wed Nov 15 21:53:34 PST 2023; root:xnu-10002.61.3~2/RELEASE_ARM64_T8103 > Python Version: 3.11.2 (main, Feb 21 2024, 12:24:36) [Clang 15.0.0 (clang-1500.1.0.2.5)] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.22 > langchain_openai: 0.0.6 > langchain_text_splitters: 0.0.1 > langgraph: 0.0.39 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langserve
deepcopy is extremely slow. Can we define a copy function?
https://api.github.com/repos/langchain-ai/langchain/issues/21001/comments
6
2024-04-29T06:16:41Z
2024-05-27T05:17:12Z
https://github.com/langchain-ai/langchain/issues/21001
2,268,212,827
21,001
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_pinecone import PineconeVectorStore from langchain_community.embeddings.huggingface import HuggingFaceEmbeddings index_name = "langchain-test-index" embeddings = HuggingFaceEmbeddings() docsearch = PineconeVectorStore(index_name, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query) print(docs[0].page_content) ``` ### Error Message and Stack Trace (if applicable) ```python --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) [<ipython-input-9-87c0f7711524>](https://localhost:8080/#) in <cell line: 2>() 1 query = "What did the president say about Ketanji Brown Jackson" ----> 2 docs = docsearch.similarity_search(query) 3 print(docs[0].page_content) 2 frames [/usr/local/lib/python3.10/dist-packages/langchain_pinecone/vectorstores.py](https://localhost:8080/#) in similarity_search_by_vector_with_score(self, embedding, k, filter, namespace) 207 namespace = self._namespace 208 docs = [] --> 209 results = self._index.query( 210 vector=embedding, 211 top_k=k, AttributeError: 'str' object has no attribute 'query' ``` ### Description I was just looking through the documentation in pinecone section, the loading part work just fine but the retrieving using any function give the error above, but with the pinecone-client it works fine. To reproduce the error, I used the code from the documentation. ### System Info langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.46 langchain-openai==0.1.4 langchain-pinecone==0.1.0 langchain-text-splitters==0.0.1
langchain-pinecone retreive functions error : 'str' object has no attribute 'query'
https://api.github.com/repos/langchain-ai/langchain/issues/20993/comments
3
2024-04-28T16:30:01Z
2024-04-29T19:25:31Z
https://github.com/langchain-ai/langchain/issues/20993
2,267,669,257
20,993
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from langchain_openai import OpenAI ### Error Message and Stack Trace (if applicable) from langchain_openai import OpenAI 2024-04-28T15:21:34.177321153Z File "/workspace/venv/lib/python3.10/site-packages/langchain_openai/__init__.py", line 1, in <module> 2024-04-28T15:21:34.177325586Z from langchain_openai.chat_models import ( 2024-04-28T15:21:34.177330011Z File "/workspace/venv/lib/python3.10/site-packages/langchain_openai/chat_models/__init__.py", line 1, in <module> 2024-04-28T15:21:34.177335117Z from langchain_openai.chat_models.azure import AzureChatOpenAI 2024-04-28T15:21:34.177339632Z File "/workspace/venv/lib/python3.10/site-packages/langchain_openai/chat_models/azure.py", line 13, in <module> 2024-04-28T15:21:34.177344081Z from langchain_openai.chat_models.base import ChatOpenAI 2024-04-28T15:21:34.177349992Z File "/workspace/venv/lib/python3.10/site-packages/langchain_openai/chat_models/base.py", line 42, in <module> 2024-04-28T15:21:34.177354420Z from langchain_core.messages import ( 2024-04-28T15:21:34.177358965Z ImportError: cannot import name 'InvalidToolCall' from 'langchain_core.messages' (/workspace/venv/lib/python3.10/site-packages/langchain_core/messages/__init__.py) ### Description I ma trying to import Openai from langchain_openai . ### System Info langchain latest version
ImportError: cannot import name 'InvalidToolCall' from 'langchain_core.messages' (/workspace/venv/lib/python3.10/site-packages/langchain_core/messages/__init__.py
https://api.github.com/repos/langchain-ai/langchain/issues/20991/comments
16
2024-04-28T15:26:34Z
2024-08-07T01:19:21Z
https://github.com/langchain-ai/langchain/issues/20991
2,267,635,125
20,991
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code no at the moment ### Error Message and Stack Trace (if applicable) _No response_ ### Description In langraph we use chain.ainvoke() in inner node and app.astream_events() for the whole graph app. But we found out that the chain.ainvoke() output streaming tokens. We I dived into the code, and found maybe because of the following code: https://github.com/langchain-ai/langchain/blob/804390ba4bcc306b90cb6d75b7f01a4231ab6463/libs/core/langchain_core/language_models/chat_models.py#L684-L701 `type(self)._astream` is `ChatOpenAI._astream` `kwargs` is a empty {}, which dose not have `stream` key from params. The langgraph app have a `LogStreamCallbackHandler` in the run_manager.handlers. So the `if statement` is `True` and the code generated streaming output which is not expected. May be you should add key 'stream' to `kwargs` from `params`. And I have tried it solved my problem. ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.2.0: Wed Nov 15 21:53:34 PST 2023; root:xnu-10002.61.3~2/RELEASE_ARM64_T8103 > Python Version: 3.11.2 (main, Feb 21 2024, 12:24:36) [Clang 15.0.0 (clang-1500.1.0.2.5)] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.22 > langchain_openai: 0.0.6 > langchain_text_splitters: 0.0.1 > langgraph: 0.0.39 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langserve
chain.ainvoke() will result in streaming output
https://api.github.com/repos/langchain-ai/langchain/issues/20980/comments
5
2024-04-28T06:41:22Z
2024-07-04T04:19:09Z
https://github.com/langchain-ai/langchain/issues/20980
2,267,382,986
20,980
[ "langchain-ai", "langchain" ]
### Checklist - [X] I added a very descriptive title to this issue. - [X] I included a link to the documentation page I am referring to (if applicable). ### Issue with current documentation: The documentation here: https://python.langchain.com/docs/integrations/llms/huggingface_endpoint/ has incorrect import code (not sure if recent change caused it to not work). Currently states: from langchain_community.llms import HuggingFaceEndpoint Correct: from langchain_community.llms**.huggingface_endpoint** import HuggingFaceEndpoint Found while trying to follow the documentation ### Idea or request for content: A minor change needs to be made to first code block on page
DOC: HuggingFaceEndpoint documentation incorrect for importing
https://api.github.com/repos/langchain-ai/langchain/issues/20977/comments
1
2024-04-27T23:04:39Z
2024-05-12T13:14:39Z
https://github.com/langchain-ai/langchain/issues/20977
2,267,228,854
20,977
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```bash cd langchain poetry install --with lint,docs --no-root make clean make api_docs_build ``` ### Error Message and Stack Trace (if applicable) Running `make api_docs_build` as is results in this error ```bash poetry run python docs/api_reference/create_api_rst.py Starting to build API reference files. Building package: community Building package: text-splitters Building package: core Building package: experimental Building package: standard-tests pyproject.toml not found in /home/karim/Projects/langchain/libs/partners/standard-tests. You are either attempting to build a directory which is not a package or the package is missing a pyproject.toml file which should be added.Aborting the build. make: *** [Makefile:37: api_docs_build] Error 1 ``` Excluding `standard-tests` and running the same command results in this error: ```bash API reference files built. cd docs/api_reference && poetry run make html Running Sphinx v4.5.0 Extension error: Could not import extension sphinxcontrib.autodoc_pydantic (exception: `BaseSettings` has been moved to the `pydantic-settings` package. See https://docs.pydantic.dev/2.6/migration/#basesettings-has-moved-to-pydantic-settings for more details. For further information visit https://errors.pydantic.dev/2.6/u/import-error) make[1]: *** [html] Error 2 make: *** [api_docs_build] Error 2 ``` ### Description * When I run `make api_docs_build` I get an error regarding `lib/standard-tests` folder. This is likely causing the first problem. * When I exclude `lib/standard-tests` folder, I get a migration error from pydantic * Adding `standard-tests` to the exclusions list and upgrading `autodoc_pydantic` to `1.9.0` eliminates both issues ### System Info ```bash pip freeze | grep langchain -e git+ssh://git@github.com/langchain-ai/langchain@f1a0614f3ba896b3168f0faad79ffb97df91ba6e#egg=langchain&subdirectory=libs/langchain -e git+ssh://git@github.com/langchain-ai/langchain@f1a0614f3ba896b3168f0faad79ffb97df91ba6e#egg=langchain_community&subdirectory=libs/community -e git+ssh://git@github.com/langchain-ai/langchain@f1a0614f3ba896b3168f0faad79ffb97df91ba6e#egg=langchain_core&subdirectory=libs/core -e git+ssh://git@github.com/langchain-ai/langchain@f1a0614f3ba896b3168f0faad79ffb97df91ba6e#egg=langchain_experimental&subdirectory=libs/experimental -e git+ssh://git@github.com/langchain-ai/langchain@f1a0614f3ba896b3168f0faad79ffb97df91ba6e#egg=langchain_openai&subdirectory=libs/partners/openai -e git+ssh://git@github.com/langchain-ai/langchain@f1a0614f3ba896b3168f0faad79ffb97df91ba6e#egg=langchain_text_splitters&subdirectory=libs/text-splitters ``` platform mac and wsl ```bash python --version Python 3.10.12 ```
[build] make api_docs_build fails - standard-tests being pulled into api_docs_build and olded version of autodoc_pydantic being used
https://api.github.com/repos/langchain-ai/langchain/issues/20972/comments
0
2024-04-27T19:44:08Z
2024-08-03T16:08:31Z
https://github.com/langchain-ai/langchain/issues/20972
2,267,160,246
20,972
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from dotenv import load_dotenv import duckdb from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import DuckDB from langchain_core.documents import Document from time import time load_dotenv() TABLE_NAME = "embeddings" documents = [Document(page_content="Jacek is the best software engineer in the world", metadata={"id": "1"})] db_conn = duckdb.connect('./test.DUCKDB') try: start_exists = time() print("Checking table exists") table = db_conn.table(TABLE_NAME) table.show() vector_store = DuckDB(connection=db_conn, table_name=TABLE_NAME, embedding=OpenAIEmbeddings(), vector_key="embedding") print(f"Table exists check took {time() - start_exists} seconds") except Exception as e: start_not_exists = time() print(f"Table does not exist, create it from documents") vector_store = DuckDB.from_documents(documents, connection=db_conn, table_name=TABLE_NAME, embedding=OpenAIEmbeddings(), vector_key="embedding") print(f"Table does not exist, took {time() - start_not_exists} seconds") start_search = time() query = "Who is the best software engineer in the world?" docs = vector_store.similarity_search(query) print(f"Search result: {docs}") print(f"Search took {time() - start_search} seconds") ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description I use DuckDB as vector store. When I execute similarity_search, I expect `distance` property is returned as a (metadata) part of result documents. I discussed this issue in DuckDB community and we agreed that it is a bug and it should be returned. I am going to fix it. ### System Info - Ubuntu 22.04 - python 3.10.12 - langchain==0.1.16 - openai==1.13.3 - langchain_openai==0.1.1 - duckdb==0.10.2
DuckDB: distance/similarity property not reported to documents returned by similarity_search
https://api.github.com/repos/langchain-ai/langchain/issues/20969/comments
0
2024-04-27T15:16:26Z
2024-05-24T22:17:53Z
https://github.com/langchain-ai/langchain/issues/20969
2,267,058,281
20,969
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_community.llms import Ollama llm = Ollama(model=params['model'],num_ctx=2048)#, num_predict=1100) with open("./prompt.txt", encoding="utf-8") as fd: doc_text=fd.read() result = llm(doc_text) print(result) ''' Setup prompt chains ''' from langchain.chains.mapreduce import MapReduceChain from langchain_text_splitters import CharacterTextSplitter, RecursiveCharacterTextSplitter from langchain.chains import ReduceDocumentsChain, MapReduceDocumentsChain # Map map_prompt = PromptTemplate.from_template(params['map_template']) map_chain = LLMChain(llm=llm, prompt=map_prompt) # Reduce reduce_prompt = PromptTemplate.from_template(params['reduce_template']) # Run chain reduce_chain = LLMChain(llm=llm, prompt=reduce_prompt) # Takes a list of documents, combines them into a single string, and passes this to an LLMChain combine_documents_chain = StuffDocumentsChain( llm_chain=reduce_chain, document_variable_name="doc_summaries" ) # Combines and iteravely reduces the mapped documents reduce_documents_chain = ReduceDocumentsChain( # This is final chain that is called. combine_documents_chain=combine_documents_chain, # If documents exceed context for `StuffDocumentsChain` collapse_documents_chain=combine_documents_chain, # The maximum number of tokens to group documents into. token_max=params['reduce_token_max'], ) # Combining documents by mapping a chain over them, then combining results map_reduce_chain = MapReduceDocumentsChain( # Map chain llm_chain=map_chain, # Reduce chain reduce_documents_chain=reduce_documents_chain, # The variable name in the llm_chain to put the documents in document_variable_name="docs", # Return the results of the map steps in the output return_intermediate_steps=True, ) print("Running map reduce summarisation...") result = map_reduce_chain.invoke(docs) ``` ### Error Message and Stack Trace (if applicable) Running map reduce summarisation... Token indices sequence length is longer than the specified maximum sequence length for this model (1993 > 1024). Running this sequence through the model will result in indexing errors ### Description I am running MapReduceDocumentsChain with Ollama and the "llama3" model. Llama3 has a context window of 8k tokens. Ollama is given the argument "num_ctx = 4096". However, the message produced indicates that the maximum sequence length being accepted is 1024. This must be happening with the ReduceDocumentsChain. Why is this the case? Any solutions? Thank you. ### System Info System Information ------------------ > OS: Windows > OS Version: 10.0.19045 > Python Version: 3.12.2 | packaged by Anaconda, Inc. | (main, Feb 27 2024, 17:28:07) [MSC v.1916 64 bit (AMD64)] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.43 > langchain_openai: 0.1.2 > langchain_text_splitters: 0.0.1
Llama3 context window is 8k but Langchain with Ollama shows "Token indices sequence length is longer than the specified maximum sequence length for this model (1916 > 1024). "
https://api.github.com/repos/langchain-ai/langchain/issues/20967/comments
1
2024-04-27T14:19:09Z
2024-05-16T15:55:55Z
https://github.com/langchain-ai/langchain/issues/20967
2,267,035,278
20,967
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from langchain.sql_database import SQLDatabase from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder,PromptTemplate from langchain.tools import BaseTool from langchain.tools.render import format_tool_to_openai_function from langchain.schema.runnable import Runnable,RunnableLambda,RunnableParallel from langchain.chat_models import ChatOpenAI from langchain.agents.format_scratchpad import format_to_openai_function_messages from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain.agents import AgentExecutor from pydantic import BaseModel, Field import os from secret_key import openapi_key from sqlalchemy import create_engine import constants from datetime import datetime import re from typing import Optional # os.environ['OPENAI_API_KEY'] = 'sk-xxxxxxxxxxxx' os.environ['OPENAI_API_KEY'] = openapi_key def chat5(question: str): # Define the SQL DML Chain Prompt Template SQL_DML_CHAIN_PROMPT = """You are an expert in SQLITE. Your main objective is to construct Data manipulation SQLITE query given the user question: {user_question}. You need to construct the Data manipulation SQLITE query for the following Database Schema: {table_info} Only Output the final SQL-Query and nothing else. SQL-Query:""" SQL_DML_CHAIN_PROMPT = """You are expert in MS SQL. Your main objective is to construct Data manipulation MS SQL query give the user question: {user_question}. You need to construct the Data manipulation SQLITE query for the following Database Schema: {table_info} Check user query for INSERT, UPDATE or DELETE operation, based on that perform the sql query. Wrapped column names: All column names should be wrapped in square brackets [] as delimiters. Use GETDATE() to get the current date and time instead of DATETIME('now'). Consider the column name carefully from the PAY_transaction_settingallow table where the modification is done. Take 'euid' in PAY_transaction_settingallow table from employee_details table which is 'employeeEuid' in employee_details table based on the matching 'employeeName' or 'employeeId' from employee_details table and stores it as 'euid' in the PAY_transaction_settingallow table. Similarly, to get the allowance ID ('alw_id') from the pay_mst_allowance table based on the matching allowance description ('alw_desc') or short name ('short_name'), check both 'alw_desc' and 'short_name'. Pay attention to the column names in user query and sql query. Perform JOIN operation to fetch euid and alw_id from respective tables not INNER JOIN. Selected table: Specify PAY_transaction_settingallow as the table to update. Employee and allowance selection: Use the WHERE clause to filter employees based on employeeName and allowances based on alw_desc. Date handling: 'createDate' should be the date on which the values are inserted, current date, it can not be NULL. 'effect_date' should be the start date of month. 'to_date' should be the end date of month. 'updatedDate' should be the date on which values are updated and it should be included only when UPDATE keywoed is used i query. UPDATE query should not change the 'createdDate' Currency: Assume the amount to be in rupees. If the users gives 'given by' in query enter that value in 'givenBy' column in PAY_transaction_settingallow table Modify the 'givenBy' column only when given by is specified by user, if not dont take givenBy column. Removed newlines: Write the query as a single string without newlines (\n). Ensure the query executes efficiently and without errors. If data or Values are already present in the table, dont again run the sql query. If no modifcation is made in table dont not display the message. If no rows are modifyed output its as "0 rows affected" Only Output the message after execution of SQL-Query If duplicate value is encountred with check_duplicate function Output the message like "The SQL query has been skipped due to duplicate data.". -- Replace DATETIME('now') with GETDATE() for SQL Server compatibility REPLACE(CAST('' AS VARCHAR(MAX)), 'DATETIME(''now'')', 'GETDATE()') SQL-Query: {user_question} """ # Define the prompt template prompt = PromptTemplate(template=SQL_DML_CHAIN_PROMPT, input_variables=['user_question', 'table_info']) from urllib.parse import quote_plus server_name = constants.server_name database_name = constants.database_name username = constants.username password = constants.password encoded_password = quote_plus(password) connection_uri = f"mssql+pyodbc://{username}:{encoded_password}@{server_name}/{database_name}?driver=ODBC+Driver+17+for+SQL+Server" engine = create_engine(connection_uri) model_name = "get-3.5-turbo-16k" # db = SQLDatabase(engine, view_support=True, include_tables=['HR_Testing']) # db = SQLDatabase(engine, view_support=True, include_tables=['EGV_emp_departments_ChatGPT']) db = SQLDatabase(engine, view_support=True, include_tables=['PAY_transaction_settingallow', 'PAY_mst_allowance','employee_details'],sample_rows_in_table_info=5) def check_duplicate(query: str, db: SQLDatabase) -> Optional[str]: """ Check for duplicate data before executing an INSERT query. Args: query (str): The SQL query to be checked. db (SQLDatabase): The SQLDatabase object. Returns: Optional[str]: The original query if no duplicate is found, or None if a duplicate is detected. """ # Define a regular expression pattern to match the INSERT statement pattern = r'INSERT INTO (\w+) \((.*?)\) VALUES \((.*?)\)' # Attempt to match the pattern in the query match = re.match(pattern, query) # Check if the pattern matched successfully if match: # Extract table name, columns, and values from the matched groups table_name = match.group(1) columns = [col.strip() for col in match.group(2).split(',')] values = [val.strip() for val in match.group(3).split(',')] # Check if the table name matches the expected table name (e.g., 'PAY_transaction_settingallow') if table_name != 'PAY_transaction_settingallow': # If the table name doesn't match, return the original query return query # Extract the values of euid, alw_id, amount, and effect_date from the values list euid_index = columns.index('euid') alw_id_index = columns.index('alw_id') amount_index = columns.index('amount') # effect_date_index = columns.index('effect_date') euid = values[euid_index] alw_id = values[alw_id_index] amount = values[amount_index] # effect_date = values[effect_date_index] # Construct a SELECT query to check for duplicates based on euid, alw_id, and effect_date check_query = f"SELECT 1 FROM {table_name} WHERE euid = ? AND alw_id = ? AND amount = ?" # Execute the check query with the values of euid, alw_id, and effect_date cursor = db.cursor() cursor.execute(check_query, (euid, alw_id, amount)) row = cursor.fetchone() # If a row is found, return None to indicate that the query should not be executed if row: return "The SQL query has been skipped due to duplicate data." else: # No duplicates found, return the original query return query # If the pattern didn't match or the table name wasn't recognized, return the original query return query # Define the SQL DML Chain with the modified check_duplicate function sql_dml_chain = RunnableParallel({ "user_question": lambda x: question, "table_info": lambda _: db.get_table_info() }) | \ prompt | \ ChatOpenAI().bind(stop='SQL-Query:') | \ RunnableLambda(lambda x: check_duplicate(x.content, db) if 'INSERT' in x.content else x.content) # Define the Chat Prompt Template agent_prompt = ChatPromptTemplate.from_messages( [ ("system", """ You are expert in SQL whose main objective is to mainpulate the Database for which you have been given access. You can use the tool `sql_db_manipulation` to interact with Database and mainpulate the database as per the user requirement. Check user query for INSERT, UPDATE or DELETE operation, based on that perform the sql query. Wrapped column names: All column names should be wrapped in square brackets [] as delimiters. Use GETDATE() to get the current date and time instead of DATETIME('now'). Consider the column name carefully from the PAY_transaction_settingallow table where the modification is done. Take 'euid' in PAY_transaction_settingallow table from employee_details table which is 'employeeEuid' in employee_details table based on the matching 'employeeName' or 'employeeId' from employee_details table and stores it as 'euid' in the PAY_transaction_settingallow table. Similarly, to get the allowance ID ('alw_id') from the pay_mst_allowance table based on the matching allowance description ('alw_desc') or short name ('short_name'), check both 'alw_desc' and 'short_name'. Pay attention to the column names in user query and sql query. Perform JOIN operation to fetch euid and alw_id from respective tables not INNER JOIN. Selected table: Specify PAY_transaction_settingallow as the table to update. Employee and allowance selection: Use the WHERE clause to filter employees based on employeeName and allowances based on alw_desc. Date handling: 'createDate' should be the date on which the values are inserted, current date, it can not be NULL. 'effect_date' should be the start date of month. 'to_date' should be the end date of month. 'updatedDate' should be the date on which values are updated and it should be included only when UPDATE keywoed is used i query. UPDATE query should not change the 'createdDate' Currency: Assume the amount to be in rupees. If the users gives 'given by' in query enter that value in 'givenBy' column in PAY_transaction_settingallow table Modify the 'givenBy' column only when given by is specified by user, if not dont take givenBy column. Removed newlines: Write the query as a single string without newlines (\n). Ensure the query executes efficiently and without errors. If data or Values are already present in the table, dont again run the sql query. If no modifcation is made in table dont not display the message. If no rows are modifyed output its as "0 rows affected" Only Output the message after execution of SQL-Query If duplicate value is encountred with check_duplicate function Output the message like "The SQL query has been skipped due to duplicate data.". """), ("user", "{input}"), MessagesPlaceholder(variable_name="agent_scratchpad"), ] ) # Define the data model for SQLDBMANIPULATION tool class SQLDBMANIPULATION(BaseModel): user_query: str = Field(description='User question which will be translated to a Data Manipulation SQL Query and will be executed on the underlying database') class SQLDBMANIPULATIONTool(BaseTool): name = "sql_db_manipulation" description = "Use this tool to convert and execute DML queries given the user question, Use GETDATE() to get the current date and time instead of DATETIME('now')" args_schema: type[SQLDBMANIPULATION] = SQLDBMANIPULATION sql_dml_chain: Runnable def _run( self, user_query: str ) -> str: """Use the tool.""" try: if "The SQL query has been skipped due to duplicate data." not in user_query: # Execute the SQL query affected_rows = db._execute(user_query) if affected_rows == 0: # If no rows were affected, return the appropriate message return "0 rows affected" else: # Otherwise, return the success message return "The SQL query has been executed successfully." else: # If the query was skipped due to duplicate data, return the message return "The SQL query has been skipped due to duplicate data." except Exception as e: # If an error occurs during execution error_message = f"Error executing SQL query: {str(e)}" if "duplicate data" not in error_message.lower(): # If the error is not due to duplicate data, return the specific error message return error_message elif "Invalid column name" in error_message: # If the error is due to an invalid column name, provide a more informative error message return "Error: Invalid column name used in the SQL query." else: # If the error is due to duplicate data, return the standard message return "The SQL query has been skipped due to duplicate data." tools = [SQLDBMANIPULATIONTool(sql_dml_chain=sql_dml_chain)] llm_with_tools = ChatOpenAI().bind(functions=[format_tool_to_openai_function(t) for t in tools]) agent = ( { "input": lambda x: x["input"], "agent_scratchpad": lambda x: format_to_openai_function_messages( x["intermediate_steps"] ), } | agent_prompt | llm_with_tools | OpenAIFunctionsAgentOutputParser() ) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) answer = agent_executor.invoke({"input": question}) return answer["output"] result= chat5("insert personal allowance of 6000 to employee id TA******* for feb 2024, given by 3003") print(result) ### Error Message and Stack Trace (if applicable) > Entering new AgentExecutor chain... Invoking: `sql_db_manipulation` with `{'user_query': "INSERT INTO PAY_transaction_settingallow (euid, alw_id, amount, effect_date, to_date, createDate, givenBy) SELECT ed.employeeEuid, pma.alw_id, 6000, '2024-02-01', '2024-02-29', GETDATE(), '3003' FROM employee_details ed JOIN pay_mst_allowance pma ON ed.employeeName = 'TA*******' AND (pma.alw_desc = 'personal allowance' OR pma.short_name = 'personal allowance') WHERE NOT EXISTS (SELECT 1 FROM PAY_transaction_settingallow WHERE euid = ed.employeeEuid AND alw_id = pma.alw_id AND effect_date = '2024-02-01' AND to_date = '2024-02-29' AND amount = 6000)"}` The SQL query has been executed successfully.The personal allowance of 6000 has been inserted for employee ID TA******* for February 2024, given by 3003. ### Description in the output result of AgentExecutor its give the result as "The personal allowance of 6000 has been inserted for employee ID TA******* for February 2024, given by 3003. " but there is an error in the sql query written there as it's taking employee name instead of employeeID, in that case it should give the output something like "query is not executed" or "0 rows effectd" instead of giving as "The personal allowance of 6000 has been inserted for employee ID TA******* for February 2024, given by 3003." in lot of cases its happening the same when its not done any changes in table still its giving the output has "has been inserted" or "has been updated" i have written a logic to handle it externally, but that doesn't seems to work, so how to resolve this issue? ### System Info python: 3.11 langchain: latest os: windows
Error in AgentExecutor output result
https://api.github.com/repos/langchain-ai/langchain/issues/20965/comments
2
2024-04-27T08:31:32Z
2024-08-09T16:08:28Z
https://github.com/langchain-ai/langchain/issues/20965
2,266,912,926
20,965
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_openai.embeddings import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter from langchain_community.vectorstores import DocArrayInMemorySearch from langchain_community.document_loaders import TextLoader import tempfile import whisper from pytube import YouTube # Let's do this only if we haven't created the transcription file yet. if not os.path.exists("transcription.txt"): youtube = YouTube(YOUTUBE_VIDEO) audio = youtube.streams.filter(only_audio=True).first() # Let's load the base model. This is not the most accurate model but it's fast. whisper_model = whisper.load_model("base") with tempfile.TemporaryDirectory() as tmpdir: file = audio.download(output_path=tmpdir) transcription = whisper_model.transcribe(file, fp16=False)["text"].strip() with open("transcription.txt", "w") as file: file.write(transcription) documents = TextLoader("transcription.txt").load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() db = DocArrayInMemorySearch.from_documents(docs, embeddings) ``` ### Error Message and Stack Trace (if applicable) ```python --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[27], [line 11](vscode-notebook-cell:?execution_count=27&line=11) [7](vscode-notebook-cell:?execution_count=27&line=7) docs = text_splitter.split_documents(documents) [9](vscode-notebook-cell:?execution_count=27&line=9) embeddings = OpenAIEmbeddings() ---> [11](vscode-notebook-cell:?execution_count=27&line=11) db = DocArrayInMemorySearch.from_documents(docs, embeddings) File [c:\Users\astec\OneDrive\Documents\RAG_PROJECT\.venv\Lib\site-packages\langchain_core\vectorstores.py:550](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_core/vectorstores.py:550), in VectorStore.from_documents(cls, documents, embedding, **kwargs) [548](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_core/vectorstores.py:548) texts = [d.page_content for d in documents] [549](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_core/vectorstores.py:549) metadatas = [d.metadata for d in documents] --> [550](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_core/vectorstores.py:550) return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs) File [c:\Users\astec\OneDrive\Documents\RAG_PROJECT\.venv\Lib\site-packages\langchain_community\vectorstores\docarray\in_memory.py:68](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:68), in DocArrayInMemorySearch.from_texts(cls, texts, embedding, metadatas, **kwargs) [46](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:46) @classmethod [47](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:47) def from_texts( [48](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:48) cls, (...) [52](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:52) **kwargs: Any, [53](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:53) ) -> DocArrayInMemorySearch: [54](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:54) """Create an DocArrayInMemorySearch store and insert data. [55](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:55) [56](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:56) Args: (...) [66](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:66) DocArrayInMemorySearch Vector Store [67](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:67) """ ---> [68](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:68) store = cls.from_params(embedding, **kwargs) [69](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:69) store.add_texts(texts=texts, metadatas=metadatas) [70](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:70) return store File [c:\Users\astec\OneDrive\Documents\RAG_PROJECT\.venv\Lib\site-packages\langchain_community\vectorstores\docarray\in_memory.py:39](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:39), in DocArrayInMemorySearch.from_params(cls, embedding, metric, **kwargs) [21](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:21) @classmethod [22](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:22) def from_params( [23](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:23) cls, (...) [28](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:28) **kwargs: Any, [29](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:29) ) -> DocArrayInMemorySearch: [30](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:30) """Initialize DocArrayInMemorySearch store. [31](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:31) [32](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:32) Args: (...) [37](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:37) **kwargs: Other keyword arguments to be passed to the get_doc_cls method. [38](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:38) """ ---> [39](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:39) _check_docarray_import() [40](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:40) from docarray.index import InMemoryExactNNIndex [42](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py:42) doc_cls = cls._get_doc_cls(space=metric, **kwargs) File [c:\Users\astec\OneDrive\Documents\RAG_PROJECT\.venv\Lib\site-packages\langchain_community\vectorstores\docarray\base.py:19](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/base.py:19), in _check_docarray_import() [17](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/base.py:17) def _check_docarray_import() -> None: [18](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/base.py:18) try: ---> [19](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/base.py:19) import docarray [21](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/base.py:21) da_version = docarray.__version__.split(".") [22](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/langchain_community/vectorstores/docarray/base.py:22) if int(da_version[0]) == 0 and int(da_version[1]) <= 31: File [c:\Users\astec\OneDrive\Documents\RAG_PROJECT\.venv\Lib\site-packages\docarray\__init__.py:5](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/__init__.py:5) [1](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/__init__.py:1) __version__ = '0.32.1' [3](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/__init__.py:3) import logging ----> [5](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/__init__.py:5) from docarray.array import DocList, DocVec [6](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/__init__.py:6) from docarray.base_doc.doc import BaseDoc [7](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/__init__.py:7) from docarray.utils._internal.misc import _get_path_from_docarray_root_level File [c:\Users\astec\OneDrive\Documents\RAG_PROJECT\.venv\Lib\site-packages\docarray\array\__init__.py:2](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/__init__.py:2) [1](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/__init__.py:1) from docarray.array.any_array import AnyDocArray ----> [2](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/__init__.py:2) from docarray.array.doc_list.doc_list import DocList [3](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/__init__.py:3) from docarray.array.doc_vec.doc_vec import DocVec [5](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/__init__.py:5) __all__ = ['DocList', 'DocVec', 'AnyDocArray'] File [c:\Users\astec\OneDrive\Documents\RAG_PROJECT\.venv\Lib\site-packages\docarray\array\doc_list\doc_list.py:44](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:44) [36](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:36) T = TypeVar('T', bound='DocList') [37](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:37) T_doc = TypeVar('T_doc', bound=BaseDoc) [40](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:40) class DocList( [41](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:41) ListAdvancedIndexing[T_doc], [42](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:42) PushPullMixin, [43](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:43) IOMixinArray, ---> [44](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:44) AnyDocArray[T_doc], [45](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:45) ): [46](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:46) """ [47](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:47) DocList is a container of Documents. [48](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:48) (...) [114](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:114) [115](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:115) """ [117](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/doc_list/doc_list.py:117) doc_type: Type[BaseDoc] = AnyDoc File [c:\Users\astec\OneDrive\Documents\RAG_PROJECT\.venv\Lib\site-packages\docarray\array\any_array.py:46](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/any_array.py:46), in AnyDocArray.__class_getitem__(cls, item) [43](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/any_array.py:43) @classmethod [44](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/any_array.py:44) def __class_getitem__(cls, item: Union[Type[BaseDoc], TypeVar, str]): [45](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/any_array.py:45) if not isinstance(item, type): ---> [46](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/any_array.py:46) return Generic.__class_getitem__.__func__(cls, item) # type: ignore [47](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/any_array.py:47) # this do nothing that checking that item is valid type var or str [48](file:///C:/Users/astec/OneDrive/Documents/RAG_PROJECT/.venv/Lib/site-packages/docarray/array/any_array.py:48) if not issubclass(item, BaseDoc): AttributeError: 'builtin_function_or_method' object has no attribute '__func__' ``` ### Description Im trying to use langchain's DocArrayInMemorySearch to create a vector database for my transcription text file, I've written code exactly as it is shown within the LangChain documentation but it does not work ### System Info System Information ------------------ > OS: Windows > OS Version: 10.0.22631 > Python Version: 3.12.3 (tags/v3.12.3:f6650f9, Apr 9 2024, 14:05:25) [MSC v.1938 64 bit (AMD64)] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.51 > langchain_openai: 0.1.3 > langchain_pinecone: 0.1.0 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
Langchain DocArrayInMemorySearch not working
https://api.github.com/repos/langchain-ai/langchain/issues/20957/comments
1
2024-04-26T21:56:36Z
2024-05-15T21:17:11Z
https://github.com/langchain-ai/langchain/issues/20957
2,266,553,770
20,957
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code This is a problem encountered by checking a piece of code before committing it ### Error Message and Stack Trace (if applicable) Before that I created a new virtual environment, git clone langchain's repository and use pip install -e. All dependencies are installed ### Description This is a problem encountered by checking a piece of code before committing it. Before that I created a new virtual environment, git clone langchain's repository and use pip install -e. All dependencies are installed. An error occurred while executing make lint_diff <img width="436" alt="image" src="https://github.com/langchain-ai/langchain/assets/164149097/8faf80fe-f743-4666-9bbf-5367872126af"> <img width="577" alt="image" src="https://github.com/langchain-ai/langchain/assets/164149097/4623df19-0c82-45c9-8a31-4e62420c06ff"> <img width="408" alt="image" src="https://github.com/langchain-ai/langchain/assets/164149097/42a2857d-15b2-4d6d-b6a9-e7f5fbba36b9"> ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:41 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T8103 > Python Version: 3.11.9 (main, Apr 19 2024, 11:44:45) [Clang 14.0.6 ] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.51 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
Command not found: ruff
https://api.github.com/repos/langchain-ai/langchain/issues/20934/comments
2
2024-04-26T15:24:18Z
2024-04-30T19:46:13Z
https://github.com/langchain-ai/langchain/issues/20934
2,266,018,752
20,934
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` retrieve_chain = self.cat_query_prompt | self.retriever_llm | StrOutputParser() json_s = retrieve_chain.invoke({"question": query,"schema":self.cat_schema_json, "brand_list":list(df['brand_name'].unique()), "few_shot":self.cat_schema_fewshot}) ``` ### Error Message and Stack Trace (if applicable) File "/workspace/selfquery_utils.py", line 151, in get_categorical_filters json_s = retrieve_chain.invoke({"question": query,"schema":self.cat_schema_json, "brand_list":list(df['brand_name'].unique()), "few_shot":self.cat_schema_fewshot}) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/layers/google.python.pip/pip/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 2499, in invoke input = step.invoke( ^^^^^^^^^^^^ File "/layers/google.python.pip/pip/lib/python3.11/site-packages/langchain_core/language_models/llms.py", line 276, in invoke self.generate_prompt( File "/layers/google.python.pip/pip/lib/python3.11/site-packages/langchain_core/language_models/llms.py", line 633, in generate_prompt return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/layers/google.python.pip/pip/lib/python3.11/site-packages/langchain_core/language_models/llms.py", line 803, in generate output = self._generate_helper( ^^^^^^^^^^^^^^^^^^^^^^ File "/layers/google.python.pip/pip/lib/python3.11/site-packages/langchain_core/language_models/llms.py", line 670, in _generate_helper raise e File "/layers/google.python.pip/pip/lib/python3.11/site-packages/langchain_core/language_models/llms.py", line 657, in _generate_helper self._generate( File "/layers/google.python.pip/pip/lib/python3.11/site-packages/langchain_google_vertexai/llms.py", line 223, in _generate res = _completion_with_retry( ^^^^^^^^^^^^^^^^^^^^^^^ File "/layers/google.python.pip/pip/lib/python3.11/site-packages/langchain_google_vertexai/llms.py", line 72, in _completion_with_retry with telemetry.tool_context_manager(llm._user_agent): File "/layers/google.python.runtime/python/lib/python3.11/contextlib.py", line 144, in __exit__ next(self.gen) File "/layers/google.python.pip/pip/lib/python3.11/site-packages/google/cloud/aiplatform/telemetry.py", line 48, in tool_context_manager _pop_tool_name(tool_name) File "/layers/google.python.pip/pip/lib/python3.11/site-packages/google/cloud/aiplatform/telemetry.py", line 57, in _pop_tool_name raise RuntimeError( RuntimeError: Tool context error detected. This can occur due to parallelization. ### Description The chain generates a json that is goint to be used as a filter for a vector database. I've been using this chain for months and its the first time that I get this error. I tried to replicate it but nothing happened. ### System Info google-cloud-discoveryengine==0.11.2 google-cloud-aiplatform langchain langchain-core langchain-experimental langchainplus-sdk langchain-google-genai ipywidgets==7.7.2 pandas==2.0.3 google-cloud-bigquery db-dtypes langchain-google-vertexai shortuuid google-cloud-storage redis
Getting "RuntimeError: Tool context error detected. This can occur due to parallelization." while invoking a chain using langchain_google_vertexai
https://api.github.com/repos/langchain-ai/langchain/issues/20929/comments
8
2024-04-26T13:23:22Z
2024-06-10T15:37:33Z
https://github.com/langchain-ai/langchain/issues/20929
2,265,784,123
20,929
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` prompt = ChatPromptTemplate.from_template(prompt) model = HuggingFacePipeline(pipeline=LLM) chain = prompt | model results = chain.batch( df.to_dict( orient="records" ), config={ "max_concurrency": 2 }, ) for response in results: print(response.content) ``` ### Error Message and Stack Trace (if applicable) str does contain response ### Description Ehe chain.batch method does not return an AImessage, as detailed in the documentation, instead it return a list of strings. This string contains the prompt + response, making it up to the user to seperate the two. ### System Info langchain 0.1.14 python 3.10.5 system: ubuntu 22
chain called through the batch method return list[str] instead of list[AIMessage] when using the HuggingFacePipeline
https://api.github.com/repos/langchain-ai/langchain/issues/20926/comments
0
2024-04-26T11:38:04Z
2024-08-02T16:08:07Z
https://github.com/langchain-ai/langchain/issues/20926
2,265,599,031
20,926
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_community.tools import DuckDuckGoSearchResults from langchain import hub from langchain.agents import create_openai_functions_agent from langchain_experimental.llms.ollama_functions import OllamaFunctions from langgraph.prebuilt import create_agent_executor tools = [DuckDuckGoSearchResults(max_results=3)] # llm = OllamaFunctions(model="mixtral") llm = OllamaFunctions(model="llama3:latest") prompt = hub.pull("hwchase17/openai-functions-agent") # Construct the OpenAI Functions agent agent_runnable = create_openai_functions_agent(llm, tools, prompt) agent_executor = create_agent_executor(agent_runnable, tools) agent_executor.invoke( {"input": "who is the winnner of the us open", "chat_history": []} ) ``` ### Error Message and Stack Trace (if applicable) ``` --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[1], [line 21](vscode-notebook-cell:?execution_count=1&line=21) [18](vscode-notebook-cell:?execution_count=1&line=18) agent_runnable = create_openai_functions_agent(llm, tools, prompt) [20](vscode-notebook-cell:?execution_count=1&line=20) agent_executor = create_agent_executor(agent_runnable, tools) ---> [21](vscode-notebook-cell:?execution_count=1&line=21) agent_executor.invoke( [22](vscode-notebook-cell:?execution_count=1&line=22) {"input": "who is the winnner of the us open", "chat_history": []} [23](vscode-notebook-cell:?execution_count=1&line=23) ) ... [152](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:152) def _create_chat_stream( [153](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:153) self, [154](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:154) messages: List[BaseMessage], [155](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:155) stop: Optional[List[str]] = None, [156](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:156) **kwargs: Any, [157](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:157) ) -> Iterator[str]: [158](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:158) payload = { [159](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:159) "model": self.model, --> [160](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:160) "messages": self._convert_messages_to_ollama_messages(messages), [161](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:161) } [162](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:162) yield from self._create_stream( [163](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:163) payload=payload, stop=stop, api_url=f"{self.base_url}[/api/chat](https://file+.vscode-resource.vscode-cdn.net/api/chat)", **kwargs [164](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:164) ) File [~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:112](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:112), in ChatOllama._convert_messages_to_ollama_messages(self, messages) [110](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:110) role = "system" [111](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:111) else: --> [112](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:112) raise ValueError("Received unsupported message type for Ollama.") [114](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:114) content = "" [115](https://file+.vscode-resource.vscode-cdn.net/Users/bas/Development/HeadingFWD/langchain-playground/notebooks/langgraph/~/Development/HeadingFWD/langchain-playground/.venv/lib/python3.11/site-packages/langchain_community/chat_models/ollama.py:115) images = [] ValueError: Received unsupported message type for Ollama. ``` ### Description I'm trying to get Function Calls working with `OllamaFunctions`. I tried this with several different models btw, mistral, llama3, dolphincoder, mixtral:8x22b. It will always respond with: ``` ValueError: Received unsupported message type for Ollama. ``` I've found these issues as well that might be related: https://github.com/langchain-ai/langchain/issues/14360 https://github.com/langchain-ai/langchain/pull/20881 I found that OllamaFunctions returns a `FunctionMessage` but `_convert_messages_to_ollama_messages` from OllamaChat doesn't recognize that and is not able to call the function. https://github.com/langchain-ai/langchain/blob/4c437ebb9c2fb532ce655ac1e0c354c82a715df7/libs/community/langchain_community/chat_models/ollama.py#L99 Any help would be greatly appreciated. ### System Info ``` python3 -m langchain_core.sys_info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:37 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6031 > Python Version: 3.11.8 (v3.11.8:db85d51d3e, Feb 6 2024, 18:02:37) [Clang 13.0.0 (clang-1300.0.29.30)] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.49 > langchain_experimental: 0.0.57 > langchain_openai: 0.1.3 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 > langgraph: 0.0.39 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langserve ```
OllamaFunctions does not work - Received unsupported message type for Ollama
https://api.github.com/repos/langchain-ai/langchain/issues/20924/comments
4
2024-04-26T10:02:21Z
2024-06-13T09:55:39Z
https://github.com/langchain-ai/langchain/issues/20924
2,265,435,854
20,924
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [x] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-3.5-turbo-16k", temperature=0) prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful assistant that translates {input_language} to {output_language}.", ), ("human", "{input}"), ] ) agent = prompt | llm response = "" async for token in agent.astream({ "input_language": "English", "output_language": "German", "input": "I love programming.", }): response += token.content ``` ### Error Message and Stack Trace (if applicable) File "/home/rcaulk/projects/flowdapt_new_schema/chat-service/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 2900, in astream async for chunk in self.atransform(input_aiter(), config, **kwargs): File "/home/rcaulk/projects/flowdapt_new_schema/chat-service/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 2883, in atransform async for chunk in self._atransform_stream_with_config( File "/home/rcaulk/projects/flowdapt_new_schema/chat-service/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 1980, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/rcaulk/projects/flowdapt_new_schema/chat-service/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 2853, in _atransform async for output in final_pipeline: File "/home/rcaulk/projects/flowdapt_new_schema/chat-service/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 1334, in atransform async for output in self.astream(final, config, **kwargs): File "/home/rcaulk/projects/flowdapt_new_schema/chat-service/.venv/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 319, in astream raise e File "/home/rcaulk/projects/flowdapt_new_schema/chat-service/.venv/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 297, in astream async for chunk in self._astream( File "/home/rcaulk/projects/flowdapt_new_schema/chat-service/.venv/lib/python3.11/site-packages/langchain_openai/chat_models/base.py", line 560, in _astream async with response: 'async_generator' object does not support the asynchronous context manager protocol ### Description Using an async generator fails with 'async_generator' object does not support the asynchronous context manager protocol in langchain-openai>=0.1.2 Everything is functional in langchain-openai<=0.1.1. ### System Info langchain-openai==0.1.2+ Ubuntu 22.04 Python 3.11.4
[BUG] langchain-openai 0.1.2+ breaks async generation
https://api.github.com/repos/langchain-ai/langchain/issues/20923/comments
10
2024-04-26T09:42:50Z
2024-06-23T17:20:22Z
https://github.com/langchain-ai/langchain/issues/20923
2,265,390,401
20,923
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` (venv)LeideMacBook-Pro community % poetry run pytest tests/integration_tests/document_loaders/test_recursive_url_loader.py ================================================================================ test session starts ================================================================================ platform darwin -- Python 3.11.4, pytest-7.4.4, pluggy-1.4.0 -- /Users/zhanglei/Work/github/langchain/venv/bin/python cachedir: .pytest_cache rootdir: /Users/zhanglei/Work/github/langchain/libs/community configfile: pyproject.toml plugins: syrupy-4.6.1, asyncio-0.20.3, cov-4.1.0, vcr-1.0.2, mock-3.12.0, anyio-3.7.1, dotenv-0.5.2, requests-mock-1.11.0, socket-0.6.0 asyncio: mode=Mode.AUTO collected 6 items tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_async_recursive_url_loader FAILED [ 16%] tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_async_recursive_url_loader_deterministic PASSED [ 33%] tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_recursive_url_loader PASSED [ 50%] tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_async_equivalent PASSED [ 66%] tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_loading_invalid_url PASSED [ 83%] tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_async_metadata_necessary_properties PASSED [100%] ===================================================================================== FAILURES ====================================================================================== __________________________________________________________________________ test_async_recursive_url_loader __________________________________________________________________________ def test_async_recursive_url_loader() -> None: url = "https://docs.python.org/3.9/" loader = RecursiveUrlLoader( url, extractor=lambda _: "placeholder", use_async=True, max_depth=3, timeout=None, check_response_status=True, ) docs = loader.load() > assert len(docs) == 513 E AssertionError: assert 512 == 513 E + where 512 = len([Document(page_content='placeholder', metadata={'source': 'https://docs.python.org/3.9/', 'content_type': 'text/html', 'title': '3.9.18 Documentation', 'language': None}), Document(page_content='placeholder', metadata={'source': 'https://docs.python.org/3.9/search.html', 'content_type': 'text/html', 'title': 'Search — Python 3.9.18 documentation', 'language': None}), Document(page_content='placeholder', metadata={'source': 'https://docs.python.org/3.9/index.html', 'content_type': 'text/html', 'title': '3.9.18 Documentation', 'language': None}), Document(page_content='placeholder', metadata={'source': 'https://docs.python.org/3.9/library/index.html', 'content_type': 'text/html', 'title': 'The Python Standard Library — Python 3.9.18 documentation', 'language': None}), Document(page_content='placeholder', metadata={'source': 'https://docs.python.org/3.9/library/xml.sax.reader.html', 'content_type': 'text/html', 'title': 'xml.sax.xmlreader — Interface for XML parsers — Python 3.9.18 documentation', 'language': None}), Document(page_content='placeholder', metadata={'source': 'https://docs.python.org/3.9/library/tkinter.colorchooser.html', 'content_type': 'text/html', 'title': 'tkinter.colorchooser — Color choosing dialog — Python 3.9.18 documentation', 'language': None}), ...]) tests/integration_tests/document_loaders/test_recursive_url_loader.py:15: AssertionError ================================================================================= warnings summary ================================================================================== tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_async_recursive_url_loader tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_async_recursive_url_loader_deterministic tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_recursive_url_loader tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_async_equivalent tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_async_metadata_necessary_properties /Users/zhanglei/.pyenv/versions/3.11.4/lib/python3.11/html/parser.py:170: XMLParsedAsHTMLWarning: It looks like you're parsing an XML document using an HTML parser. If this really is an HTML document (maybe it's XHTML?), you can ignore or filter this warning. If it's XML, you should know that using an XML parser will be more reliable. To parse this document as XML, make sure you have the lxml package installed, and pass the keyword argument `features="xml"` into the BeautifulSoup constructor. k = self.parse_starttag(i) -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ================================================================================ slowest 5 durations ================================================================================ 48.34s call tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_async_recursive_url_loader_deterministic 31.59s call tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_async_equivalent 30.15s call tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_async_metadata_necessary_properties 25.80s call tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_async_recursive_url_loader 15.13s call tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_sync_recursive_url_loader ============================================================================== short test summary info ============================================================================== FAILED tests/integration_tests/document_loaders/test_recursive_url_loader.py::test_async_recursive_url_loader - AssertionError: assert 512 == 513 ================================================================ 1 failed, 5 passed, 5 warnings in 151.33s (0:02:31) ================================================================ ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description The integration tests for "test_async_recursive_url_loader.py" are failing ### System Info langchain==0.1.14 langchain-community==0.0.31 langchain-core==0.1.40 langchain-experimental==0.0.56 langchain-openai==0.1.1 langchain-text-splitters==0.0.1 langchainhub==0.1.15 macOS 14.3.1 Python 3.11.4
The integration tests for "test_async_recursive_url_loader.py" are failing
https://api.github.com/repos/langchain-ai/langchain/issues/20919/comments
0
2024-04-26T08:52:32Z
2024-07-09T08:15:46Z
https://github.com/langchain-ai/langchain/issues/20919
2,265,294,100
20,919
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code user_question = tracker.latest_message['text'] #metadata = tracker.latest_message.get('metadata', {}) text_field = "text" vectorstore = PineconeVectorStore( index_name ="rasarag", embeddings, text_field ) response = rag_chain(vectorstore,user_question) def rag_chain(vectorstore,user_question): retriever = vectorstore.as_retriever() prompt = hub.pull("rlm/rag-prompt") rag_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | prompt | llm | StrOutputParser() ) return rag_chain.invoke(user_question) ### Error Message and Stack Trace (if applicable) Traceback (most recent call last): File "handle_request", line 83, in handle_request ) File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\rasa_sdk\endpoint.py", line 113, in webhook result = await executor.run(action_call) File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\rasa_sdk\executor.py", line 399, in run action(dispatcher, tracker, domain) File "C:\Users\prakotian\Desktop\Projects\GenAI Projects\RasaRAGGPT\actions\actions.py", line 30, in run response = rag_chain(vectorstore,user_question) File "C:\Users\prakotian\Desktop\Projects\GenAI Projects\RasaRAGGPT\actions\llm.py", line 62, in rag_chain return rag_chain.invoke(user_question) File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_core\runnables\base.py", line 2499, in invoke input = step.invoke( File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_core\runnables\base.py", line 3144, in invoke output = {key: future.result() for key, future in zip(steps, futures)} File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_core\runnables\base.py", line 3144, in <dictcomp> output = {key: future.result() for key, future in zip(steps, futures)} File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\concurrent\futures\_base.py", line 458, in result return self.__get_result() File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\concurrent\futures\_base.py", line 403, in __get_result raise self._exception File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\concurrent\futures\thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_core\runnables\base.py", line 2499, in invoke input = step.invoke( File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_core\retrievers.py", line 193, in invoke return self.get_relevant_documents( File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_core\retrievers.py", line 321, in get_relevant_documents raise e File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_core\retrievers.py", line 314, in get_relevant_documents result = self._get_relevant_documents( File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_core\vectorstores.py", line 696, in _get_relevant_documents docs = self.vectorstore.similarity_search(query, **self.search_kwargs) File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_pinecone\vectorstores.py", line 247, in similarity_search docs_and_scores = self.similarity_search_with_score( File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_pinecone\vectorstores.py", line 192, in similarity_search_with_score return self.similarity_search_by_vector_with_score( File "C:\Users\prakotian\AppData\Local\miniconda3\envs\RasaGPT\lib\site-packages\langchain_pinecone\vectorstores.py", line 209, in similarity_search_by_vector_with_score results = self._index.query( AttributeError: 'str' object has no attribute 'query' ### Description I am trying to use RASA with langchain but I am facing this error ### System Info System Information ------------------ > OS: Windows > OS Version: 10.0.19045 > Python Version: 3.10.14 | packaged by Anaconda, Inc. | (main, Mar 21 2024, 16:20:14) [MSC v.1916 64 bit (AMD64)] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.50 > langchain_chroma: 0.1.0 > langchain_cohere: 0.1.4 > langchain_groq: 0.1.3 > langchain_openai: 0.1.3 > langchain_pinecone: 0.1.0 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15
Pinecone RAG not working.
https://api.github.com/repos/langchain-ai/langchain/issues/20918/comments
0
2024-04-26T08:26:29Z
2024-08-02T16:08:02Z
https://github.com/langchain-ai/langchain/issues/20918
2,265,244,855
20,918
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` langfuse_handler = CallbackHandler( secret_key="sk-lf-...", public_key="pk-lf-...", host="host.." ... ) prompt_template = ChatPromptTemplate.from_template( template=prompt, ) llm = BedrockChat( credentials_profile_name=profile, model_id=model_id, client=client, model_kwargs=model_kwargs, verbose=verbose, callbacks=[langfuse_handler], ) output_parser = StrOutputParser() chain = prompt_template | llm | output_parser output = chain.invoke( input={"color": "red"}, config={"callbacks": [langfuse_handler]}, ) ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description I’ve encountered a persistent issue with the latest versions of langchain, langchain-core, and langchain community. The problem arises when the system fails to recognize the model, which results in the following warning message: `WARNING:langfuse:Langfuse was not able to parse the LLM model. The LLM call will be recorded without model name. Please create an issue so we can fix your integration.` This issue prevents the correct tracing of model usage and pricing on Langfuse. Interestingly, when I revert to older versions of the packages (langchain v0.1.13, langchain community v0.0.31, and langchain-core v0.1.39), the warning no longer appears, and Langfuse operates as expected. ### System Info langchain-core==0.1.46 langchain-community==0.0.34 langchain==0.1.16
Langfuse was not able to parse the LLM model.
https://api.github.com/repos/langchain-ai/langchain/issues/20915/comments
2
2024-04-26T07:39:01Z
2024-08-08T16:06:45Z
https://github.com/langchain-ai/langchain/issues/20915
2,265,159,454
20,915
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code Other values like `DATABRICKS_TOKEN` and `DATABRICKS_HOST` are set in env vars. ```python from langchain_community.utilities.sql_database import SQLDatabase db = SQLDatabase.from_databricks( catalog="samples", schema="nyctaxi", warehouse_id="<redacted>" ) result = db.run("SELECT 1") print(result) ``` ### Error Message and Stack Trace (if applicable) No error message, just hangs indefinitely, I can't find a way to introspect what's going on. ### Description I'm trying to create an instance of SQLDatabase from Databricks configs, would expect to get an error or for there to be some type of output. I've pared the code down from a more expansive agent workflow to just this and pinned it down to the `from_databricks` call that's just hanging. Super appreciate any insight. I don't see anybody else having this problem, but I also can't see anything wrong in my configs after hours of troubleshooting. Thanks in advance 🙏🏻 . ### System Info ``` System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:19: 22 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T8112 > Python Version: 3.11.8 (main, Apr 7 2024, 16:30:13) [Clang 15.0.0 (clang-1500.3.9.4)] Package Information ------------------- > langchain_core: 0.1.46 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.51 > langchain_experimental: 0.0.57 > langchain_openai: 0.1.3 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve ```
`SQLDatabase.from_databricks` seems to hang indefinitely
https://api.github.com/repos/langchain-ai/langchain/issues/20910/comments
1
2024-04-25T21:58:34Z
2024-05-15T06:13:15Z
https://github.com/langchain-ai/langchain/issues/20910
2,264,565,012
20,910
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from langchain_community.document_loaders import ArxivLoader docs = ArxivLoader(query = "Advanced regression models for real estate price prediction", load_max_docs=100, load_all_available_meta=True).load() ### Error Message and Stack Trace (if applicable) --------------------------------------------------------------------------- HTTPError Traceback (most recent call last) Cell In[9], [line 7](vscode-notebook-cell:?execution_count=9&line=7) [1](vscode-notebook-cell:?execution_count=9&line=1) from langchain_community.document_loaders import ArxivLoader [3](vscode-notebook-cell:?execution_count=9&line=3) #ArxivLoader [4](vscode-notebook-cell:?execution_count=9&line=4) #HTTPError: HTTP Error 404: Not Found [5](vscode-notebook-cell:?execution_count=9&line=5) [6](vscode-notebook-cell:?execution_count=9&line=6) # Load documents using ArxivLoader with the concise_query ----> [7](vscode-notebook-cell:?execution_count=9&line=7) docs = ArxivLoader(query = "Advanced regression models for real estate price prediction", load_max_docs=100, load_all_available_meta=True).load() File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/document_loaders/arxiv.py:27](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/document_loaders/arxiv.py:27), in ArxivLoader.load(self) [26](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/document_loaders/arxiv.py:26) def load(self) -> List[Document]: ---> [27](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/document_loaders/arxiv.py:27) return self.client.load(self.query) File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/utilities/arxiv.py:208](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/utilities/arxiv.py:208), in ArxivAPIWrapper.load(self, query) [206](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/utilities/arxiv.py:206) for result in results: [207](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/utilities/arxiv.py:207) try: --> [208](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/utilities/arxiv.py:208) doc_file_name: str = result.download_pdf() [209](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/utilities/arxiv.py:209) with fitz.open(doc_file_name) as doc_file: [210](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain_community/utilities/arxiv.py:210) text: str = "".join(page.get_text() for page in doc_file) File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/arxiv/__init__.py:214](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/arxiv/__init__.py:214), in Result.download_pdf(self, dirpath, filename) [212](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/arxiv/__init__.py:212) filename = self._get_default_filename() [213](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/arxiv/__init__.py:213) path = os.path.join(dirpath, filename) --> [214](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/arxiv/__init__.py:214) written_path, _ = urlretrieve(self.pdf_url, path) [215](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/arxiv/__init__.py:215) return written_path File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:241](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:241), in urlretrieve(url, filename, reporthook, data) [224](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:224) """ [225](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:225) Retrieve a URL into a temporary location on disk. [226](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:226) (...) [237](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:237) data file as well as the resulting HTTPMessage object. [238](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:238) """ [239](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:239) url_type, path = _splittype(url) --> [241](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:241) with contextlib.closing(urlopen(url, data)) as fp: [242](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:242) headers = fp.info() [244](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:244) # Just return the local path and the "headers" for file:// [245](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:245) # URLs. No sense in performing a copy unless requested. File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:216](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:216), in urlopen(url, data, timeout, cafile, capath, cadefault, context) [214](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:214) else: [215](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:215) opener = _opener --> [216](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:216) return opener.open(url, data, timeout) File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:525](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:525), in OpenerDirector.open(self, fullurl, data, timeout) [523](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:523) for processor in self.process_response.get(protocol, []): [524](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:524) meth = getattr(processor, meth_name) --> [525](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:525) response = meth(req, response) [527](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:527) return response File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:634](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:634), in HTTPErrorProcessor.http_response(self, request, response) [631](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:631) # According to RFC 2616, "2xx" code indicates that the client's [632](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:632) # request was successfully received, understood, and accepted. [633](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:633) if not (200 <= code < 300): --> [634](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:634) response = self.parent.error( [635](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:635) 'http', request, response, code, msg, hdrs) [637](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:637) return response File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:563](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:563), in OpenerDirector.error(self, proto, *args) [561](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:561) if http_err: [562](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:562) args = (dict, 'default', 'http_error_default') + orig_args --> [563](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:563) return self._call_chain(*args) File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:496](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:496), in OpenerDirector._call_chain(self, chain, kind, meth_name, *args) [494](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:494) for handler in handlers: [495](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:495) func = getattr(handler, meth_name) --> [496](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:496) result = func(*args) [497](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:497) if result is not None: [498](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:498) return result File [/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:643](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:643), in HTTPDefaultErrorHandler.http_error_default(self, req, fp, code, msg, hdrs) [642](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:642) def http_error_default(self, req, fp, code, msg, hdrs): --> [643](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:643) raise HTTPError(req.full_url, code, msg, hdrs, fp) HTTPError: HTTP Error 404: Not Found ### Description I am trying to use ArxivLoader from langchain_community.document_loaders to load 100 academic articles from arxiv database for certain keywords with metadata. But, I am getting this error. I have successfully run the code beforehand, but this time, it gives 404 Error. ### System Info MacOS, Python 3.10.13 pip freeze | grep langchain langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.46 langchain-openai==0.0.6 langchain-text-splitters==0.0.1 langchainhub==0.1.14
Getting "HTTP Error 404: Not Found" Error Using ArxivLoader
https://api.github.com/repos/langchain-ai/langchain/issues/20909/comments
2
2024-04-25T21:06:55Z
2024-08-06T16:08:37Z
https://github.com/langchain-ai/langchain/issues/20909
2,264,497,053
20,909
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain.text_splitter import CharacterTextSplitter splitter = CharacterTextSplitter( chunk_size=10, chunk_overlap=0, separator=". ", keep_separator=True, ) for d in splitter.create_documents(["Text 1. Text 2. Text 3. Text 4."]): print(d.page_content) print("---") ``` ### Error Message and Stack Trace (if applicable) ``` Text 1 --- . Text 2 --- . Text 3 --- . Text 4. --- ``` ### Description I'm trying to split text by sentence, while keeping end-of-sentence punctuation. Instead of putting the punctuation back at the end of the corresponding chunk, the library adds it to the front of the following chunk. This problem is quite critical if the output is used for text-to-speech input. ### System Info ``` langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.46 langchain-text-splitters==0.0.1 ``` MacOS, Python 3.10.13
`CharacterTextSplitter` with `keep_separator=True` sets the separator to the beginning of each chunk instead of an end
https://api.github.com/repos/langchain-ai/langchain/issues/20908/comments
1
2024-04-25T21:04:55Z
2024-05-22T20:17:47Z
https://github.com/langchain-ai/langchain/issues/20908
2,264,494,166
20,908
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python import duckdb as db from langchain.vectorstores import DuckDB from langchain_community.embeddings import HuggingFaceEmbeddings embeddings= HuggingFaceEmbeddings(model_name= "avsolatorio/GIST-small-Embedding-v0") example_text = embeddings.embed_query("this is example text") # new database conn = db.connect(database='data/example.db') conn.sql(""" CREATE OR REPLACE TABLE t1 ( id VARCHAR PRIMARY KEY, content VARCHAR, embedding FLOAT[], ); """) conn.execute("""INSERT INTO t1 VALUES ( 'id1', 'this is example text', $1, )""", [example_text]) vector_store = DuckDB( connection= conn, embedding= embeddings, vector_key= 'embedding', id_key = 'id', text_key= 'content', table_name = 't1' ) vector_store.add_texts(['more example text', 'yet more again']) # Results in --> BinderException: Binder Error: table t1 has 3 columns but 4 values were supplied vector_store.similarity_search('more example text') # Results in --> KeyError: 'metadata' conn.sql(""" CREATE OR REPLACE TABLE t1 ( id VARCHAR PRIMARY KEY, content VARCHAR, embedding FLOAT[], additional_field1 VARCHAR, -- not named metadata and works to add but not to search ); """) conn.execute("""INSERT INTO t1 VALUES ( 'id1', 'this is example text', $1, 'random thing', )""", [example_text]) vector_store = DuckDB( connection= conn, embedding= embeddings, vector_key= 'embedding', id_key = 'id', text_key= 'content', table_name = 't1' ) vector_store.add_texts(['more example text', 'yet more again']) # Results in --> Works vector_store.similarity_search('more example text') # Results in --> KeyError: 'metadata' conn.sql(""" CREATE OR REPLACE TABLE t1 ( id VARCHAR PRIMARY KEY, content VARCHAR, embedding FLOAT[], metadata VARCHAR, -- ); """) conn.execute("""INSERT INTO t1 VALUES ( 'id1', 'this is example text', $1, '', )""", [example_text]) vector_store = DuckDB( connection= conn, embedding= embeddings, vector_key= 'embedding', id_key = 'id', text_key= 'content', table_name = 't1' ) vector_store.add_texts(['more example text', 'yet more again']) # Results in --> works vector_store.similarity_search('more example text') # Results in --> works conn.close() ``` ### Error Message and Stack Trace (if applicable) File index.pyx:196, in pandas._libs.index.IndexEngine.get_loc() File pandas/_libs/hashtable_class_helper.pxi:7081, in pandas._libs.hashtable.PyObjectHashTable.get_item() File pandas/_libs/hashtable_class_helper.pxi:7089, in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'metadata' The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) File [/Users/user/Documents/project/task/run.py:1 ----> [1](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:1) vector_store.similarity_search('more example text') File [~/Documents/project](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project) Playground/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:198, in DuckDB.similarity_search(self, query, k, **kwargs) [175](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:175) list_cosine_similarity = self.duckdb.FunctionExpression( ... [3815](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/pandas/core/indexes/base.py:3815) # InvalidIndexError. Otherwise we fall through and re-raise [3816](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/pandas/core/indexes/base.py:3816) # the TypeError. [3817](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/pandas/core/indexes/base.py:3817) self._check_indexing_error(key) KeyError: 'metadata' --------------------------------------------------------------------------- BinderException Traceback (most recent call last) File [/Users/user/Documents/project/task/run.py:24 [8](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:8) conn.execute("""INSERT INTO t1 VALUES ( [9](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:9) 'id1', [10](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:10) 'this is example text', [11](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:11) $1, [12](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:12) )""", [example_text]) [15](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:15) vector_store = DuckDB( [16](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:16) connection= conn, [17](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:17) embedding= embeddings, (...) [21](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:21) table_name = 't1' [22](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:22) ) ---> [24](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/task/run.py:24) vector_store.add_texts(['more example text', 'yet more again']) File [~/Documents/project](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project) Playground/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:156, in DuckDB.add_texts(self, texts, metadatas, **kwargs) [150](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:150) # Serialize metadata if present, else default to None [151](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:151) metadata = ( [152](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:152) json.dumps(metadatas[idx]) [153](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:153) if metadatas and idx < len(metadatas) [154](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:154) else None [155](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:155) ) --> [156](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:156) self._connection.execute( [157](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:157) f"INSERT INTO {self._table_name} VALUES (?,?,?,?)", [158](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:158) [ids[idx], text, embedding, metadata], [159](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:159) ) [160](https://file+.vscode-resource.vscode-cdn.net/Users/user/Documents/project/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/duckdb.py:160) return ids BinderException: Binder Error: table t1 has 3 columns but 4 values were supplied ### Description I'm trying to use the langchain.vectorstores DuckDB object to create a vector store for embeddings. I already had an existing table from a colleague and I thought to map the existing fields to DuckDB object initialization. Unfortunately, there is not a field for `metadata` and if you do *not* have this field, nothing works. Both adding text and similarity search either result in an error and stops the program or a hidden errors where (I was not able to reproduce this with the minimal example above) that doesn't add new text to the database or results in an empty list `[]` as a result for similarity search. I only discovered the reason for the problem when I used a blank database and used the DuckDB vectorstore object create the table. I realized then that it also created a `metadata` field, which makes sense considering the pattern across other vectorstores. I propose adding this as a mapping argument when users are adapting an existing table. This would at least highlight to the user that a metadata field is expected and map the table if it already exists under a different name. Additionally, adding the field if missing would also be an improvement imo. ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.2.0: Wed Nov 15 21:54:51 PST 2023; root:xnu-10002.61.3~2/RELEASE_ARM64_T6030 > Python Version: 3.12.1 (main, Jan 25 2024, 14:02:10) [Clang 15.0.0 (clang-1500.1.0.2.5)] Package Information ------------------- > langchain_core: 0.1.44 > langchain: 0.1.16 > langchain_community: 0.0.33 > langsmith: 0.1.36 > langchain_openai: 0.1.1 > langchain_postgres: 0.0.3 > langchain_text_splitters: 0.0.1 > langgraph: 0.0.32 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langserve
duckdb vector store missing metadata field during initialization causing failure when connecting to existing tables
https://api.github.com/repos/langchain-ai/langchain/issues/20906/comments
0
2024-04-25T20:48:56Z
2024-08-01T16:07:14Z
https://github.com/langchain-ai/langchain/issues/20906
2,264,470,541
20,906
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain.prompts import FewShotPromptTemplate, PromptTemplate from langchain.chat_models import ChatOpenAI from langchain.pydantic_v1 import BaseModel from langchain_experimental.tabular_synthetic_data.base import SyntheticDataGenerator from langchain_experimental.tabular_synthetic_data.openai import create_openai_data_generator, OPENAI_TEMPLATE from langchain_experimental.tabular_synthetic_data.prompts import SYNTHETIC_FEW_SHOT_SUFFIX, SYNTHETIC_FEW_SHOT_PREFIX class MedicalBilling(BaseModel): patient_id: int patient_name: str diagnosis_code: str procedure_code: str total_charge: float insurance_claim_amount: float examples = [ {"example": """Patient ID: 123456, Patient Name: John Doe, Diagnosis Code: J20.9, Procedure Code: 99203, Total Charge: $500, Insurance Claim Amount: $350"""}, {"example": """Patient ID: 789012, Patient Name: Johnson Smith, Diagnosis Code: M54.5, Procedure Code: 99213, Total Charge: $150, Insurance Claim Amount: $120"""}, {"example": """Patient ID: 345678, Patient Name: Emily Stone, Diagnosis Code: E11.9, Procedure Code: 99214, Total Charge: $300, Insurance Claim Amount: $250"""}, ] OPENAI_TEMPLATE = PromptTemplate(input_variables=["example"], template="{example}") prompt_template = FewShotPromptTemplate( prefix=SYNTHETIC_FEW_SHOT_PREFIX, examples=examples, suffix=SYNTHETIC_FEW_SHOT_SUFFIX, input_variables=["subject", "extra"], example_prompt=OPENAI_TEMPLATE, ) from langchain_community.llms import VLLMOpenAI llm = VLLMOpenAI( openai_api_key="EMPTY", openai_api_base="http://localhost:8000/v1", model_name="meta-llama/meta-llama-3-8B-Instruct", ) synthetic_data_generator = create_openai_data_generator( output_schema=MedicalBilling, llm=llm, prompt=prompt_template, ) synthetic_results = synthetic_data_generator.generate( subject="medical_billing", extra="the name must be chosen at random. Make it something you wouldn't normally choose.", runs=1, ) ``` ### Error Message and Stack Trace (if applicable) ``` { "name": "TypeError", "message": "Completions.create() got an unexpected keyword argument 'functions'", "stack": "--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[10], line 21 13 # os.environ['OPENAI_API_KEY'] = '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' 15 synthetic_data_generator = create_openai_data_generator( 16 output_schema=MedicalBilling, 17 llm=llm, 18 prompt=prompt_template, 19 ) ---> 21 synthetic_results = synthetic_data_generator.generate( 22 subject=\"medical_billing\", 23 extra=\"the name must be chosen at random. Make it something you wouldn't normally choose.\", 24 runs=1, 25 ) File ~/home/.venv/lib/python3.10/site-packages/langchain_experimental/tabular_synthetic_data/base.py:96, in SyntheticDataGenerator.generate(self, subject, runs, *args, **kwargs) 91 raise ValueError( 92 \"llm_chain is none, either set either llm_chain or llm at generator \" 93 \"construction\" 94 ) 95 for _ in range(runs): ---> 96 result = self.llm_chain.run(subject=subject, *args, **kwargs) 97 self.results.append(result) 98 self._update_examples(result) File ~/home/.venv/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:148, in deprecated.<locals>.deprecate.<locals>.warning_emitting_wrapper(*args, **kwargs) 146 warned = True 147 emit_warning() --> 148 return wrapped(*args, **kwargs) File ~/home/.venv/lib/python3.10/site-packages/langchain/chains/base.py:574, in Chain.run(self, callbacks, tags, metadata, *args, **kwargs) 569 return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[ 570 _output_key 571 ] 573 if kwargs and not args: --> 574 return self(kwargs, callbacks=callbacks, tags=tags, metadata=metadata)[ 575 _output_key 576 ] 578 if not kwargs and not args: 579 raise ValueError( 580 \"`run` supported with either positional arguments or keyword arguments,\" 581 \" but none were provided.\" 582 ) File ~/home/.venv/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:148, in deprecated.<locals>.deprecate.<locals>.warning_emitting_wrapper(*args, **kwargs) 146 warned = True 147 emit_warning() --> 148 return wrapped(*args, **kwargs) File ~/home/.venv/lib/python3.10/site-packages/langchain/chains/base.py:378, in Chain.__call__(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info) 346 \"\"\"Execute the chain. 347 348 Args: (...) 369 `Chain.output_keys`. 370 \"\"\" 371 config = { 372 \"callbacks\": callbacks, 373 \"tags\": tags, 374 \"metadata\": metadata, 375 \"run_name\": run_name, 376 } --> 378 return self.invoke( 379 inputs, 380 cast(RunnableConfig, {k: v for k, v in config.items() if v is not None}), 381 return_only_outputs=return_only_outputs, 382 include_run_info=include_run_info, 383 ) File ~/home/.venv/lib/python3.10/site-packages/langchain/chains/base.py:163, in Chain.invoke(self, input, config, **kwargs) 161 except BaseException as e: 162 run_manager.on_chain_error(e) --> 163 raise e 164 run_manager.on_chain_end(outputs) 166 if include_run_info: File ~/home/.venv/lib/python3.10/site-packages/langchain/chains/base.py:153, in Chain.invoke(self, input, config, **kwargs) 150 try: 151 self._validate_inputs(inputs) 152 outputs = ( --> 153 self._call(inputs, run_manager=run_manager) 154 if new_arg_supported 155 else self._call(inputs) 156 ) 158 final_outputs: Dict[str, Any] = self.prep_outputs( 159 inputs, outputs, return_only_outputs 160 ) 161 except BaseException as e: File ~/home/.venv/lib/python3.10/site-packages/langchain/chains/llm.py:103, in LLMChain._call(self, inputs, run_manager) 98 def _call( 99 self, 100 inputs: Dict[str, Any], 101 run_manager: Optional[CallbackManagerForChainRun] = None, 102 ) -> Dict[str, str]: --> 103 response = self.generate([inputs], run_manager=run_manager) 104 return self.create_outputs(response)[0] File ~/home/.venv/lib/python3.10/site-packages/langchain/chains/llm.py:115, in LLMChain.generate(self, input_list, run_manager) 113 callbacks = run_manager.get_child() if run_manager else None 114 if isinstance(self.llm, BaseLanguageModel): --> 115 return self.llm.generate_prompt( 116 prompts, 117 stop, 118 callbacks=callbacks, 119 **self.llm_kwargs, 120 ) 121 else: 122 results = self.llm.bind(stop=stop, **self.llm_kwargs).batch( 123 cast(List, prompts), {\"callbacks\": callbacks} 124 ) File ~/home/.venv/lib/python3.10/site-packages/langchain_core/language_models/llms.py:633, in BaseLLM.generate_prompt(self, prompts, stop, callbacks, **kwargs) 625 def generate_prompt( 626 self, 627 prompts: List[PromptValue], (...) 630 **kwargs: Any, 631 ) -> LLMResult: 632 prompt_strings = [p.to_string() for p in prompts] --> 633 return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs) File ~/home/.venv/lib/python3.10/site-packages/langchain_core/language_models/llms.py:803, in BaseLLM.generate(self, prompts, stop, callbacks, tags, metadata, run_name, run_id, **kwargs) 788 if (self.cache is None and get_llm_cache() is None) or self.cache is False: 789 run_managers = [ 790 callback_manager.on_llm_start( 791 dumpd(self), (...) 801 ) 802 ] --> 803 output = self._generate_helper( 804 prompts, stop, run_managers, bool(new_arg_supported), **kwargs 805 ) 806 return output 807 if len(missing_prompts) > 0: File ~/home/.venv/lib/python3.10/site-packages/langchain_core/language_models/llms.py:670, in BaseLLM._generate_helper(self, prompts, stop, run_managers, new_arg_supported, **kwargs) 668 for run_manager in run_managers: 669 run_manager.on_llm_error(e, response=LLMResult(generations=[])) --> 670 raise e 671 flattened_outputs = output.flatten() 672 for manager, flattened_output in zip(run_managers, flattened_outputs): File ~/home/.venv/lib/python3.10/site-packages/langchain_core/language_models/llms.py:657, in BaseLLM._generate_helper(self, prompts, stop, run_managers, new_arg_supported, **kwargs) 647 def _generate_helper( 648 self, 649 prompts: List[str], (...) 653 **kwargs: Any, 654 ) -> LLMResult: 655 try: 656 output = ( --> 657 self._generate( 658 prompts, 659 stop=stop, 660 # TODO: support multiple run managers 661 run_manager=run_managers[0] if run_managers else None, 662 **kwargs, 663 ) 664 if new_arg_supported 665 else self._generate(prompts, stop=stop) 666 ) 667 except BaseException as e: 668 for run_manager in run_managers: File ~/home/.venv/lib/python3.10/site-packages/langchain_community/llms/openai.py:460, in BaseOpenAI._generate(self, prompts, stop, run_manager, **kwargs) 448 choices.append( 449 { 450 \"text\": generation.text, (...) 457 } 458 ) 459 else: --> 460 response = completion_with_retry( 461 self, prompt=_prompts, run_manager=run_manager, **params 462 ) 463 if not isinstance(response, dict): 464 # V1 client returns the response in an PyDantic object instead of 465 # dict. For the transition period, we deep convert it to dict. 466 response = response.dict() File ~/home/.venv/lib/python3.10/site-packages/langchain_community/llms/openai.py:115, in completion_with_retry(llm, run_manager, **kwargs) 113 \"\"\"Use tenacity to retry the completion call.\"\"\" 114 if is_openai_v1(): --> 115 return llm.client.create(**kwargs) 117 retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) 119 @retry_decorator 120 def _completion_with_retry(**kwargs: Any) -> Any: File ~/home/.venv/lib/python3.10/site-packages/openai/_utils/_utils.py:275, in required_args.<locals>.inner.<locals>.wrapper(*args, **kwargs) 273 msg = f\"Missing required argument: {quote(missing[0])}\" 274 raise TypeError(msg) --> 275 return func(*args, **kwargs) TypeError: Completions.create() got an unexpected keyword argument 'functions'" } ``` ### Description The synthetic data generator seems to be working only when `llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)`. When I switched it to point to the vLLM API server as shown in the code is when it starts to fail. ### System Info **Platform:** Linux **Python:** 3.10 **Package versions:** ```langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.45 langchain-experimental==0.0.57 langchain-openai==0.0.5 langchain-text-splitters==0.0.1```
TypeError: Completions.create() got an unexpected keyword argument 'functions' when running Synthetic data generator over vLLM
https://api.github.com/repos/langchain-ai/langchain/issues/20895/comments
1
2024-04-25T16:38:32Z
2024-08-04T16:08:01Z
https://github.com/langchain-ai/langchain/issues/20895
2,264,034,401
20,895
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code The following Code doesn't register the cited_answer citations object: ```python import os from operator import itemgetter from typing import List, Optional from uuid import UUID from langchain.chains import ConversationalRetrievalChain from langchain.embeddings.ollama import OllamaEmbeddings from langchain.llms.base import BaseLLM from langchain.prompts import HumanMessagePromptTemplate, SystemMessagePromptTemplate from langchain.retrievers import ContextualCompressionRetriever from langchain.retrievers.document_compressors import FlashrankRerank from langchain.schema import format_document from langchain_cohere import CohereRerank from langchain_community.chat_models import ChatLiteLLM from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate, PromptTemplate from langchain_core.pydantic_v1 import Field as FieldV1 from langchain_core.runnables import RunnableLambda, RunnablePassthrough from langchain_openai import ChatOpenAI, OpenAIEmbeddings from logger import get_logger from models import BrainSettings # Importing settings related to the 'brain' from modules.brain.service.brain_service import BrainService from modules.chat.service.chat_service import ChatService from modules.prompt.service.get_prompt_to_use import get_prompt_to_use from pydantic import BaseModel, ConfigDict from pydantic_settings import BaseSettings from supabase.client import Client, create_client from vectorstore.supabase import CustomSupabaseVectorStore logger = get_logger(__name__) class cited_answer(BaseModel): """Answer the user question based only on the given sources, and cite the sources used.""" answer: str = FieldV1( ..., description="The answer to the user question, which is based only on the given sources.", ) citations: List[int] = FieldV1( ..., description="The integer IDs of the SPECIFIC sources which justify the answer.", ) ``` ### Error Message and Stack Trace (if applicable) Here is the langsmith: <img width="1330" alt="image" src="https://github.com/langchain-ai/langchain/assets/19614572/ff05012b-64b8-4d43-a33c-f1446c1c6386"> And if I don't put List but just Int it works <img width="939" alt="image" src="https://github.com/langchain-ai/langchain/assets/19614572/0397cac7-7aac-40f4-89b1-1cb3f4ac70d2"> ### Description I'm trying to attach a function calling for citation, but List[int] doesn't work. I tried with Pydantic V1 and V2. None seems to work ### System Info langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.45 langchain-openai==0.1.3 langchain-text-splitters==0.0.1 ### Documentation Link I'm based on this documentation https://python.langchain.com/docs/use_cases/question_answering/citations/#cite-documents
List of Int doesn't work in Function Calling
https://api.github.com/repos/langchain-ai/langchain/issues/20890/comments
1
2024-04-25T15:30:43Z
2024-04-27T14:39:28Z
https://github.com/langchain-ai/langchain/issues/20890
2,263,907,640
20,890
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code **import asyncio from semantic_kernel import Kernel as sk from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion, AzureChatCompletion from semantic_kernel.prompt_template import PromptTemplateConfig from semantic_kernel.utils.settings import openai_settings_from_dot_env, azure_openai_settings_from_dot_env** ### Error Message and Stack Trace (if applicable) Exception has occurred: ImportError cannot import name 'PromptTemplateConfig' from 'semantic_kernel.prompt_template' (unknown location) File "C:\Users\TINGLE\Downloads\1\import asyncio.py", line 4, in <module> from semantic_kernel.prompt_template import PromptTemplateConfig ImportError: cannot import name 'PromptTemplateConfig' from 'semantic_kernel.prompt_template' (unknown location) ### Description Getting this error while trying to import the below libraries: ### System Info NA
cannot import name 'PromptTemplateConfig' from 'semantic_kernel.prompt_template' (unknown location)
https://api.github.com/repos/langchain-ai/langchain/issues/20885/comments
1
2024-04-25T10:20:35Z
2024-04-25T14:23:18Z
https://github.com/langchain-ai/langchain/issues/20885
2,263,221,771
20,885
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code llm = ChatOpenAI(temperature=0, model="gpt-4-turbo") document_content_description = "Various documents" retriever = SelfQueryRetriever.from_llm( llm, vectorstore, document_content_description, metadata_field_info, verbose=True, enable_limit=True, search_kwargs={ "k": 10 } ) question = "NVIDIA" context = retriever.invoke(question, verbose=True) print(context) ### Error Message and Stack Trace (if applicable) [Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 1'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 2'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 3'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 4'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 5'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 6'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 7'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 8'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 9'), Document(page_content='Source: NVIDIA', metadata={'title': 'NVIDIA 10') ] ### Description I am trying to retrieve relevant document about NVIDIA, but facing duplication. I am trying to find a way so that I can only receive unique documents from Chroma. I am also open for suggestions like: "use this vectorstore since it supports this". ### System Info langchain==0.1.16 langchain-anthropic==0.1.11 langchain-chroma==0.1.0 langchain-cohere==0.1.4 langchain-community==0.0.33 langchain-core==0.1.45 langchain-experimental==0.0.57 langchain-google-genai==1.0.2 langchain-groq==0.1.3 langchain-mistralai==0.1.2 langchain-openai==0.1.3 langchain-text-splitters==0.0.1 langchainhub==0.1.15
SelfQueryRetriever returning duplicate documents
https://api.github.com/repos/langchain-ai/langchain/issues/20884/comments
0
2024-04-25T09:31:54Z
2024-08-05T16:09:01Z
https://github.com/langchain-ai/langchain/issues/20884
2,263,124,611
20,884
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code Example is taken from [this cookbook](https://github.com/langchain-ai/langchain/blob/master/cookbook/mongodb-langchain-cache-memory.ipynb) ``` import time from langchain_mongodb import MongoDBAtlasVectorSearch from pymongo import MongoClient from langchain_openai import OpenAIEmbeddings from langchain.callbacks.manager import get_openai_callback from langchain_core.globals import set_llm_cache from langchain_mongodb.cache import MongoDBAtlasSemanticCache DB_NAME = "vector-search-db" COLLECTION_NAME = "vector-search" ATLAS_VECTOR_SEARCH_INDEX_NAME = "test-vector-index" MONGODB_URI = "" client = MongoClient(MONGODB_URI, appname="devrel.content.python") collection = client[DB_NAME][COLLECTION_NAME] OPENAI_API_KEY = '' # Using the text-embedding-ada-002 since that's what was used to create embeddings in the movies dataset embeddings = OpenAIEmbeddings( openai_api_key=OPENAI_API_KEY, model="text-embedding-ada-002" ) vector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string=MONGODB_URI, namespace=DB_NAME + "." + COLLECTION_NAME, embedding=embeddings, index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME, ) retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 5}) from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI # Generate context using the retriever, and pass the user question through retrieve = { "context": retriever | (lambda docs: "\n\n".join([d.page_content for d in docs])), "question": RunnablePassthrough(), } template = """Answer the question based only on the following context: \ {context} Question: {question} """ # Defining the chat prompt prompt = ChatPromptTemplate.from_template(template) # Defining the model to be used for chat completion model = ChatOpenAI(temperature=0, openai_api_key=OPENAI_API_KEY) # Parse output as a string parse_output = StrOutputParser() # Naive RAG chain naive_rag_chain = retrieve | prompt | model | parse_output set_llm_cache( MongoDBAtlasSemanticCache( connection_string=MONGODB_URI, embedding=embeddings, collection_name="semantic_cache", database_name=DB_NAME, index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME, wait_until_ready=True, ) ) question = "When formally independence was declared?" with get_openai_callback() as cb: start = time.time() res = naive_rag_chain.invoke(question) end = time.time() if naive_rag_chain: print(res) print("--- cb") print(str(cb) + f"({end - start:.2f} seconds)") else: print('no compressed_docs') with get_openai_callback() as cb: start = time.time() res = naive_rag_chain.invoke(question) end = time.time() if naive_rag_chain: print(res) print("--- cb") print(str(cb) + f"({end - start:.2f} seconds)") else: print('no compressed_docs') ``` ### Error Message and Stack Trace (if applicable) ``` Traceback (most recent call last): File "/home/dmitry/Desktop/vector-search-from-cookbook.py", line 77, in <module> res = naive_rag_chain.invoke(question) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dmitry/.pyenv/versions/3.11.6/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 2499, in invoke input = step.invoke( ^^^^^^^^^^^^ File "/home/dmitry/.pyenv/versions/3.11.6/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 158, in invoke self.generate_prompt( File "/home/dmitry/.pyenv/versions/3.11.6/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 560, in generate_prompt return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dmitry/.pyenv/versions/3.11.6/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 421, in generate raise e File "/home/dmitry/.pyenv/versions/3.11.6/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 411, in generate self._generate_with_cache( File "/home/dmitry/.pyenv/versions/3.11.6/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 651, in _generate_with_cache llm_cache.update(prompt, llm_string, result.generations) File "/home/dmitry/.pyenv/versions/3.11.6/lib/python3.11/site-packages/langchain_mongodb/cache.py", line 293, in update _wait_until(is_indexed, return_val) File "/home/dmitry/.pyenv/versions/3.11.6/lib/python3.11/site-packages/langchain_mongodb/cache.py", line 119, in _wait_until raise TimeoutError("Didn't ever %s" % success_description) TimeoutError: Didn't ever [ChatGeneration(text='Independence was formally declared on July 4, 1776.', generation_info={'finish_reason': 'stop', 'logprobs': None}, message=AIMessage(content='Independence was formally declared on July 4, 1776.', response_metadata={'token_usage': {'completion_tokens': 14, 'prompt_tokens': 639, 'total_tokens': 653}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_c2295e73ad', 'finish_reason': 'stop', 'logprobs': None}, id='run-0295bd5f-b95e-4b85-98ee-f3bcc8a1cdec-0'))] ``` ### Description I was following this Example from [this cookbook](https://github.com/langchain-ai/langchain/blob/master/cookbook/mongodb-langchain-cache-memory.ipynb) I loaded own data (splitted text by paragraphs and uploaded to mongo db with this code (using the same index) ``` text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=0, separators=["\n\n", "\n", "(?<=\. )", " "], length_function=len ) # split by \n docs = text_splitter.split_text(data) print(docs) client = MongoClient(mongodb_conn_string) collection = client[db_name][collection_name] # Insert the documents in MongoDB Atlas with their embedding docsearch = MongoDBAtlasVectorSearch.from_texts( docs, embeddings, collection=collection, index_name=vector_index_name ) ``` So data is uploaded like this: ![image](https://github.com/langchain-ai/langchain/assets/68155915/3138bd2d-9c52-4ef4-964b-9105826b7341) The problem is, that when I don't use `wait_until_ready` param in set_llm_cache, it returns relevant results, BUT without taking it from cache - the executing time is the same: ``` --- cb Tokens Used: 653 Prompt Tokens: 639 Completion Tokens: 14 Successful Requests: 1 Total Cost (USD): $0.0009865(5.72 seconds) Independence was formally declared on July 4, 1776. --- cb Tokens Used: 653 Prompt Tokens: 639 Completion Tokens: 14 Successful Requests: 1 Total Cost (USD): $0.0009865(3.00 seconds) ``` So I ran it multiple times, 5-6 secs remain. I assume we don't wait cache indexing, but with `wait_until_ready` it raises error. Though something is being written in cache collection ![image](https://github.com/langchain-ai/langchain/assets/68155915/f4960177-4a07-46e0-b94f-eeb8b8bf860b) My vector settings ![image](https://github.com/langchain-ai/langchain/assets/68155915/c218afe1-af64-4c8f-9881-74d84f9c5a39) ### System Info ``` langchain==0.1.16 langchain-anthropic==0.1.6 langchain-community==0.0.34 langchain-core==0.1.45 langchain-mongodb==0.1.3 langchain-openai==0.1.3 langchain-text-splitters==0.0.1 ```
set_llm_cache doesn't work. Returns TimeoutError: Didn't ever...
https://api.github.com/repos/langchain-ai/langchain/issues/20882/comments
0
2024-04-25T09:19:37Z
2024-08-01T16:06:59Z
https://github.com/langchain-ai/langchain/issues/20882
2,263,100,253
20,882
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ***importing all required libraries***** spec_json="../..../.json" spec_path=Path(spec) openapi_path=OpenAPISpec.from_file(spec_path) llm=ChatOpenAI(model="gpt-4-32k") spec_chain=get_openapi_chain(spec=openapi_path,llm=llm,header=headers) queryStr="......" spec_chain.invoke(queryStr) ### Error Message and Stack Trace (if applicable) SSLError: HTTPSConnectionPool(host={internal host}, port=443): Max retries exceeded with url : {/..../..../} (Caused by SSLError(SSLCertVerificationError (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed : unable to get the local issuer certificate (_ssl.c:1007)'))) ### Description As a developer, I am using the get_openai_chain function to invoke the OpenAPI spec endpoint depending on consumer query. The internal OpenAPI business endpoint hosted on HTTPS, requires SSL certificate verification. **Expected Behavior:** The consumer submits a query, and get_openai_chain uses this query to interact with the model along with a predefined set of functions specified in the functions parameter. The model may choose to call one of these functions; if it does, the output will be a stringified JSON object that conforms to a custom schema (note: the model may include unexpected parameters). The get_openai_chain function should then parse the string into JSON within your code, and execute your function using the provided arguments using SimpleRequestChain. **Current Scenario:** The consumer submits a query, and get_openai_chain uses this query to interact with the model along with a predefined set of functions specified in the functions parameter. --Passed The model may choose to call one of these functions; if it does, the output will be a stringified JSON object that conforms to a custom schema (note: the model may include unexpected parameters).--Passed The get_openai_chain function should then parse the string into JSON within your code, and execute your function using the provided arguments using SimpleRequestChain.- **Failling** **Issue:** SimpleRequestChain is failing to establish a connection with the OpenAPI spec endpoint, as there is no way to specify the certificate path for SSL verification. ### System Info langchain==0.1.16 langchain-chroma==0.1.0 langchain-community==0.0.33 langchain-core==0.1.43 langchain-openai==0.1.3 langchain-text-splitters==0.0.1 OS: Windows Python Version: 3.10.11
SSL Certificate Verification Issue with get_openai_chain Function in SimpleRequestChain
https://api.github.com/repos/langchain-ai/langchain/issues/20870/comments
2
2024-04-25T02:18:30Z
2024-08-09T16:08:18Z
https://github.com/langchain-ai/langchain/issues/20870
2,262,499,287
20,870
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code When using FAISS, each vector store newly created with `from_texts()` is initialized with zero documents: ```python import langchain_community.embeddings embeddings = langchain_community.embeddings.FakeEmbeddings(size=4) import langchain_community.vectorstores def make_vs(texts): return langchain_community.vectorstores.FAISS.from_texts( texts=texts, embedding=embeddings) vs = make_vs(['a', 'b', 'c']) print([d.page_content for d in vs.similarity_search('z', k=100)]) # >>> returns ['a', 'b', 'c'] vs = make_vs(['d', 'e', 'f']) print([d.page_content for d in vs.similarity_search('z', k=100)]) # >>> returns ['d', 'e', 'f'] ``` But when using Chroma, subsequent vector stores newly created with `from_texts()` still have documents from previous vector stores: ```python import langchain_community.embeddings embeddings = langchain_community.embeddings.FakeEmbeddings(size=4) import langchain_community.vectorstores def make_vs(texts): return langchain_community.vectorstores.Chroma.from_texts( texts=texts, embedding=embeddings) vs = make_vs(['a', 'b', 'c']) print([d.page_content for d in vs.similarity_search('z', k=100)]) # >>> returns ['a', 'b', 'c'] vs = make_vs(['d', 'e', 'f']) print([d.page_content for d in vs.similarity_search('z', k=100)]) # >>> returns ['a', 'b', 'c', 'd', 'e', 'f'] - INCORRECT ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description When I create a new Chroma vector store object with `from_texts()`, documents from previous vector stores are not deleted. The code above shows an example. This occurs regardless of whether I assign to the same variable: ```python vs = make_vs(['a', 'b', 'c']) vs = make_vs(['d', 'e', 'f']) ``` or to different variables: ```python vs1 = make_vs(['a', 'b', 'c']) vs2 = make_vs(['d', 'e', 'f']) ``` or if I try to manually force object destruction: ```python vs = make_vs(['a', 'b', 'c']) del vs vs = make_vs(['d', 'e', 'f']) ``` Only an explicit `delete_collection()` will delete the documents: ```python vs = make_vs(['a', 'b', 'c']) vs.delete_collection() vs = make_vs(['d', 'e', 'f']) ``` but this is a workaround - the vector store is still incorrectly "sticky"; we're just deleting the documents. In addition, this not an easy workaround complex real-world cases where vector store operations are decentralized and called in different scopes. If I want to add content to a vector store, I would use `add_texts()`. If I want to create a new vector store, then I would use `from-texts()` and any previous vector store content should be disregarded by construction. ### System Info System Information ------------------ > OS: Linux > OS Version: #1 SMP Wed Aug 10 16:21:17 UTC 2022 > Python Version: 3.11.0 (main, Nov 10 2022, 08:24:18) [GCC 8.2.0] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.50 > langchain_openai: 0.0.6 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
When using Chroma, vector stores newly created with `from_texts()` do not delete previous documents
https://api.github.com/repos/langchain-ai/langchain/issues/20866/comments
5
2024-04-24T23:23:46Z
2024-08-02T16:07:42Z
https://github.com/langchain-ai/langchain/issues/20866
2,262,342,270
20,866
[ "langchain-ai", "langchain" ]
### Checklist - [X] I added a very descriptive title to this issue. - [X] I included a link to the documentation page I am referring to (if applicable). ### Issue with current documentation: Examples: https://github.com/search?q=repo%3Alangchain-ai%2Flangchain+%22model+%3D+chatAnthropic%22&type=code In several places, we start using an Anthropic model likes this: `model = ChatAnthropic(model='claude-3-opus-20240229')` This is confusing for someone reading the code/docs for 2 reasons: 1. The pattern we typically use elsewhere (sometimes even for using `ChatAnthropic`, is by assigning it to "llm" instead of "model" 2. "model" is a parameter that the downstream user often assigns a particular argument (the specific Anthropic model). This is the primary opportunity for confusion IMO. We are working with a "model" parameter, and also creating an object that is called "model". This is by no means a major issue, but it's something that I came across, and it might be worth addressing for consistency and communication reasons. I am happy to open a PR to address this throughout the repo. ### Idea or request for content: Where possible with reasonable effort (so not messing with too many downstream stuff), change `model = ChatAnthropic(model='...')` to `llm = ChatAnthropic(model='...')` or similar.
DOC: example code, docs, and other spots involving invoking an anthropic model object can be confusing
https://api.github.com/repos/langchain-ai/langchain/issues/20865/comments
1
2024-04-24T23:13:02Z
2024-08-01T16:06:49Z
https://github.com/langchain-ai/langchain/issues/20865
2,262,333,908
20,865
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_chroma import Chroma db = Chroma() db.persist() ``` ### Error Message and Stack Trace (if applicable) ```python AttributeError: 'Chroma' object has no attribute 'persist' ``` ### Description I saw in a langchain-related issue on the Chroma GitHub page that they mention that in Chroma 0.4.x, the persist method no longer exists: https://github.com/chroma-core/chroma/issues/2012#issuecomment-2053917062 Therefore, I believe it should also be removed here: https://github.com/langchain-ai/langchain/blob/87d31a3ec0d4aeb7fe3af90f00511677c38f3a3b/libs/community/langchain_community/vectorstores/chroma.py#L613 ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:10:42 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6000 > Python Version: 3.9.11 (v3.9.11:2de452f8bf, Mar 16 2022, 10:44:40) [Clang 13.0.0 (clang-1300.0.29.30)] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.49 > langchain_chroma: 0.1.0 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
Persist method in Chroma no longer exists in Chroma 0.4.x
https://api.github.com/repos/langchain-ai/langchain/issues/20851/comments
1
2024-04-24T18:57:51Z
2024-04-26T07:36:19Z
https://github.com/langchain-ai/langchain/issues/20851
2,261,971,874
20,851
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code llm = ChatOpenAI( model='gpt-4-0125-preview', temperature=0, max_tokens=4000 ) tools = [self.vector_db_tool] agent = create_openai_tools_agent(llm, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) ### Error Message and Stack Trace (if applicable) peer closed connection without sending complete message body (incomplete chunked read) ### Description I am using latest langchain version. ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:22 PDT 2022; root:xnu-8020.121.3~4/RELEASE_X86_64 > Python Version: 3.12.2 (main, Feb 20 2024, 04:30:04) [Clang 14.0.0 (clang-1400.0.29.202)] Package Information ------------------- > langchain_core: 0.1.42 > langchain: 0.1.16 > langchain_community: 0.0.32 > langsmith: 0.1.47 > langchain_openai: 0.1.3 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
When chat history is long i am getting this error. peer closed connection without sending complete message body (incomplete chunked read)
https://api.github.com/repos/langchain-ai/langchain/issues/20846/comments
0
2024-04-24T17:42:09Z
2024-07-31T16:08:25Z
https://github.com/langchain-ai/langchain/issues/20846
2,261,844,431
20,846
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain.agents.openai_assistant import OpenAIAssistantRunnable assistant = OpenAIAssistantRunnable.create_assistant( name="langchain assistant", instructions="You are a personal math tutor. Write and run code to answer math questions.", tools=[{"type": "code_interpreter"}], model="gpt-4-1106-preview", ) result = assistant.invoke({"content": "What's 10 - 4 raised to the 2.7"}) ### Error Message and Stack Trace (if applicable) Traceback (most recent call last): File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/uvicorn/protocols/http/httptools_impl.py", line 411, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 69, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/fastapi/applications.py", line 1054, in __call__ await super().__call__(scope, receive, send) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/applications.py", line 123, in __call__ await self.middleware_stack(scope, receive, send) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/middleware/errors.py", line 186, in __call__ raise exc File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/middleware/errors.py", line 164, in __call__ await self.app(scope, receive, _send) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 65, in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/_exception_handler.py", line 64, in wrapped_app raise exc File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app await app(scope, receive, sender) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 756, in __call__ await self.middleware_stack(scope, receive, send) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 776, in app await route.handle(scope, receive, send) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 297, in handle await self.app(scope, receive, send) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 77, in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/_exception_handler.py", line 64, in wrapped_app raise exc File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app await app(scope, receive, sender) File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 72, in app response = await func(request) ^^^^^^^^^^^^^^^^^^^ File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/fastapi/routing.py", line 278, in app raw_response = await run_endpoint_function( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/fastapi/routing.py", line 191, in run_endpoint_function return await dependant.call(**values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/home/Repo/ai/main.py", line 16, in read_root return await interact(message.text) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/home/Repo/ai/bot/bot.py", line 16, in interact assistant = OpenAIAssistantRunnable.create_assistant( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/home/Library/Caches/pypoetry/virtualenvs/A5OhnBxC-py3.12/lib/python3.12/site-packages/langchain/agents/openai_assistant/base.py", line 247, in create_assistant assistant = client.beta.assistants.create( ### Description I am trying to create the Open AI Assistant and I se the error: "TypeError: Assistants.create() got an unexpected keyword argument 'file_ids'" ### System Info macos > Python Version: 3.12.3 (main, Apr 9 2024, 08:09:14) [Clang 15.0.0 (clang-1500.3.9.4)] > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.50 > langchain_openai: 0.1.3 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 fastapi: 0.110.2 uvicorn: 0.29.0
Assistants.create() got an unexpected keyword argument 'file_ids'
https://api.github.com/repos/langchain-ai/langchain/issues/20842/comments
3
2024-04-24T17:11:28Z
2024-07-18T12:43:29Z
https://github.com/langchain-ai/langchain/issues/20842
2,261,782,985
20,842
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code I took [this code](https://github.com/langchain-ai/langgraph/blob/470718381407f1d8a7d23ab684eac370e138f2c6/examples/multi_agent/agent_supervisor.ipynb) and replaced OpenAI with anthropic [here](https://github.com/ChristianSch/agents/blob/main/multi-agent/agent_supervisor.py). ### Error Message and Stack Trace (if applicable) This causes 'System message must be at beginning of message list' to be thrown in the `_format_messages` of `chat_models.py`. Full stacktrace: ``` Exception has occurred: ValueError (note: full exception trace is shown but execution is paused at: _run_module_as_main) System message must be at beginning of message list. File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_anthropic/chat_models.py", line 149, in _format_messages raise ValueError("System message must be at beginning of message list.") File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_anthropic/chat_models.py", line 321, in _format_params system, formatted_messages = _format_messages(messages) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_anthropic/chat_models.py", line 444, in _generate params = self._format_params(messages=messages, stop=stop, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 626, in _generate_with_cache result = self._generate( ^^^^^^^^^^^^^^^ File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 417, in generate raise e File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 417, in generate raise e File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 556, in generate_prompt return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py", line 154, in invoke self.generate_prompt( File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 4511, in invoke return self.bound.invoke( ^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langchain_core/runnables/base.py", line 2499, in invoke input = step.invoke( ^^^^^^^^^^^^ File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langgraph/pregel/__init__.py", line 1102, in _panic_or_proceed raise exc File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/site-packages/langgraph/pregel/__init__.py", line 700, in stream _panic_or_proceed(done, inflight, step) File "/Users/christian/dev/agents/multi-agent/agent_supervisor.py", line 154, in <module> for s in graph.stream( File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/runpy.py", line 88, in _run_code exec(code, run_globals) File "/opt/homebrew/Caskroom/miniconda/base/envs/assistant/lib/python3.11/runpy.py", line 198, in _run_module_as_main (Current frame) return _run_code(code, main_globals, None, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: System message must be at beginning of message list. ``` ### Description When using a router for example in a multi-agent scenario or any other scenario where ChatAnthropic is fed with more than one system message, an error is thrown. I deem this a valid scenario though: ![image](https://github.com/langchain-ai/langchain/assets/6138133/60e2085f-edf4-4439-9bda-25440f51826f) ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.3.0: Wed Dec 20 21:30:59 PST 2023; root:xnu-10002.81.5~7/RELEASE_ARM64_T6030 > Python Version: 3.11.5 | packaged by conda-forge | (main, Aug 27 2023, 03:33:12) [Clang 15.0.7 ] Package Information ------------------- > langchain_core: 0.1.42 > langchain: 0.1.16 > langchain_community: 0.0.32 > langsmith: 0.1.47 > langchain_anthropic: 0.1.8 > langchain_experimental: 0.0.57 > langchain_google_genai: 0.0.6 > langchain_openai: 0.0.6 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 > langgraph: 0.0.38 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langserve
ChatAnthropic can't handle mutliple system messages (i.e. for multi-agent scenarios, routers)
https://api.github.com/repos/langchain-ai/langchain/issues/20835/comments
1
2024-04-24T15:02:27Z
2024-07-31T16:08:20Z
https://github.com/langchain-ai/langchain/issues/20835
2,261,519,531
20,835
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python embedding = embed_with_retry( self, input=text, text_type="query", model=self.model )[0]["embedding"] ``` It should be : ```python embedding = embed_with_retry( self, input=[text], text_type="query", model=self.model )[0]["embedding"] ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description If the parameter 'text' passed in is not a list, the string will be iterated continuously in the method _embed_with_retry, and finally the first embedding result will be returned. It seems meaningless, and when the 'text' is long, it will cause request limit, so I think this maybe a bug. ### System Info not related
The embed_query func of DashScopeEmbeddings class has bug
https://api.github.com/repos/langchain-ai/langchain/issues/20830/comments
0
2024-04-24T11:41:46Z
2024-07-31T16:08:15Z
https://github.com/langchain-ai/langchain/issues/20830
2,261,092,145
20,830
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on) doc = """ ```yaml my: foo: bar a: b ``` """ md_header_splits = markdown_splitter.split_text(markdown_document) ``` expected should be ```yaml my: foo: bar a: b ``` actual is ```yaml my: foo: bar a: b ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description Here is a fix that works for whitespaces indents, not sure it covers the tabs though markdown.py: split_text ```python in_code_block = False opening_fence = "" code_block_indent = -1 for line in lines: stripped_line = line.strip() if not in_code_block: # Exclude inline code spans if stripped_line.startswith("```") and stripped_line.count("```") == 1: in_code_block = True opening_fence = "```" code_block_indent = len(line) - len(stripped_line) elif stripped_line.startswith("~~~"): in_code_block = True opening_fence = "~~~" code_block_indent = len(line) - len(stripped_line) else: if stripped_line.startswith(opening_fence): in_code_block = False opening_fence = "" if in_code_block: total_line_indent = len(line) - len(stripped_line) stripped_line = " "*max(0, total_line_indent - code_block_indent) + stripped_line current_content.append(stripped_line) continue ``` ### System Info - Installing typing-extensions (4.11.0) - Downgrading urllib3 (2.2.1 -> 1.26.18) - Installing exceptiongroup (1.2.1) - Installing frozenlist (1.4.1) - Installing h11 (0.14.0) - Installing jsonpointer (2.4) - Installing multidict (6.0.5) - Installing mypy-extensions (1.0.0) - Installing orjson (3.10.1) - Downgrading packaging (24.0 -> 23.2) - Installing pydantic (1.10.15) - Installing six (1.16.0) - Installing sniffio (1.3.1) - Installing aiosignal (1.3.1) - Installing anyio (4.3.0) - Installing asttokens (2.4.1) - Installing async-timeout (4.0.3) - Installing attrs (23.2.0) - Installing executing (2.0.1) - Installing greenlet (3.0.3) - Installing hpack (4.0.0) - Installing httpcore (1.0.5) - Installing hyperframe (6.0.1) - Installing jsonpatch (1.33) - Installing langsmith (0.1.50) - Installing marshmallow (3.21.1) - Installing parso (0.8.4) - Installing pure-eval (0.2.2) - Installing pyyaml (6.0.1) - Installing tenacity (8.2.3) - Installing traitlets (5.14.3) - Installing typing-inspect (0.9.0) - Installing wcwidth (0.2.13) - Installing yarl (1.9.4) - Installing aiohttp (3.9.5) - Installing dataclasses-json (0.6.4) - Installing distro (1.9.0) - Installing decorator (5.1.1) - Installing grpcio (1.62.2) - Installing h2 (4.1.0) - Installing httpx (0.27.0) - Installing jedi (0.19.1) - Installing jupyter-core (5.7.2) - Installing langchain-core (0.1.45) - Installing matplotlib-inline (0.1.7) - Installing numpy (1.26.4) - Installing prompt-toolkit (3.0.43) - Installing protobuf (4.25.3) - Installing pygments (2.17.2) - Installing python-dateutil (2.9.0.post0) - Installing pyzmq (26.0.2) - Installing regex ([202](https://gitlab.com/neural-concept/product/llms/llmops/-/jobs/6703816413#L202)4.4.16) - Updating setuptools (65.5.1 -> 69.5.1) - Installing sqlalchemy (2.0.29) - Installing stack-data (0.6.3) - Installing tornado (6.4) - Installing tqdm (4.66.2) - Installing comm (0.2.2) - Installing debugpy (1.8.1) - Installing grpcio-tools (1.62.2) - Installing ipython (8.23.0) - Installing jupyter-client (8.6.1) - Installing langchain-community (0.0.34) - Installing langchain-text-splitters (0.0.1) - Installing nest-asyncio (1.6.0) - Installing openai (1.23.3) - Installing portalocker (2.8.2) - Installing psutil (5.9.8) - Installing tiktoken (0.6.0) - Installing click (8.1.7) - Installing ipykernel (6.29.4) - Installing langchain (0.1.11) - Installing langchain-openai (0.0.8) - Installing qdrant-client (1.6.4)
Markdown text splitter will remove code block indentation
https://api.github.com/repos/langchain-ai/langchain/issues/20823/comments
0
2024-04-24T09:54:40Z
2024-07-31T16:08:11Z
https://github.com/langchain-ai/langchain/issues/20823
2,260,891,406
20,823
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` ChatLiteLLM max_tokens: int = 256 ChatOpenAI max_tokens: Optional[int] = None ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description My current code cannot detect number of tokens so I don't want to set a specific number for max_tokens value. But in ChatLiteLLM I cannot set max_tokens = None ### System Info langchain==0.1.0 langchain-community==0.0.10 langchain-core==0.1.10 langchain-openai==0.0.2.post1
The max_tokens type of ChatLiteLLM is not consistency with ChatOpenAI
https://api.github.com/repos/langchain-ai/langchain/issues/20816/comments
0
2024-04-24T07:23:41Z
2024-07-31T16:08:05Z
https://github.com/langchain-ai/langchain/issues/20816
2,260,571,804
20,816
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code memory = ConversationBufferMemory( memory_key="chat_history", return_messages=True ) prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful assistant, designed to use tools tell me the distance between cities.", ), ("placeholder", "{chat_history}"), ("human", "{input}"), ("placeholder", "{agent_scratchpad}"), ] ) tools=load_tools(['wolfram-alpha']) agent = create_tool_calling_agent( llm = ChatGroq(temperature=0, model_name="llama3-8b-8192"), tools=tools, prompt=prompt, ) agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory,verbose=True) agent_executor.invoke({"input": "How far is New York City to Tokyo?"}) ### Error Message and Stack Trace (if applicable) Traceback (most recent call last): File "/Users/jay/pythonProject/Wolfram-lc-Groq-llama3.py", line 33, in <module> agent_executor.invoke({"input": "How far is New York City to Tokyo?"}) File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain/chains/base.py", line 163, in invoke raise e File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain/chains/base.py", line 153, in invoke self._call(inputs, run_manager=run_manager) File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain/agents/agent.py", line 1432, in _call next_step_output = self._take_next_step( File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain/agents/agent.py", line 1138, in _take_next_step [ File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain/agents/agent.py", line 1138, in <listcomp> [ File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain/agents/agent.py", line 1166, in _iter_next_step output = self.agent.plan( File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain/agents/agent.py", line 514, in plan for chunk in self.runnable.stream(inputs, config={"callbacks": callbacks}): File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 2875, in stream yield from self.transform(iter([input]), config, **kwargs) File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 2862, in transform yield from self._transform_stream_with_config( File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 1880, in _transform_stream_with_config chunk: Output = context.run(next, iterator) # type: ignore File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 2826, in _transform for output in final_pipeline: File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 1283, in transform for chunk in input: File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 4728, in transform yield from self.bound.transform( File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 1300, in transform yield from self.stream(final, config, **kwargs) File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 249, in stream raise e File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 229, in stream for chunk in self._stream(messages, stop=stop, **kwargs): File "/Users/jay/opt/anaconda3/envs/langchain/lib/python3.10/site-packages/langchain_groq/chat_models.py", line 290, in _stream for rtc in message.additional_kwargs["tool_calls"] KeyError: 'tool_calls' ### Description The tool cannot be called correctly when calling the Groq model through langchain. It would be perfectly fine to switch the model here to gpt3.5, but I would like to use other models like llama3, gemini, etc. It seems that only openai can call multiple tools through proxies very well I guess it may be an agent problem, but I really don't know how to customize a suitable agent to solve the problem ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:41 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T8103 > Python Version: 3.10.12 (main, Jul 5 2023, 15:34:07) [Clang 14.0.6 ] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.38 > langchain_cli: 0.0.21 > langchain_decorators: 0.5.4 > langchain_experimental: 0.0.56 > langchain_google_genai: 1.0.1 > langchain_google_vertexai: 0.1.2 > langchain_groq: 0.1.2 > langchain_openai: 0.1.1 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 > langserve: 0.1.0
The tool cannot be called correctly when calling the Groq model through langchain——KeyError: 'tool_calls'
https://api.github.com/repos/langchain-ai/langchain/issues/20811/comments
9
2024-04-24T04:42:47Z
2024-04-25T13:41:07Z
https://github.com/langchain-ai/langchain/issues/20811
2,260,303,319
20,811
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code vectorstore = OpenSearchVectorSearch( embedding_function=embeddings, index_name="sample-index", opensearch_url="https://localhost:9200", http_auth=("admin","admin"), use_ssl = False, verify_certs = False ) ## Load Ollama LAMA2 LLM model llm=Ollama(model="llama2") from langchain_core.prompts import ChatPromptTemplate prompt = ChatPromptTemplate.from_template(""" Answer the following question based only on the provided context. Think step by step before providing a detailed answer. I will tip you $1000 if the user finds the answer helpful. <context> {context} </context> """) from langchain.chains import RetrievalQA qa_chain = RetrievalQA.from_chain_type( llm, retriever=vectorstore.as_retriever(), chain_type_kwargs={"prompt": prompt} ) question = "Hi" result = qa_chain({"query": question}) print(result["result"]) ### Error Message and Stack Trace (if applicable) result = qa_chain({"query": question}) File "/usr/local/lib/python3.10/site-packages/langchain_core/_api/deprecation.py", line 145, in warning_emitting_wrapper return wrapped(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 378, in __call__ return self.invoke( File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 163, in invoke raise e File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 153, in invoke self._call(inputs, run_manager=run_manager) File "/usr/local/lib/python3.10/site-packages/langchain/chains/retrieval_qa/base.py", line 144, in _call answer = self.combine_documents_chain.run( File "/usr/local/lib/python3.10/site-packages/langchain_core/_api/deprecation.py", line 145, in warning_emitting_wrapper return wrapped(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 550, in run return self(kwargs, callbacks=callbacks, tags=tags, metadata=metadata)[ File "/usr/local/lib/python3.10/site-packages/langchain_core/_api/deprecation.py", line 145, in warning_emitting_wrapper return wrapped(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 378, in __call__ return self.invoke( File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 163, in invoke raise e File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 153, in invoke self._call(inputs, run_manager=run_manager) File "/usr/local/lib/python3.10/site-packages/langchain/chains/combine_documents/base.py", line 137, in _call output, extra_return_dict = self.combine_docs( File "/usr/local/lib/python3.10/site-packages/langchain/chains/combine_documents/stuff.py", line 244, in combine_docs return self.llm_chain.predict(callbacks=callbacks, **inputs), {} File "/usr/local/lib/python3.10/site-packages/langchain/chains/llm.py", line 293, in predict return self(kwargs, callbacks=callbacks)[self.output_key] File "/usr/local/lib/python3.10/site-packages/langchain_core/_api/deprecation.py", line 145, in warning_emitting_wrapper return wrapped(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 378, in __call__ return self.invoke( File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 163, in invoke raise e File "/usr/local/lib/python3.10/site-packages/langchain/chains/base.py", line 153, in invoke self._call(inputs, run_manager=run_manager) File "/usr/local/lib/python3.10/site-packages/langchain/chains/llm.py", line 103, in _call response = self.generate([inputs], run_manager=run_manager) File "/usr/local/lib/python3.10/site-packages/langchain/chains/llm.py", line 115, in generate return self.llm.generate_prompt( File "/usr/local/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 569, in generate_prompt return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs) File "/usr/local/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 748, in generate output = self._generate_helper( File "/usr/local/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 606, in _generate_helper raise e File "/usr/local/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 593, in _generate_helper self._generate( File "/usr/local/lib/python3.10/site-packages/langchain_community/llms/ollama.py", line 421, in _generate final_chunk = super()._stream_with_aggregation( File "/usr/local/lib/python3.10/site-packages/langchain_community/llms/ollama.py", line 330, in _stream_with_aggregation for stream_resp in self._create_generate_stream(prompt, stop, **kwargs): File "/usr/local/lib/python3.10/site-packages/langchain_community/llms/ollama.py", line 172, in _create_generate_stream yield from self._create_stream( File "/usr/local/lib/python3.10/site-packages/langchain_community/llms/ollama.py", line 233, in _create_stream response = requests.post( File "/usr/local/lib/python3.10/site-packages/requests/api.py", line 115, in post return request("post", url, data=data, json=json, **kwargs) File "/usr/local/lib/python3.10/site-packages/requests/api.py", line 59, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python3.10/site-packages/requests/sessions.py", line 589, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.10/site-packages/requests/sessions.py", line 703, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.10/site-packages/requests/adapters.py", line 519, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=11434): Max retries exceeded with url: /api/generate (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2aa40c85b0>: Failed to establish a new connection: [Errno 111] Connection refused')) ### Description If I do a similarity search, it works but with the retrieval QA it gives this error. Seems bizzare. ### System Info langchain==0.1.13 langchain-community==0.0.29 langchain-core==0.1.33 langchain-text-splitters==0.0.1 llama-index-embeddings-langchain==0.1.2 llama-index-llms-langchain==0.1.3
Opensearch with Retrieval QA doesn't work
https://api.github.com/repos/langchain-ai/langchain/issues/20809/comments
0
2024-04-24T00:56:19Z
2024-07-31T16:08:00Z
https://github.com/langchain-ai/langchain/issues/20809
2,260,042,490
20,809
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python model_id = "meta.llama2-70b-chat-v1" llm = BedrockChat(model_id=model_id, model_kwargs={"temperature": 0.5}) llm.get_num_tokens("this is a text") ``` ### Error Message and Stack Trace (if applicable) '(MaxRetryError("HTTPSConnectionPool(host='huggingface.co', port=443): Max retries exceeded with url: /gpt2/resolve/main/tokenizer_config.json (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x7f55346aa800>, 'Connection to huggingface.co timed out. (connect timeout=10)'))"), '(Request ID: *****')' thrown while requesting HEAD https://huggingface.co/gpt2/resolve/main/tokenizer_config.json ### Description I noticed BedrockChat is using GPT2 Tokenizer rather than LlamaTokenizer for the meta.llama2-70b-chat-v1 model I first found this out when using Langchain in a network-isolated environment and was getting this error, where it's try to download gpt2 tokenizer_config, The network error itself is not the problem but rather BedRockChat is not using the right tokenizer when doing token count. The code snippet I was executing was this. I traced back to to the parent class [BaseLanguageModel](https://github.com/langchain-ai/langchain/blob/master/libs/core/langchain_core/language_models/base.py) and noticed it is in fact using GPT2 Tokenizer. ### System Info `!pip freeze | grep langchain` ``` langchain==0.1.16 langchain-community==0.0.33 langchain-core==0.1.45 langchain-text-splitters==0.0.1 langchainplus-sdk==0.0.20 ```
BedrockChat is using GPT2 Tokenzier rather than LlamaTokenizer
https://api.github.com/repos/langchain-ai/langchain/issues/20807/comments
1
2024-04-23T23:11:22Z
2024-07-31T16:07:55Z
https://github.com/langchain-ai/langchain/issues/20807
2,259,927,888
20,807
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_community.callbacks import get_openai_callback from langchain_openai import OpenAIEmbeddings model = OpenAIEmbeddings(model="text-embedding-3-small") with get_openai_callback() as cb: model.embed_documents(["Hello world"]) print(cb) ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description The `get_openai_callback` does not record token usages and costs when OpenAIEmbedding is used, reporting: ```text Tokens Used: 0 Prompt Tokens: 0 Completion Tokens: 0 Successful Requests: 0 Total Cost (USD): $0.0 ``` instead of ``` Tokens Used: 2 Prompt Tokens: 2 Completion Tokens: 0 Successful Requests: 1 Total Cost (USD): $2e-07 ``` ### System Info ``` System Information ------------------ > OS: Linux > OS Version: #1 SMP PREEMPT_DYNAMIC Wed, 17 Apr 2024 10:11:09 +0000 > Python Version: 3.11.8 (main, Feb 12 2024, 14:50:05) [GCC 13.2.1 20230801] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.40 > langchain_chroma: 0.1.0 > langchain_openai: 0.1.3 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 > langchainplus_sdk: 0.0.7 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve ```
get_open_ai_callback broken on OpenAIEmbeddings
https://api.github.com/repos/langchain-ai/langchain/issues/20799/comments
0
2024-04-23T18:15:03Z
2024-07-30T16:07:46Z
https://github.com/langchain-ai/langchain/issues/20799
2,259,486,717
20,799
[ "langchain-ai", "langchain" ]
Hi
Issuw with passing two prompts as input to `conversationchain`
https://api.github.com/repos/langchain-ai/langchain/issues/20797/comments
5
2024-04-23T17:40:53Z
2024-04-26T13:08:00Z
https://github.com/langchain-ai/langchain/issues/20797
2,259,419,820
20,797
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code Code is bascially: https://python.langchain.com/docs/use_cases/question_answering/chat_history/ but use AzureSearch with async API ```python from langchain_community.vectorstores.azuresearch import AzureSearch retriver = AzureSearch().as_retriever() #... astream = pipeline.astream({"input": user_question}) async for chunk in astream: print(chunk) ``` It results in `NotImplementedError: AzureSearchVectorStoreRetriever does not support async` but it works just fine in the previous version. ### Error Message and Stack Trace (if applicable) ``` 2024-04-23 11:58:15,788 ERROR Exception inside application: 'async_generator' object is not iterable Traceback (most recent call last): File "/app/gpt_exploration/chat.py", line 132, in run_async_query async for chunk in astream: File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4704, in astream async for item in self.bound.astream( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4704, in astream async for item in self.bound.astream( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2900, in astream async for chunk in self.atransform(input_aiter(), config, **kwargs): File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2883, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2853, in _atransform async for output in final_pipeline: File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4740, in atransform async for item in self.bound.atransform( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2883, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2853, in _atransform async for output in final_pipeline: File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/passthrough.py", line 587, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/passthrough.py", line 577, in _atransform yield await first_map_chunk_task ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/utils/aiter.py", line 62, in anext_impl return await __anext__(iterator) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3317, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3304, in _atransform chunk = AddableDict({step_name: task.result()}) ^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3287, in get_next_chunk return await py_anext(generator) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4740, in atransform async for item in self.bound.atransform( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2883, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2853, in _atransform async for output in final_pipeline: File "/usr/local/lib/python3.12/site-packages/langchain_core/output_parsers/transform.py", line 60, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1943, in _atransform_stream_with_config final_input: Optional[Input] = await py_anext(input_for_tracing, None) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/utils/aiter.py", line 62, in anext_impl return await __anext__(iterator) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/utils/aiter.py", line 97, in tee_peer item = await iterator.__anext__() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1316, in atransform async for chunk in input: File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1316, in atransform async for chunk in input: File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4740, in atransform async for item in self.bound.atransform( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/passthrough.py", line 587, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/passthrough.py", line 577, in _atransform yield await first_map_chunk_task ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/utils/aiter.py", line 62, in anext_impl return await __anext__(iterator) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3317, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3304, in _atransform chunk = AddableDict({step_name: task.result()}) ^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3287, in get_next_chunk return await py_anext(generator) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4172, in atransform async for output in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4086, in _atransform async for ichunk in input: File "/usr/local/lib/python3.12/site-packages/langchain_core/utils/aiter.py", line 97, in tee_peer item = await iterator.__anext__() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/utils/aiter.py", line 97, in tee_peer item = await iterator.__anext__() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/utils/aiter.py", line 97, in tee_peer item = await iterator.__anext__() ^^^^^^^^^^^^^^^^^^^^^^^^^^ [Previous line repeated 7 more times] File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/passthrough.py", line 587, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/passthrough.py", line 577, in _atransform yield await first_map_chunk_task ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/utils/aiter.py", line 62, in anext_impl return await __anext__(iterator) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3317, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3304, in _atransform chunk = AddableDict({step_name: task.result()}) ^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 3287, in get_next_chunk return await py_anext(generator) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 4740, in atransform async for item in self.bound.atransform( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1333, in atransform async for output in self.astream(final, config, **kwargs): File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/branch.py", line 380, in astream async for chunk in runnable.astream( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2900, in astream async for chunk in self.atransform(input_aiter(), config, **kwargs): File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2883, in atransform async for chunk in self._atransform_stream_with_config( File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1979, in _atransform_stream_with_config chunk: Output = await asyncio.create_task( # type: ignore[call-arg] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 2853, in _atransform async for output in final_pipeline: File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 1333, in atransform async for output in self.astream(final, config, **kwargs): File "/usr/local/lib/python3.12/site-packages/langchain_core/runnables/base.py", line 820, in astream yield await self.ainvoke(input, config, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/retrievers.py", line 227, in ainvoke return await self.aget_relevant_documents( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_core/retrievers.py", line 384, in aget_relevant_documents raise e File "/usr/local/lib/python3.12/site-packages/langchain_core/retrievers.py", line 377, in aget_relevant_documents result = await self._aget_relevant_documents( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/langchain_community/vectorstores/azuresearch.py", line 735, in _aget_relevant_documents raise NotImplementedError( NotImplementedError: AzureSearchVectorStoreRetriever does not support async During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/asgiref/sync.py", line 518, in thread_handler raise exc_info[1] File "/usr/local/lib/python3.12/site-packages/django/http/response.py", line 514, in __aiter__ async for part in self.streaming_content: File "/usr/local/lib/python3.12/site-packages/django/http/response.py", line 471, in awrapper async for part in _iterator: File "/app/gpt_exploration/chat.py", line 152, in run_async_query store_data(session_id, answer_id, user_question, answer, answer_time, doc_context['context'], configuration_id) ~~~~~~~~~~~^^^^^^^^^^^ TypeError: 'NoneType' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/django/core/handlers/asgi.py", line 170, in __call__ await self.handle(scope, receive, send) File "/usr/local/lib/python3.12/site-packages/django/core/handlers/asgi.py", line 209, in handle task.result() File "/usr/local/lib/python3.12/site-packages/django/core/handlers/asgi.py", line 193, in process_request await self.send_response(response, send) File "/usr/local/lib/python3.12/site-packages/django/core/handlers/asgi.py", line 325, in send_response async for part in content: File "/usr/local/lib/python3.12/site-packages/django/http/response.py", line 524, in __aiter__ for part in await sync_to_async(list)(self.streaming_content): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/asgiref/sync.py", line 468, in __call__ ret = await asyncio.shield(exec_coro) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/asgiref/sync.py", line 520, in thread_handler return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ TypeError: 'async_generator' object is not iterable ``` ### Description This is a regression, installing `langchain-community==0.0.33` fixes the issue, installing `langchain-community==0.0.34` breaks. ### System Info langchain==0.1.8 # 0.0.33 works langchain-community==0.0.34 langchain-core==0.1.44 langchain-openai==0.0.6
langchain community 0.0.34 NotImplementedError: AzureSearchVectorStoreRetriever does not support async - working in 0.0.33
https://api.github.com/repos/langchain-ai/langchain/issues/20787/comments
1
2024-04-23T12:38:16Z
2024-08-05T16:08:51Z
https://github.com/langchain-ai/langchain/issues/20787
2,258,773,796
20,787
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code import os from common import constants from langchain.chat_models import ChatOpenAI from langchain.chains import ConversationChain from langchain.memory import ConversationBufferMemory chat = ChatOpenAI( base_url=constants.BASE_URL, openai_api_key=constants.API_KEY ) # 创建 Memory memory = ConversationBufferMemory(return_messages=True) # 将 Memory 封装到 ConversationChain conversation = ConversationChain(llm=chat, memory=memory) print(conversation.prompt.template) # response = conversation.predict(input="请问中国的首都是哪里?") # print(response) response = conversation.apply([{"input": "请问中国的首都是哪里?"}]) print(response) ### Error Message and Stack Trace (if applicable) Current conversation: {history} Human: {input} AI: Traceback (most recent call last): File "/opt/anaconda3/envs/syxy/lib/python3.8/site-packages/langchain/chains/llm.py", line 157, in apply raise e File "/opt/anaconda3/envs/syxy/lib/python3.8/site-packages/langchain/chains/llm.py", line 154, in apply response = self.generate(input_list, run_manager=run_manager) File "/opt/anaconda3/envs/syxy/lib/python3.8/site-packages/langchain/chains/llm.py", line 78, in generate prompts, stop = self.prep_prompts(input_list, run_manager=run_manager) File "/opt/anaconda3/envs/syxy/lib/python3.8/site-packages/langchain/chains/llm.py", line 105, in prep_prompts selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} File "/opt/anaconda3/envs/syxy/lib/python3.8/site-packages/langchain/chains/llm.py", line 105, in <dictcomp> selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} KeyError: 'history' python-BaseException ### Description 调用predict方法可以正常执行 调用apply方法报错,没有history key history key 是memory 的key apply方法 没有经过chain的 __call__方法 直接调用llm 的generate_prompt方法 导致了报错 ### System Info langchain @ file:///home/conda/feedstock_root/build_artifacts/langchain_1685957913682/work langchain-core @ file:///home/conda/feedstock_root/build_artifacts/langchain-core_1703029179104/work macos python 3.8.5
Langchain ConversationChain.apply 没有加载memory 中的key导致了key error
https://api.github.com/repos/langchain-ai/langchain/issues/20785/comments
3
2024-04-23T09:52:20Z
2024-04-25T04:18:47Z
https://github.com/langchain-ai/langchain/issues/20785
2,258,441,588
20,785
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python def load_chat_template() -> ChatPromptTemplate: """ Loads and returns a Langchain ChatPromptTemplate, initiated with system & user messages. Expects to find the templates within a subdirectory named 'prompts' and the system prompt template is named 'system.jinja2'. Returns: ChatPromptTemplate: Configured chat prompt template with system and user messages, including a placeholder for agent messages. """ cwd = Path(__file__).parent system_prompt = PromptTemplate.from_file(cwd / "prompts" / "system.jinja2", template_format="jinja2") return ChatPromptTemplate.from_messages( [ ("system", system_prompt.format()), ("user", "{input}"), MessagesPlaceholder(variable_name="agent_scratchpad"), ] ) llm = AzureChatOpenAI( api_key=config.api_key, api_version=config.azure_openai_api_version, azure_endpoint=config.azure_openai_endpoint, azure_deployment=config.azure_openai_deployment_name, ) chat_template = load_chat_template() # Create a list of custom tools to be used by the agent # Replace this with some sample tools # Output: List[BaseTool] tools = prepare_tools(self._search_service) # Reference https://python.langchain.com/docs/modules/agents/agent_types/openai_tools/ agent = create_openai_tools_agent(llm, tools, chat_template) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=init_config().rag_agent_verbose) if isinstance(agent_executor.agent, RunnableMultiActionAgent): # BUG: This prints true always print(f"Agent is set to stream: {agent_executor.agent.stream_runnable}") return agent_executor.invoke({"input": input_prompt}) ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description In the `AzureChatOpenAI` model streaming is set to false, but in the `agent_executor.stream_runnable` is always set to true and it never inherits the value from `AzureChatOpenAI`, which I'd expect it to. Maybe that expectation is incorrect? Is this an intended behavior? The way I've found to disable streaming is by setting it manually false after the `AgentExecutor` is returned, like so: ```python if isinstance(agent_executor.agent, RunnableMultiActionAgent): agent_executor.agent.stream_runnable = False ``` This actually disables streaming. Is there a better way to do this? In my use case, I wanted to disable streaming so that I could enable caching for tools as OpenAI streaming implementation doesn't implement caching. ### System Info ```sh $ pip freeze | grep langchain langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.45 langchain-openai==0.1.3 langchain-text-splitters==0.0.1 langchainhub==0.1.15 opentelemetry-instrumentation-langchain==0.14.5 ``` --- Discovered the issue with @quovadim
RunnableMultiActionAgent enable streaming by default even if disabled in the LLM
https://api.github.com/repos/langchain-ai/langchain/issues/20782/comments
0
2024-04-23T09:22:59Z
2024-07-30T16:07:36Z
https://github.com/langchain-ai/langchain/issues/20782
2,258,380,545
20,782
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python interpreter_assistant = OpenAIAssistantRunnable.create_assistant( name="langchain assistant", instructions="You are a personal math tutor. Write and run code to answer math questions.", tools=[{"type": "code_interpreter"}], model="gpt-4-1106-preview", ) ``` ### Error Message and Stack Trace (if applicable) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[24], line 1 ----> 1 interpreter_assistant = OpenAIAssistantRunnable.create_assistant( 2 name="langchain assistant", 3 instructions="You are a personal math tutor. Write and run code to answer math questions.", 4 tools=[{"type": "code_interpreter"}], 5 model="gpt-4-1106-preview", 6 ) File [~/python3.11/lib/python3.11/site-packages/langchain/agents/openai_assistant/base.py:247](https://notebook.aratech.cloud/lab/tree/LLM/python3.11/lib/python3.11/site-packages/langchain/agents/openai_assistant/base.py#line=246), in OpenAIAssistantRunnable.create_assistant(cls, name, instructions, tools, model, client, **kwargs) 233 """Create an OpenAI Assistant and instantiate the Runnable. 234 235 Args: (...) 244 OpenAIAssistantRunnable configured to run using the created assistant. 245 """ 246 client = client or _get_openai_client() --> 247 assistant = client.beta.assistants.create( 248 name=name, 249 instructions=instructions, 250 tools=[_get_assistants_tool(tool) for tool in tools], # type: ignore 251 model=model, 252 file_ids=kwargs.get("file_ids"), 253 ) 254 return cls(assistant_id=assistant.id, client=client, **kwargs) TypeError: Assistants.create() got an unexpected keyword argument 'file_ids' ### Description Probably the new OpenAi assistant V2 is not accpeting the file_ids argument. ### System Info System Information ------------------ > OS: Linux > OS Version: #112~20.04.1-Ubuntu SMP Thu Mar 14 14:28:24 UTC 2024 > Python Version: 3.11.9 (main, Apr 6 2024, 17:59:24) [GCC 9.4.0] Package Information ------------------- > langchain_core: 0.1.44 > langchain: 0.1.16 > langchain_community: 0.0.33 > langsmith: 0.1.48 > langchain_experimental: 0.0.57 > langchain_openai: 0.1.3 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
OpenAI assistant new version seems not compatible
https://api.github.com/repos/langchain-ai/langchain/issues/20780/comments
3
2024-04-23T08:21:07Z
2024-05-14T16:22:45Z
https://github.com/langchain-ai/langchain/issues/20780
2,258,255,673
20,780
[ "langchain-ai", "langchain" ]
### Privileged issue - [X] I am a LangChain maintainer, or was asked directly by a LangChain maintainer to create an issue here. ### Issue Content --> 248 result = chain({"question": question_with_region, "chat_history": chat_history}) 249 sources = "\n".join(set(map(lambda x: x.metadata["source"], result['source_documents']))) 251 container_sas = self.blob_client.get_container_sas() File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain_core\_api\deprecation.py:148, in deprecated.<locals>.deprecate.<locals>.warning_emitting_wrapper(*args, **kwargs) 146 warned = True 147 emit_warning() --> 148 return wrapped(*args, **kwargs) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain\chains\base.py:378, in Chain.__call__(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info) 346 """Execute the chain. 347 348 Args: (...) 369 `Chain.output_keys`. 370 """ 371 config = { 372 "callbacks": callbacks, 373 "tags": tags, 374 "metadata": metadata, 375 "run_name": run_name, 376 } --> 378 return self.invoke( 379 inputs, 380 cast(RunnableConfig, {k: v for k, v in config.items() if v is not None}), 381 return_only_outputs=return_only_outputs, 382 include_run_info=include_run_info, 383 ) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain\chains\base.py:163, in Chain.invoke(self, input, config, **kwargs) 161 except BaseException as e: 162 run_manager.on_chain_error(e) --> 163 raise e 164 run_manager.on_chain_end(outputs) 166 if include_run_info: File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain\chains\base.py:153, in Chain.invoke(self, input, config, **kwargs) 150 try: 151 self._validate_inputs(inputs) 152 outputs = ( --> 153 self._call(inputs, run_manager=run_manager) 154 if new_arg_supported 155 else self._call(inputs) 156 ) 158 final_outputs: Dict[str, Any] = self.prep_outputs( 159 inputs, outputs, return_only_outputs 160 ) 161 except BaseException as e: File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain\chains\conversational_retrieval\base.py:155, in BaseConversationalRetrievalChain._call(self, inputs, run_manager) 151 accepts_run_manager = ( 152 "run_manager" in inspect.signature(self._get_docs).parameters 153 ) 154 if accepts_run_manager: --> 155 docs = self._get_docs(new_question, inputs, run_manager=_run_manager) 156 else: 157 docs = self._get_docs(new_question, inputs) # type: ignore[call-arg] File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain\chains\conversational_retrieval\base.py:317, in ConversationalRetrievalChain._get_docs(self, question, inputs, run_manager) 309 def _get_docs( 310 self, 311 question: str, (...) 314 run_manager: CallbackManagerForChainRun, 315 ) -> List[Document]: 316 """Get docs.""" --> 317 docs = self.retriever.get_relevant_documents( 318 question, callbacks=run_manager.get_child() 319 ) 320 return self._reduce_tokens_below_limit(docs) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain_core\retrievers.py:321, in BaseRetriever.get_relevant_documents(self, query, callbacks, tags, metadata, run_name, **kwargs) 319 except Exception as e: 320 run_manager.on_retriever_error(e) --> 321 raise e 322 else: 323 run_manager.on_retriever_end( 324 result, 325 ) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain_core\retrievers.py:314, in BaseRetriever.get_relevant_documents(self, query, callbacks, tags, metadata, run_name, **kwargs) 312 _kwargs = kwargs if self._expects_other_args else {} 313 if self._new_arg_supported: --> 314 result = self._get_relevant_documents( 315 query, run_manager=run_manager, **_kwargs 316 ) 317 else: 318 result = self._get_relevant_documents(query, **_kwargs) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain_core\vectorstores.py:696, in VectorStoreRetriever._get_relevant_documents(self, query, run_manager) 692 def _get_relevant_documents( 693 self, query: str, *, run_manager: CallbackManagerForRetrieverRun 694 ) -> List[Document]: 695 if self.search_type == "similarity": --> 696 docs = self.vectorstore.similarity_search(query, **self.search_kwargs) 697 elif self.search_type == "similarity_score_threshold": 698 docs_and_similarities = ( 699 self.vectorstore.similarity_search_with_relevance_scores( 700 query, **self.search_kwargs 701 ) 702 ) File C:\codespaces\chatbot\stable-code\portal-api\utilities\azuresearch.py:353, in AzureSearch.similarity_search(self, query, k, **kwargs) 340 def similarity_search( 341 self, query: str, k: int = 4, **kwargs: Any 342 ) -> List[Document]: 343 """ 344 Returns the most similar indexed documents to the query text. 345 (...) 351 List[Document]: A list of documents that are most similar to the query text. 352 """ --> 353 docs_and_scores = self.similarity_search_with_score( 354 query, k=k, filters=self.filters) 355 return [doc for doc, _ in docs_and_scores] File C:\codespaces\chatbot\stable-code\portal-api\utilities\azuresearch.py:372, in AzureSearch.similarity_search_with_score(self, query, k, filters) 360 """Return docs most similar to query. 361 362 Args: (...) 367 List of Documents most similar to the query and score for each 368 """ 369 if self.index_name == "embeddings": 370 results = self.client.search( 371 search_text="", --> 372 vector=Vector(value=np.array(self.embedding_function( 373 query), dtype=np.float32).tolist(), k=k, fields=FIELDS_CONTENT_VECTOR), 374 select=[f"{FIELDS_TITLE},{FIELDS_CONTENT},{FIELDS_METADATA}"], 375 filter=filters 376 ) 377 # Convert results to Document objects 378 docs = [ 379 ( 380 Document( (...) 386 for result in results 387 ] File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain_community\embeddings\openai.py:697, in OpenAIEmbeddings.embed_query(self, text) 688 def embed_query(self, text: str) -> List[float]: 689 """Call out to OpenAI's embedding endpoint for embedding query text. 690 691 Args: (...) 695 Embedding for the text. 696 """ --> 697 return self.embed_documents([text])[0] File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain_community\embeddings\openai.py:668, in OpenAIEmbeddings.embed_documents(self, texts, chunk_size) 665 # NOTE: to keep things simple, we assume the list may contain texts longer 666 # than the maximum context and use length-safe embedding function. 667 engine = cast(str, self.deployment) --> 668 return self._get_len_safe_embeddings(texts, engine=engine) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain_community\embeddings\openai.py:494, in OpenAIEmbeddings._get_len_safe_embeddings(self, texts, engine, chunk_size) 492 batched_embeddings: List[List[float]] = [] 493 for i in _iter: --> 494 response = embed_with_retry( 495 self, 496 input=tokens[i : i + _chunk_size], 497 **self._invocation_params, 498 ) 499 if not isinstance(response, dict): 500 response = response.dict() File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain_community\embeddings\openai.py:116, in embed_with_retry(embeddings, **kwargs) 114 """Use tenacity to retry the embedding call.""" 115 if is_openai_v1(): --> 116 return embeddings.client.create(**kwargs) 117 retry_decorator = _create_retry_decorator(embeddings) 119 @retry_decorator 120 def _embed_with_retry(**kwargs: Any) -> Any: File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\resources\embeddings.py:113, in Embeddings.create(self, input, model, dimensions, encoding_format, user, extra_headers, extra_query, extra_body, timeout) 107 embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] 108 base64.b64decode(data), dtype="float32" 109 ).tolist() 111 return obj --> 113 return self._post( 114 "/embeddings", 115 body=maybe_transform(params, embedding_create_params.EmbeddingCreateParams), 116 options=make_request_options( 117 extra_headers=extra_headers, 118 extra_query=extra_query, 119 extra_body=extra_body, 120 timeout=timeout, 121 post_parser=parser, 122 ), 123 cast_to=CreateEmbeddingResponse, 124 ) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py:1233, in SyncAPIClient.post(self, path, cast_to, body, options, files, stream, stream_cls) 1219 def post( 1220 self, 1221 path: str, (...) 1228 stream_cls: type[_StreamT] | None = None, 1229 ) -> ResponseT | _StreamT: 1230 opts = FinalRequestOptions.construct( 1231 method="post", url=path, json_data=body, files=to_httpx_files(files), **options 1232 ) -> 1233 return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py:922, in SyncAPIClient.request(self, cast_to, options, remaining_retries, stream, stream_cls) 913 def request( 914 self, 915 cast_to: Type[ResponseT], (...) 920 stream_cls: type[_StreamT] | None = None, 921 ) -> ResponseT | _StreamT: --> 922 return self._request( 923 cast_to=cast_to, 924 options=options, 925 stream=stream, 926 stream_cls=stream_cls, 927 remaining_retries=remaining_retries, 928 ) File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py:1013, in SyncAPIClient._request(self, cast_to, options, remaining_retries, stream, stream_cls) 1010 err.response.read() 1012 log.debug("Re-raising status error") -> 1013 raise self._make_status_error_from_response(err.response) from None 1015 return self._process_response( 1016 cast_to=cast_to, 1017 options=options, (...) 1020 stream_cls=stream_cls, 1021 ) NotFoundError: Error code: 404 - {'error': {'code': '404', 'message': 'Resource not found'}}
Getting the Issue with the New Langchain version
https://api.github.com/repos/langchain-ai/langchain/issues/20778/comments
2
2024-04-23T08:07:47Z
2024-08-09T15:29:50Z
https://github.com/langchain-ai/langchain/issues/20778
2,258,230,169
20,778
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from langchain.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser system_message = '''You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.''' user_message = '''Question: {question} Context: {context} Answer:''' prompt = PromptTemplate( template=llama3_prompt_template.format(system_message=system_message, user_message=user_message), input_variables=['question', 'context'] ) llm = ChatOllama(model=local_llm, temperature=0) def format_docs(docs): return "\n\n".join([doc.page_content for doc in docs]) rag_chain = prompt | llm | StrOutputParser() question = 'agent memory' docs = retriever.invoke(question) generation = rag_chain.invoke({'question': question, 'context': docs}) print(generation) ### Error Message and Stack Trace (if applicable) ValueError('Ollama call failed with status code 400. Details: {"error":"unexpected server status: 1"}')Traceback (most recent call last): File "/home/darthcoder/miniconda3/envs/LangChain/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 411, in generate self._generate_with_cache( File "/home/darthcoder/miniconda3/envs/LangChain/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 632, in _generate_with_cache result = self._generate( File "/home/darthcoder/miniconda3/envs/LangChain/lib/python3.10/site-packages/langchain_community/chat_models/ollama.py", line 259, in _generate final_chunk = self._chat_stream_with_aggregation( File "/home/darthcoder/miniconda3/envs/LangChain/lib/python3.10/site-packages/langchain_community/chat_models/ollama.py", line 190, in _chat_stream_with_aggregation for stream_resp in self._create_chat_stream(messages, stop, **kwargs): File "/home/darthcoder/miniconda3/envs/LangChain/lib/python3.10/site-packages/langchain_community/chat_models/ollama.py", line 162, in _create_chat_stream yield from self._create_stream( File "/home/darthcoder/miniconda3/envs/LangChain/lib/python3.10/site-packages/langchain_community/llms/ollama.py", line 251, in _create_stream raise ValueError( ValueError: Ollama call failed with status code 400. Details: {"error":"unexpected server status: 1"} ### Description I am implementing this demo - https://github.com/langchain-ai/langgraph/blob/main/examples/rag/langgraph_rag_agent_llama3_local.ipynb - from LangChain's Youtube video The same cell during Generation sometimes runs but sometimes gives the Error 400 This occurs for other code cells too at random ### System Info System Information ------------------ > OS: Linux > OS Version: #1 SMP Thu Jan 11 04:09:03 UTC 2024 > Python Version: 3.10.13 | packaged by conda-forge | (main, Dec 23 2023, 15:36:39) [GCC 12.3.0] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.49 > langchain_chroma: 0.1.0 > langchain_cli: 0.0.21 > langchain_experimental: 0.0.53 > langchain_groq: 0.1.2 > langchain_nomic: 0.0.2 > langchain_pinecone: 0.0.3 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 > langgraph: 0.0.38 > langserve: 0.1.0
Error 400 from Ollama while generation at random cell runs
https://api.github.com/repos/langchain-ai/langchain/issues/20773/comments
9
2024-04-23T06:33:10Z
2024-05-17T04:21:54Z
https://github.com/langchain-ai/langchain/issues/20773
2,258,061,163
20,773
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code PROMPT_TEMPLATE = """Respond to the human as helpfully and accurately as possible. You have access to the following tools: {tools} Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input). Valid "action" values: "Final Answer" or {tool_names} Provide only ONE action per $JSON_BLOB, as shown: ``` {{ "action": $TOOL_NAME, "action_input": $INPUT }} ``` Follow this format: Question: input question to answer Thought: consider previous and subsequent steps Action: ``` $JSON_BLOB ``` Observation: action result ... (repeat Thought/Action/Observation N times) Thought: I know what to respond Action: ``` {{ "action": "Final Answer", "action_input": "Final response to human" }} Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation''' human = '''{input} ''' """ def create_agent( llm: BaseLanguageModel, tools: list, output_parser: WebCrawleRegexParser, tools_renderer: ToolsRenderer = render_text_description_and_args, **kwargs ): prompt_template = PromptTemplate.from_template( PROMPT_TEMPLATE ) missing_vars = {"tools", "tool_names", "agent_scratchpad"}.difference( prompt_template.input_variables ) if missing_vars: raise ValueError(f"Prompt missing required variables: {missing_vars}") from langchain.agents.format_scratchpad import format_log_to_str prompt = prompt_template.format( tools=tools_renderer(list(tools)), tool_names=", ".join([t.name for t in tools]), ) print(f"prompt={prompt}") stop = ["\nObservation"] llm_with_stop = llm.bind(stop=stop) agent = ( prompt_template| llm_with_stop ) return agent agent = create_web_crawler_agent(llm=llm, tools=tools, output_parser=None) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) ret = agent_executor.invoke({"input": "hi"}) ### Error Message and Stack Trace (if applicable) File "D:\ProgramData\anaconda3\lib\site-packages\langchain\chains\base.py", line 163, in invoke raise e File "D:\ProgramData\anaconda3\lib\site-packages\langchain\chains\base.py", line 153, in invoke self._call(inputs, run_manager=run_manager) File "D:\ProgramData\anaconda3\lib\site-packages\langchain\agents\agent.py", line 1432, in _call next_step_output = self._take_next_step( File "D:\ProgramData\anaconda3\lib\site-packages\langchain\agents\agent.py", line 1138, in _take_next_step [ File "D:\ProgramData\anaconda3\lib\site-packages\langchain\agents\agent.py", line 1138, in <listcomp> [ File "D:\ProgramData\anaconda3\lib\site-packages\langchain\agents\agent.py", line 1166, in _iter_next_step output = self.agent.plan( File "D:\ProgramData\anaconda3\lib\site-packages\langchain\agents\agent.py", line 397, in plan for chunk in self.runnable.stream(inputs, config={"callbacks": callbacks}): File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 2875, in stream yield from self.transform(iter([input]), config, **kwargs) File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 2862, in transform yield from self._transform_stream_with_config( File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 1880, in _transform_stream_with_config chunk: Output = context.run(next, iterator) # type: ignore File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 2826, in _transform for output in final_pipeline: File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 4722, in transform yield from self.bound.transform( File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 1283, in transform for chunk in input: File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 1300, in transform yield from self.stream(final, config, **kwargs) File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 808, in stream yield self.invoke(input, config, **kwargs) File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\prompts\base.py", line 128, in invoke return self._call_with_config( File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\base.py", line 1625, in _call_with_config context.run( File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\runnables\config.py", line 347, in call_func_with_variable_args return func(input, **kwargs) # type: ignore[call-arg] File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\prompts\base.py", line 111, in _format_prompt_with_error_handling _inner_input = self._validate_input(inner_input) File "D:\ProgramData\anaconda3\lib\site-packages\langchain_core\prompts\base.py", line 103, in _validate_input raise KeyError( KeyError: "Input to PromptTemplate is missing variables {'tools', 'tool_names'}. Expected: ['input', 'tool_names', 'tools'] Received: ['input', 'intermediate_steps']" ### Description ### System Info
LangChain's Prompt is like a holy shit design. So many errors when i uesd it in AgentExecutor.Could you improve it ?
https://api.github.com/repos/langchain-ai/langchain/issues/20769/comments
3
2024-04-23T04:14:52Z
2024-07-12T03:09:30Z
https://github.com/langchain-ai/langchain/issues/20769
2,257,904,037
20,769
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code The following code will endlessly print multiple poems and revisions of poems about fish : ```python from langchain_community.chat_models.ollama import ChatOllama llm = ChatOllama(model='llama3:70b') for chunk in llm.stream('Write a poem about fish'): print(chunk.content) ``` This can be solved by adding an explicit stop condition: ```python llm = ChatOllama(model='llama3:70b', stop=["<|eot_id|>"]) ``` Can you please update the `Ollama` and `ChatOllama` elements to include this stop condition for Llama3? ### Error Message and Stack Trace (if applicable) _No response_ ### Description See example code. Generations under Llama3 never terminate ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:49 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6020 > Python Version: 3.11.5 (main, Sep 11 2023, 08:31:25) [Clang 14.0.6 ] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.32 > langsmith: 0.1.43 > langchain_google_vertexai: 0.0.5 > langchain_openai: 0.0.8 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.14 > langserve: 0.0.34 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph
Ollama running Llama3 does not terminate.
https://api.github.com/repos/langchain-ai/langchain/issues/20765/comments
8
2024-04-22T23:31:08Z
2024-08-06T16:08:27Z
https://github.com/langchain-ai/langchain/issues/20765
2,257,628,343
20,765
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain_community.llms import Replicate model = Replicate( model="meta/meta-llama-3-70b-instruct:" + version, model_kwargs={"temperature": 0.2, "max_length": 1024, "top_p": 1}, ) ``` This when compared to directly using Replicate's API within Python: ```python import replicate replicate.run( "meta/meta-llama-3-70b-instruct", input={ "top_p": 0.9, "prompt": prompt, "max_tokens": 512, "min_tokens": 0, "temperature": 0.6, "prompt_template": "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nYou are a helpful assistant<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n", "presence_penalty": 1.15, "frequency_penalty": 0.2 } ) ``` ### Error Message and Stack Trace (if applicable) replicate.exceptions.ReplicateError: ReplicateError Details: title: Invalid version or not permitted status: 422 detail: The specified version does not exist (or perhaps you don't have permission to use it?) ### Description I am trying to use Langchain to use Llama 3 - however, there are no version numbers that are required when I am using Replicate's API directly. There are also no direct ways on the Replicate website to find which specific version number we are using when trying to use replicate. To identify the version number, I queried `https://api.replicate.com/v1/models/meta/meta-llama-3-70b-instruct` as a GET request, and received the `latest_version` in the response. Upon feeding this latest_version into the 'version' variable, I still get the above error message. Two questions: 1. Am I doing something wrong here when invoking the Replicate model using Langchain? 2. Can we get rid of the version number requirement, when Replicate's own API does not require a version number in most scenarios? It could be an optional parameter perhaps. ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:25 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6030 > Python Version: 3.9.18 | packaged by conda-forge | (main, Dec 23 2023, 16:35:41) [Clang 16.0.6 ] Package Information ------------------- > langchain_core: 0.1.42 > langchain: 0.1.16 > langchain_community: 0.0.32 > langsmith: 0.1.46 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
Replicate Version Numbers and issues with running Llama 3 using Langchain's Replicate class
https://api.github.com/repos/langchain-ai/langchain/issues/20757/comments
7
2024-04-22T20:49:46Z
2024-07-31T13:50:12Z
https://github.com/langchain-ai/langchain/issues/20757
2,257,439,971
20,757
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python # main.py import os from typing import Any from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import ChatResult, LLMResult from langchain_core.outputs.chat_generation import ChatGeneration from langchain_openai import ChatOpenAI # bug in langchain.schema.ChatResult class CorrectChatResult(ChatResult): generations: list[list[ChatGeneration]] # type: ignore class WrongTypedAgentCallbackHandler(BaseCallbackHandler): def on_llm_end(self, response: LLMResult, **kwargs: Any) -> Any: print(response.generations[0][0].message) class CorrectAgentCallbackHandler(BaseCallbackHandler): def on_llm_end(self, response: CorrectChatResult, **kwargs: Any) -> Any: print(response.generations[0][0].message) llm = ChatOpenAI( api_key=os.getenv("OPENAI_API_KEY", ""), max_tokens=5, callbacks=[CorrectAgentCallbackHandler(), WrongTypedAgentCallbackHandler()], ) llm.invoke("is mypy helpfull tool?") ``` ```sh mypy main.py ``` ### Error Message and Stack Trace (if applicable) main.py:17: error: "Generation" has no attribute "message" [attr-defined] main.py:21: error: Signature of "on_llm_end" incompatible with supertype "LLMManagerMixin" [override] main.py:21: note: Superclass: main.py:21: note: def on_llm_end(self, response: LLMResult, *, run_id: UUID, parent_run_id: UUID | None = ..., **kwargs: Any) -> Any main.py:21: note: Subclass: main.py:21: note: def on_llm_end(self, response: CorrectChatResult, **kwargs: Any) -> Any main.py:26: error: Argument "api_key" to "ChatOpenAI" has incompatible type "str | SecretStr | None"; expected "SecretStr | None" [arg-type] main.py:26: error: Argument 2 to "getenv" has incompatible type "str"; expected "SecretStr | None" [arg-type] ### Description If I change https://github.com/langchain-ai/langchain/blob/c010ec8b71771dc3f54dc148475c90070b6a7c0b/libs/core/langchain_core/outputs/chat_result.py#L10 to correct type: `List[List[ChatGeneration]]` error get's solved ### System Info *langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.45 langchain-openai==0.0.8 langchain-text-splitters==0.0.1* platform macos python 3.11.7
LangChain.outputs.chat_result.py has wrong type hint
https://api.github.com/repos/langchain-ai/langchain/issues/20744/comments
0
2024-04-22T15:50:43Z
2024-07-29T16:08:32Z
https://github.com/langchain-ai/langchain/issues/20744
2,256,899,035
20,744
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code llm = ChatOpenAI( model_name= "ChatGLM3", # model_path="/dssg/home/acct-medhyq/medhyq-zll/chatGLM3/chatglm3-6b", openai_api_base= "http://localhost:8000/v1", openai_api_key= "EMPTY", streaming= True ) memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) readonlymemory = ReadOnlySharedMemory(memory=memory) cypher_tool = LLMCypherGraphChain( llm=llm, graph=osteosarcoma_graph, verbose=True, memory=readonlymemory) fulltext_tool = LLMKeywordGraphChain( llm=llm, graph=osteosarcoma_graph, verbose=True) vector_tool = LLMNeo4jVectorChain( llm=llm, verbose=True, graph=osteosarcoma_graph ) ### Error Message and Stack Trace (if applicable) 2024-04-22 21:47:15,296 - ERROR - Error: variable agent_scratchpad should be a list of base messages, got Could not parse LLM output: **Action:** Cypher search **Action Input:** "What genes promote the growth of osteosarcoma?" ```json tool_call(action='cypher', action_input='What genes promote the growth of osteosarcoma?') ``` Observation: Invalid or incomplete response Thought:Could not parse LLM output: I apologize for the inconvenience. To answer your question, the genes that promote the growth of osteosarcoma are not fully understood. However, some studies have identified certain genetic mutations that may contribute to the development and progression of osteosarcoma. These include mutations in the CDKN4A and TP53 genes, as well as others. It is important to note that while these genetic changes can increase the risk of developing osteosarcoma, they do not guarantee the disease will occur. Other factors, such as environmental factors and lifestyle choices, may also play a role in the development of osteosarcoma. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I apologize for the confusion earlier. To answer your question, there isn't a specific tool that can determine the response to your question. The response to your question is a complex issue involving genetics and cancer research. A team of experts in the field would need to conduct extensive research and experiments to come to a conclusion. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but as an AI language model, I don't have access to external information and cannot perform actions to look up information. The best course of action would be for you to consult with a medical professional or academic expert in the field of osteosarcoma. They will have access to current research and can provide you with the most accurate and up-to-date information. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I apologize for any confusion. To clarify, there is no one specific tool that can provide a direct answer to your question. However, I can offer some general information on the topic. Osteosarcoma is a type of cancer that affects bones and can arise from several different genetic mutations. Some of these genetic mutations, such as those in the CDKN4A and TP53 genes, have been associated with an increased risk of developing osteosarcoma. Additionally, certain lifestyle factors, such as smoking and excessive alcohol consumption, may also contribute to the development of osteosarcoma. It is important to remember, however, that genetics alone do not determine the development of osteosarcoma and that other factors may also play a role. If you have any further questions, I recommend consulting with a healthcare professional or academic expert in the field of osteosarcoma. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but I cannot perform a tool call as I am not connected to a tool. To answer your question, the response depends on the specific genetic mutations involved in osteosarcoma and the underlying causes of the disease. While there are several known genetic mutations that increase the risk of osteosarcoma, the precise mechanisms by which these mutations contribute to the disease are not yet fully understood. Additionally, there are many other factors that may contribute to the development of osteosarcoma, including environmental and lifestyle factors. Therefore, it is recommended that individuals seeking information on osteosarcoma consult with a medical professional or academic expert for the most accurate and up-to-date information. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but I cannot perform a tool call as I am not connected to a tool. To answer your question, the response to osteosarcoma growth promotion genes varies depending on the specific genetic mutations involved. Some genetic mutations like CDKN4A and TP53 gene mutations can lead to an increased risk of osteosarcoma. However, the exact mechanism by which these mutations contribute to osteosarcoma growth and development is still under investigation. It is recommended to consult with a medical professional or academic expert for the most accurate and up-to-date information on this topic. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but as an AI language model, I don't have access to current research on specific cases and cannot provide a personalized response. The best way to get an accurate answer would be to consult with a medical professional or academic expert who specializes in the field of osteosarcoma. They can provide you with the most up-to-date information and give you personalized advice based on your specific situation. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but I am unable to perform a tool call to retrieve information on the\u57fa\u56e0\u4fc3\u8fdb\u9aa8\u8089\u7624\u751f\u957f\u7684\u54cd\u5e94\u3002\u8bf7\u60a8\u5c1d\u8bd5\u5176\u4ed6\u95ee\u9898\u6216\u5bfb\u6c42\u4e13\u4e1a\u4eba\u58eb\u7684\u5e2e\u52a9\u4ee5\u83b7\u53d6\u66f4\u51c6\u786e\u7684\u7b54\u6848\u3002 Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but I am unable to provide a response to your question as I do not have access to any relevant tools or information. Can you please try again with a different question or seek assistance from a different source? Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but as an AI language model, I don't have access to current research on specific cases and cannot provide a personalized response. The best way to get an accurate answer would be to consult with a medical professional or academic expert who specializes in the field of osteosarcoma. They can provide you with the most up-to-date information and give you personalized advice based on your specific situation. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but as an AI language model, I don't have access to current research on specific cases and cannot provide a personalized response. The best way to get an accurate answer would be to consult with a medical professional or academic expert who specializes in the field of osteosarcoma. They can provide you with the most up-to-date information and give you personalized advice based on your specific situation. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but I cannot provide a response to your question as I am not connected to any relevant tools or information. Please try again with a different question or seek assistance from a different source. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but as an AI language model, I don't have access to current research on specific cases and cannot provide a personalized response. The best way to get an accurate answer would be to consult with a medical professional or academic expert who specializes in the field of osteosarcoma. They can provide you with the most up-to-date information and give you personalized advice based on your specific situation. Observation: Invalid or incomplete response Thought:Could not parse LLM output: I'm sorry, but as an AI language model, I don't have access to current research on specific cases and cannot provide a personalized response. The best way to get an accurate answer would be to consult with a medical professional or academic expert who specializes in the field of osteosarcoma. They can provide you with the most up-to-date information and give you personalized advice based on your specific situation. Observation: Invalid or incomplete response Thought: ### Description When I ask a question, he keeps repeating Observation: Invalid or incomplete response Thought:Could not parse LLM output: ### System Info linux python 3.10 langchain lastest
#could not parser LLM output
https://api.github.com/repos/langchain-ai/langchain/issues/20743/comments
0
2024-04-22T15:39:40Z
2024-07-29T16:08:27Z
https://github.com/langchain-ai/langchain/issues/20743
2,256,871,777
20,743
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code from langchain_community.llms import Ollama llm = Ollama(model="llama3") llm.invoke("Tell me a joke") ### Error Message and Stack Trace (if applicable) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[6], [line 1](vscode-notebook-cell:?execution_count=6&line=1) ----> [1](vscode-notebook-cell:?execution_count=6&line=1) llm.invoke("Tell me a joke") File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:276, in BaseLLM.invoke(self, input, config, stop, **kwargs) [266](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:266) def invoke( [267](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:267) self, [268](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:268) input: LanguageModelInput, (...) [272](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:272) **kwargs: Any, [273](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:273) ) -> str: [274](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:274) config = ensure_config(config) [275](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:275) return ( --> [276](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:276) self.generate_prompt( [277](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:277) [self._convert_input(input)], [278](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:278) stop=stop, [279](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:279) callbacks=config.get("callbacks"), [280](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:280) tags=config.get("tags"), [281](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:281) metadata=config.get("metadata"), [282](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:282) run_name=config.get("run_name"), [283](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:283) run_id=config.pop("run_id", None), [284](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:284) **kwargs, [285](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:285) ) [286](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:286) .generations[0][0] [287](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:287) .text [288](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:288) ) File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:633, in BaseLLM.generate_prompt(self, prompts, stop, callbacks, **kwargs) [625](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:625) def generate_prompt( [626](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:626) self, [627](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:627) prompts: List[PromptValue], (...) [630](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:630) **kwargs: Any, [631](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:631) ) -> LLMResult: [632](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:632) prompt_strings = [p.to_string() for p in prompts] --> [633](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:633) return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs) File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:803, in BaseLLM.generate(self, prompts, stop, callbacks, tags, metadata, run_name, run_id, **kwargs) [788](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:788) if (self.cache is None and get_llm_cache() is None) or self.cache is False: [789](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:789) run_managers = [ [790](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:790) callback_manager.on_llm_start( [791](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:791) dumpd(self), (...) [801](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:801) ) [802](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:802) ] --> [803](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:803) output = self._generate_helper( [804](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:804) prompts, stop, run_managers, bool(new_arg_supported), **kwargs [805](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:805) ) [806](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:806) return output [807](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:807) if len(missing_prompts) > 0: File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:670, in BaseLLM._generate_helper(self, prompts, stop, run_managers, new_arg_supported, **kwargs) [668](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:668) for run_manager in run_managers: [669](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:669) run_manager.on_llm_error(e, response=LLMResult(generations=[])) --> [670](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:670) raise e [671](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:671) flattened_outputs = output.flatten() [672](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:672) for manager, flattened_output in zip(run_managers, flattened_outputs): File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:657, in BaseLLM._generate_helper(self, prompts, stop, run_managers, new_arg_supported, **kwargs) [647](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:647) def _generate_helper( [648](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:648) self, [649](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:649) prompts: List[str], (...) [653](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:653) **kwargs: Any, [654](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:654) ) -> LLMResult: [655](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:655) try: [656](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:656) output = ( --> [657](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:657) self._generate( [658](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:658) prompts, [659](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:659) stop=stop, [660](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:660) # TODO: support multiple run managers [661](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:661) run_manager=run_managers[0] if run_managers else None, [662](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:662) **kwargs, [663](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:663) ) [664](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:664) if new_arg_supported [665](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:665) else self._generate(prompts, stop=stop) [666](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:666) ) [667](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:667) except BaseException as e: [668](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_core/language_models/llms.py:668) for run_manager in run_managers: File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:417, in Ollama._generate(self, prompts, stop, images, run_manager, **kwargs) [415](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:415) generations = [] [416](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:416) for prompt in prompts: --> [417](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:417) final_chunk = super()._stream_with_aggregation( [418](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:418) prompt, [419](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:419) stop=stop, [420](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:420) images=images, [421](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:421) run_manager=run_manager, [422](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:422) verbose=self.verbose, [423](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:423) **kwargs, [424](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:424) ) [425](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:425) generations.append([final_chunk]) [426](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:426) return LLMResult(generations=generations) File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:326, in _OllamaCommon._stream_with_aggregation(self, prompt, stop, run_manager, verbose, **kwargs) [317](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:317) def _stream_with_aggregation( [318](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:318) self, [319](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:319) prompt: str, (...) [323](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:323) **kwargs: Any, [324](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:324) ) -> GenerationChunk: [325](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:325) final_chunk: Optional[GenerationChunk] = None --> [326](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:326) for stream_resp in self._create_generate_stream(prompt, stop, **kwargs): [327](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:327) if stream_resp: [328](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:328) chunk = _stream_response_to_generation_chunk(stream_resp) File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:172, in _OllamaCommon._create_generate_stream(self, prompt, stop, images, **kwargs) [164](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:164) def _create_generate_stream( [165](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:165) self, [166](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:166) prompt: str, (...) [169](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:169) **kwargs: Any, [170](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:170) ) -> Iterator[str]: [171](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:171) payload = {"prompt": prompt, "images": images} --> [172](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:172) yield from self._create_stream( [173](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:173) payload=payload, [174](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:174) stop=stop, [175](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:175) api_url=f"{self.base_url}/api/generate", [176](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:176) **kwargs, [177](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:177) ) File /mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:251, in _OllamaCommon._create_stream(self, api_url, payload, stop, **kwargs) [249](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:249) else: [250](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:250) optional_detail = response.text --> [251](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:251) raise ValueError( [252](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:252) f"Ollama call failed with status code {response.status_code}." [253](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:253) f" Details: {optional_detail}" [254](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:254) ) [255](https://vscode-remote+ssh-002dremote-002b10-002e16-002e22-002e110.vscode-resource.vscode-cdn.net/mnt/nfs/wangyu/Miniconda/envs/RAG/lib/python3.10/site-packages/langchain_community/llms/ollama.py:255) return response.iter_lines(decode_unicode=True) ValueError: Ollama call failed with status code 502. Details: ### Description I ran the instance code, but reported this error. ### System Info System Information ------------------ > OS: Linux > OS Version: #21~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 9 13:32:52 UTC 2 > Python Version: 3.10.14 (main, Mar 21 2024, 16:24:04) [GCC 11.2.0] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.49 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
ValueError: Ollama call failed with status code 502. Details
https://api.github.com/repos/langchain-ai/langchain/issues/20742/comments
9
2024-04-22T15:00:00Z
2024-06-30T15:38:14Z
https://github.com/langchain-ai/langchain/issues/20742
2,256,772,479
20,742
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python import base64 import json import os import vertexai from google.oauth2.service_account import Credentials from langchain_core.messages.human import HumanMessage from langchain_google_vertexai import ChatVertexAI llm_model = ChatVertexAI( model_name="gemini-1.5-pro-preview-0409", convert_system_message_to_human=True, temperature=0.7, ) with open("/Users/david/Downloads/1713170355070_sample_1.mp4", "rb") as f: video_b64 = base64.b64encode(f.read()).decode("utf-8") google_credentials = Credentials.from_service_account_info( json.loads(os.getenv("GCP_LIC"), strict=False) ) vertexai.init( project=os.getenv("GCP_PROJECT_ID"), location=os.getenv("GCP_REGION"), credentials=google_credentials, ) res = llm_model.invoke( [ HumanMessage( content=[ {"type": "text", "text": "Summary of video"}, {"type": "media", "mimeType": "video/mp4", "data": video_b64}, ] ), ] ) print(res) ``` JS Code Example: https://js.langchain.com/docs/use_cases/media ### Error Message and Stack Trace (if applicable) ``` Traceback (most recent call last): File "/Users/david/Documents/test2/langchain_error.py", line 30, in <module> res = llm_model.invoke( File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 158, in invoke self.generate_prompt( File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 560, in generate_prompt return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs) File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 421, in generate raise e File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 411, in generate self._generate_with_cache( File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 632, in _generate_with_cache result = self._generate( File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_google_vertexai/chat_models.py", line 497, in _generate system_instruction, history_gemini = _parse_chat_history_gemini( File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_google_vertexai/chat_models.py", line 215, in _parse_chat_history_gemini parts = _convert_to_parts(message) File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_google_vertexai/chat_models.py", line 166, in _convert_to_parts return [_convert_to_prompt(part) for part in raw_content] File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_google_vertexai/chat_models.py", line 166, in <listcomp> return [_convert_to_prompt(part) for part in raw_content] File "/Users/david/Documents/test2/.venv/lib/python3.10/site-packages/langchain_google_vertexai/chat_models.py", line 160, in _convert_to_prompt raise ValueError("Only text and image_url types are supported!") ValueError: Only text and image_url types are supported! ``` ### Description - I would expect this to work as this sample code is based on JS sample. ### System Info System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.3.0: Wed Dec 20 21:31:00 PST 2023; root:xnu-10002.81.5~7/RELEASE_ARM64_T6020 > Python Version: 3.10.0 (default, Nov 11 2023, 18:46:15) [Clang 15.0.0 (clang-1500.0.40.1)] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.49 > langchain_anthropic: 0.1.11 > langchain_error: Installed. No version info available. > langchain_google_vertexai: 1.0.1 > langchain_openai: 0.0.8 > langchain_text_splitters: 0.0.1 > langchainhub: 0.1.15 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve
Vertex AI Gemini video support
https://api.github.com/repos/langchain-ai/langchain/issues/20738/comments
4
2024-04-22T12:42:47Z
2024-05-21T16:54:12Z
https://github.com/langchain-ai/langchain/issues/20738
2,256,441,373
20,738
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python def get_history_chain(llm) -> RunnableWithMessageHistory: chain = history_prompt | llm | debug_in_chain return RunnableWithMessageHistory( chain, get_session_history=lambda session_id: RedisChatMessageHistory(session_id, settings.REDIS_URL), input_messages_key="question", history_messages_key="history", ) ``` where the llm object is an instance of `<class 'langchain_mistralai.chat_models.ChatMistralAI'>` The object passed to the llm in the chain at runtime is an instance of `<class 'langchain_core.prompt_values.ChatPromptValue'>` ### Error Message and Stack Trace (if applicable) ERROR: Exception in ASGI application Traceback (most recent call last): File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/responses.py", line 265, in __call__ await wrap(partial(self.listen_for_disconnect, receive)) File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/responses.py", line 261, in wrap await func() File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/responses.py", line 238, in listen_for_disconnect message = await receive() File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 535, in receive await self.message_event.wait() File "/usr/lib/python3.10/asyncio/locks.py", line 214, in wait await fut asyncio.exceptions.CancelledError: Cancelled by cancel scope 741aaee368c0 During handling of the above exception, another exception occurred: + Exception Group Traceback (most recent call last): | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 407, in run_asgi | result = await app( # type: ignore[func-returns-value] | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 69, in __call__ | return await self.app(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/fastapi/applications.py", line 1054, in __call__ | await super().__call__(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/applications.py", line 123, in __call__ | await self.middleware_stack(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/middleware/errors.py", line 186, in __call__ | raise exc | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/middleware/errors.py", line 164, in __call__ | await self.app(scope, receive, _send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/middleware/cors.py", line 85, in __call__ | await self.app(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 65, in __call__ | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/_exception_handler.py", line 64, in wrapped_app | raise exc | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app | await app(scope, receive, sender) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/routing.py", line 756, in __call__ | await self.middleware_stack(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/routing.py", line 776, in app | await route.handle(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/routing.py", line 297, in handle | await self.app(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/routing.py", line 77, in app | await wrap_app_handling_exceptions(app, request)(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/_exception_handler.py", line 64, in wrapped_app | raise exc | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app | await app(scope, receive, sender) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/routing.py", line 75, in app | await response(scope, receive, send) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/responses.py", line 258, in __call__ | async with anyio.create_task_group() as task_group: | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 678, in __aexit__ | raise BaseExceptionGroup( | exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception) +-+---------------- 1 ---------------- | Traceback (most recent call last): | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/responses.py", line 261, in wrap | await func() | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/starlette/responses.py", line 250, in stream_response | async for chunk in self.body_iterator: | File "/home/jules/workspaces/ai_projects/intern-assistant/assistant_api.py", line 41, in handle_streaming | # print(chunk) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 4704, in astream | async for item in self.bound.astream( | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 4704, in astream | async for item in self.bound.astream( | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 2900, in astream | async for chunk in self.atransform(input_aiter(), config, **kwargs): | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 2883, in atransform | async for chunk in self._atransform_stream_with_config( | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 1984, in _atransform_stream_with_config | chunk = cast(Output, await py_anext(iterator)) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 2853, in _atransform | async for output in final_pipeline: | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 4740, in atransform | async for item in self.bound.atransform( | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 2883, in atransform | async for chunk in self._atransform_stream_with_config( | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 1984, in _atransform_stream_with_config | chunk = cast(Output, await py_anext(iterator)) | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 2853, in _atransform | async for output in final_pipeline: | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/runnables/base.py", line 1333, in atransform | async for output in self.astream(final, config, **kwargs): | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 319, in astream | raise e | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_core/language_models/chat_models.py", line 297, in astream | async for chunk in self._astream( | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_mistralai/chat_models.py", line 455, in _astream | async for chunk in await acompletion_with_retry( | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/langchain_mistralai/chat_models.py", line 124, in _aiter_sse | async for event in event_source.aiter_sse(): | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/httpx_sse/_api.py", line 37, in aiter_sse | self._check_content_type() | File "/home/jules/workspaces/ai_projects/intern-assistant/dev_env/lib/python3.10/site-packages/httpx_sse/_api.py", line 18, in _check_content_type | raise SSEError( | httpx_sse._exceptions.SSEError: Expected response header Content-Type to contain 'text/event-stream', got 'application/json' +------------------------------------ ### Description the exception occurs when i update from langchain-mistralai==0.1.1 to langchain-mistralai==0.1.2 i have debbugged the chain, and the error appears only when calling the llm in the chain. The SSE error comes from the mistralAi client receiving packets from the Api, so i really think that's a bug in the lib. If it's not, i didn't found any documentation on this changes. ### System Info # Working version: `aiohttp==3.9.3` `aiosignal==1.3.1` annotated-types==0.6.0 `anyio==4.3.0` async-timeout==4.0.3 attrs==23.2.0 certifi==2024.2.2 charset-normalizer==3.3.2 click==8.1.7 dataclasses-json==0.6.4 exceptiongroup==1.2.0 faiss-cpu==1.8.0 fastapi==0.110.1 filelock==3.13.4 frozenlist==1.4.1 fsspec==2024.3.1 greenlet==3.0.3 grpcio==1.62.1 grpcio-tools==1.62.1 h11==0.14.0 h2==4.1.0 hpack==4.0.0 `httpcore==1.0.5` `httpx==0.25.2` `httpx-sse==0.4.0` huggingface-hub==0.22.2 hyperframe==6.0.1 idna==3.6 Jinja2==3.1.3 joblib==1.4.0 jsonpatch==1.33 jsonpointer==2.4 `langchain==0.1.15` `langchain-community==0.0.32` `langchain-core==0.1.41` `langchain-mistralai==0.1.1` `langchain-text-splitters==0.0.1` langsmith==0.1.43 MarkupSafe==2.1.5 marshmallow==3.21.1 mistralai==0.1.8 mpmath==1.3.0 multidict==6.0.5 mypy-extensions==1.0.0 networkx==3.3 numpy==1.26.4 nvidia-cublas-cu12==12.1.3.1 nvidia-cuda-cupti-cu12==12.1.105 nvidia-cuda-nvrtc-cu12==12.1.105 nvidia-cuda-runtime-cu12==12.1.105 nvidia-cudnn-cu12==8.9.2.26 nvidia-cufft-cu12==11.0.2.54 nvidia-curand-cu12==10.3.2.106 nvidia-cusolver-cu12==11.4.5.107 nvidia-cusparse-cu12==12.1.0.106 nvidia-nccl-cu12==2.19.3 nvidia-nvjitlink-cu12==12.4.127 nvidia-nvtx-cu12==12.1.105 orjson==3.10.0 packaging==23.2 pandas==2.2.1 pillow==10.3.0 portalocker==2.8.2 protobuf==4.25.3 pyarrow==15.0.2 pydantic==2.6.4 pydantic_core==2.16.3 python-dateutil==2.9.0.post0 python-dotenv==1.0.1 pytz==2024.1 PyYAML==6.0.1 qdrant-client==1.8.2 redis==5.0.3 regex==2023.12.25 requests==2.31.0 safetensors==0.4.2 scikit-learn==1.4.2 scipy==1.13.0 sentence-transformers==2.6.1 six==1.16.0 sniffio==1.3.1 SQLAlchemy==2.0.29 starlette==0.37.2 sympy==1.12 tenacity==8.2.3 threadpoolctl==3.4.0 tokenizers==0.15.2 torch==2.2.2 tqdm==4.66.2 transformers==4.39.3 triton==2.2.0 typing-inspect==0.9.0 typing_extensions==4.11.0 tzdata==2024.1 urllib3==2.2.1 uvicorn==0.29.0 yarl==1.9.4 # Last version not working: `aiohttp==3.9.5` `aiosignal==1.3.1` annotated-types==0.6.0 `anyio==4.3.0` async-timeout==4.0.3 attrs==23.2.0 certifi==2024.2.2 charset-normalizer==3.3.2 click==8.1.7 dataclasses-json==0.6.4 exceptiongroup==1.2.1 faiss-cpu==1.8.0 fastapi==0.110.2 filelock==3.13.4 frozenlist==1.4.1 fsspec==2024.3.1 greenlet==3.0.3 grpcio==1.62.2 grpcio-tools==1.62.2 h11==0.14.0 h2==4.1.0 `hpack==4.0.0` `httpcore==1.0.5` `httpx==0.25.2` `httpx-sse==0.4.0` huggingface-hub==0.22.2 hyperframe==6.0.1 idna==3.7 Jinja2==3.1.3 joblib==1.4.0 jsonpatch==1.33 jsonpointer==2.4 `langchain==0.1.16` `langchain-community==0.0.34` `langchain-core==0.1.45` `langchain-mistralai==0.1.2` `langchain-text-splitters==0.0.1` langsmith==0.1.49 MarkupSafe==2.1.5 marshmallow==3.21.1 mistralai==0.1.8 mpmath==1.3.0 multidict==6.0.5 mypy-extensions==1.0.0 networkx==3.3 numpy==1.26.4 nvidia-cublas-cu12==12.1.3.1 nvidia-cuda-cupti-cu12==12.1.105 nvidia-cuda-nvrtc-cu12==12.1.105 nvidia-cuda-runtime-cu12==12.1.105 nvidia-cudnn-cu12==8.9.2.26 nvidia-cufft-cu12==11.0.2.54 nvidia-curand-cu12==10.3.2.106 nvidia-cusolver-cu12==11.4.5.107 nvidia-cusparse-cu12==12.1.0.106 nvidia-nccl-cu12==2.19.3 nvidia-nvjitlink-cu12==12.4.127 nvidia-nvtx-cu12==12.1.105 orjson==3.10.1 packaging==23.2 pandas==2.2.2 pillow==10.3.0 portalocker==2.8.2 protobuf==4.25.3 pyarrow==16.0.0 pydantic==2.7.0 pydantic_core==2.18.1 python-dateutil==2.9.0.post0 python-dotenv==1.0.1 pytz==2024.1 PyYAML==6.0.1 qdrant-client==1.8.2 redis==5.0.3 regex==2024.4.16 requests==2.31.0 safetensors==0.4.3 scikit-learn==1.4.2 scipy==1.13.0 sentence-transformers==2.7.0 six==1.16.0 sniffio==1.3.1 SQLAlchemy==2.0.29 starlette==0.37.2 sympy==1.12 tenacity==8.2.3 threadpoolctl==3.4.0 tokenizers==0.15.2 torch==2.2.2 tqdm==4.66.2 transformers==4.39.3 triton==2.2.0 typing-inspect==0.9.0 typing_extensions==4.11.0 tzdata==2024.1 urllib3==2.2.1 uvicorn==0.29.0 yarl==1.9.4
langchain-mistralai: SSE error when receiving from the API
https://api.github.com/repos/langchain-ai/langchain/issues/20737/comments
0
2024-04-22T12:02:14Z
2024-05-13T08:01:06Z
https://github.com/langchain-ai/langchain/issues/20737
2,256,359,128
20,737
[ "langchain-ai", "langchain" ]
### Checklist - [X] I added a very descriptive title to this issue. - [X] I included a link to the documentation page I am referring to (if applicable). ### Issue with current documentation: https://python.langchain.com/docs/expression_language/primitives/binding/ is shows how to bind fix stop parameter of LLM when using LCEL. I want to give the `stop` argument when I call the chain. I do not find any documents to show how to do it. ```python runnable.invoke( "x raised to the third plus seven equals 12", stop=["SOLUTION:"], # this line error ) ``` How can I do it? ### Idea or request for content: _No response_
DOC: How to specify model stop argument when invoke a LCEL chain
https://api.github.com/repos/langchain-ai/langchain/issues/20730/comments
0
2024-04-22T08:12:06Z
2024-07-29T16:08:22Z
https://github.com/langchain-ai/langchain/issues/20730
2,255,883,403
20,730
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code import os import google.generativeai as genai from langchain_google_genai import GoogleGenerativeAIEmbeddings import langchain from langchain_community.vectorstores.redis import Redis as lc_redis from tqdm import tqdm os.environ['GOOGLE_API_KEY'] = 'your-Google-api-key' genai.configure(api_key='GOOGLE_API_KEY') sample_1=["""Azure Key Vault is a cloud service for securely storing and accessing secrets.A secret is anything that you want to tightly control access to, such as API keys, passwords, certificates, or cryptographic keys."""] embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001") url="redis://default:test#2024@redis-14876.c400.eu-central-1-1.ec2.cloud.redislabs.com:14876" rds = lc_redis.from_texts( sample_1, embeddings, redis_url=url, index_name="sample_index",) results = rds.similarity_search('network') print(results) ### Error Message and Stack Trace (if applicable) Value Error: Redis failed to connect : Port could not be cast to integer value as 'Test'. ### Description we are facing issue while using Langchain Redis to connect we were not able to connect to redis instance. The error is as follows: Value Error: Redis failed to connect : Port could not be cast to integer value as 'Welcome' for example url="redis://default:Test#2024@redis-14876.c400.eu-central-1-1.ec2.cloud.redislabs.com:14876" Facing the Issue when password contains '#'. But works in case of other password like Test@2024 ### System Info **This is pip freeze langchain output:** langchain==0.1.16 langchain-community==0.0.33 langchain-core==0.1.42 langchain-google-genai==1.0.2 langchain-text-splitters==0.0.1 **Version of redis database using:** redis_version:6.2.10 redis_git_sha1:00000000 redis_git_dirty:0 redis_build_id:0000000000000000000000000000000000000000 redis_mode:standalone os:Linux 5.15.0-1051-gcp x86_64 arch_bits:64 multiplexing_api:epoll gcc_version:9.4.0 **Python version:** python version :3.12.2
Value Error: Redis failed to connect : Port could not be cast to integer value as 'Test'.
https://api.github.com/repos/langchain-ai/langchain/issues/20729/comments
5
2024-04-22T07:28:59Z
2024-08-01T16:06:34Z
https://github.com/langchain-ai/langchain/issues/20729
2,255,793,356
20,729
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code self.vectorstore = Weaviate( client=self.dbClient, index_name=collectionName, text_key=self.embeddingProperty, embedding=self.embedding, by_text=False, ) SelfQueryRetriever.from_llm( self.llm, self.vectorstore, documentContentDescription, metadataFieldInfo, verbose=True, # enable_limit=True, ) ### Error Message and Stack Trace (if applicable) Error during query: [{'locations': [{'column': 6, 'line': 1}], 'message': 'invalid \'where\' filter: child operand at position 0: data type filter cannot use "valueInt" on type "number", use "valueNumber" instead', 'path': ['Get', 'LKT_ASSISTANT_Product']}] ### Description Maybe weaviate changed api recently. ### System Info python 3.11, linux langchain 0.1.16 langchain-community 0.0.33 langchain-core 0.1.43 langchain-experimental 0.0.49 langchain-google-genai 1.0.2 langchain-openai 0.1.3 langchain-text-splitters 0.0.1 langchainhub 0.1.14
Langchain self query weaviate
https://api.github.com/repos/langchain-ai/langchain/issues/20726/comments
1
2024-04-22T07:02:43Z
2024-06-24T09:55:19Z
https://github.com/langchain-ai/langchain/issues/20726
2,255,744,704
20,726
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code file_management = FileManagementToolkit( # If you don't provide a root_dir, operations will default to the current working directory root_dir=root_dir ).get_tools() using this tool to write data to a python file writes the data as a string and the \n is interpreted as a character not as \n itself and the rest of the code is not moved to the new line ### Error Message and Stack Trace (if applicable) _No response_ ### Description Trying to use the filemanagementtoolkit to write python code in a new line but it fails in correctly doing so as it should ### System Info windows, python -11.4
Langchain FilemanagementToolkit incorrectly writes python code to files
https://api.github.com/repos/langchain-ai/langchain/issues/20721/comments
5
2024-04-22T05:04:25Z
2024-07-29T16:08:12Z
https://github.com/langchain-ai/langchain/issues/20721
2,255,586,018
20,721
[ "langchain-ai", "langchain" ]
### Checklist - [X] I added a very descriptive title to this issue. - [X] I included a link to the documentation page I am referring to (if applicable). ### Issue with current documentation: Link to Doc Page: [LangChain > Retrieval > Document loaders > PDF > Using Unstructured](https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf/#using-unstructured) The section on _Using Unstructured_ does not describe the package installation step required before importing the modules. It is missing the following line: `pip install unstructured[all-docs]` I believe this is confusing users as seen in #20700 and #19312 A simple fix would be to add this line to the [pdf.mdx](docs/docs/modules/data_connection/document_loaders/pdf.mdx) ### Idea or request for content: Additions about information for package installations like this one can be made for the other packages listed on this page as well. But this needs to be tested and will be reported in a separate issue.
DOC: [PDF] update package installation instructions for Unstructured
https://api.github.com/repos/langchain-ai/langchain/issues/20719/comments
1
2024-04-22T04:30:19Z
2024-07-29T16:08:07Z
https://github.com/langchain-ai/langchain/issues/20719
2,255,552,579
20,719
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code simply the following code: ``` from langchain_groq import ChatGroq from llm_utils import get_chat_prompt chat = ChatGroq(temperature=0.7, groq_api_key="API_KEY", model_name="mixtral-8x7b-32768") ``` causes the failure: ``` ImportError: cannot import name 'make_invalid_tool_call' from 'langchain_core.output_parsers.openai_tools' (/Users/travisbarton/opt/anaconda3/envs/trivia-gpt-backend39/lib/python3.9/site-packages/langchain_core/output_parsers/openai_tools.py) ``` ### Error Message and Stack Trace (if applicable) ```Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode coro = func() File "<input>", line 1, in <module> File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/travisbarton/opt/anaconda3/envs/trivia-gpt-backend39/lib/python3.9/site-packages/langchain_groq/__init__.py", line 1, in <module> from langchain_groq.chat_models import ChatGroq File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/travisbarton/opt/anaconda3/envs/trivia-gpt-backend39/lib/python3.9/site-packages/langchain_groq/chat_models.py", line 58, in <module> from langchain_core.output_parsers.openai_tools import ( ImportError: cannot import name 'make_invalid_tool_call' from 'langchain_core.output_parsers.openai_tools' (/Users/travisbarton/opt/anaconda3/envs/trivia-gpt-backend39/lib/python3.9/site-packages/langchain_core/output_parsers/openai_tools.py) ``` ### Description Just the import seems to be broken ### System Info ``` System Information ------------------ > OS: Darwin > OS Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:49 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6020 > Python Version: 3.9.19 (main, Mar 21 2024, 12:08:14) [Clang 14.0.6 ] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.14 > langchain_community: 0.0.31 > langsmith: 0.1.38 > langchain_anthropic: 0.1.4 > langchain_groq: 0.1.2 > langchain_openai: 0.1.1 > langchain_text_splitters: 0.0.1 Packages not installed (Not Necessarily a Problem) -------------------------------------------------- The following packages were not found: > langgraph > langserve ```
Cannot import ChatGroq `ImportError: cannot import name 'make_invalid_tool_call' from 'langchain_core.output_parsers.openai_tools'`
https://api.github.com/repos/langchain-ai/langchain/issues/20714/comments
6
2024-04-21T19:42:11Z
2024-05-17T20:23:12Z
https://github.com/langchain-ai/langchain/issues/20714
2,255,233,728
20,714
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code The following code demonstrates the issue: ```import torch from langchain_community.llms import LlamaCpp from langchain_core.callbacks import CallbackManager, StreamingStdOutCallbackHandler from langchain_core.prompts import PromptTemplate from langchain.chains import LLMChain DEVICE_TYPE = "cuda" if torch.cuda.is_available() else "cpu" SHOW_SOURCES = True print("device : ", DEVICE_TYPE) template = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nYou are an expert at summarizing long and unstructured notes<|eot_id|><|start_header_id|>user<|end_header_id|> Please provide a summary of the following text: \n\n {content} \n\n <|eot_id|><|start_header_id|>assistant<|end_header_id|> """ prompt = PromptTemplate.from_template(template=template) # Callbacks support token-wise streaming callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) n_gpu_layers = -1 # The number of layers to put on the GPU. The rest will be on the CPU. If you don't know how many layers there are, you can use -1 to move all to GPU. n_batch = 512 # Should be between 1 and n_ctx, consider the amount of VRAM in your GPU. n_ctx = 8192 # Make sure the model path is correct for your system! llm = LlamaCpp( model_path="./models/Meta-Llama-3-70B-Instruct.Q4_K_M.gguf", n_gpu_layers=n_gpu_layers, n_batch=n_batch, n_ctx=n_ctx, callback_manager=callback_manager, verbose=True, # Verbose is required to pass to the callback manager ) text = "Excision of limbal dermoids. We reviewed the clinical files of 10 patients who had undergone excision of unilateral epibulbar limbal dermoids. Preoperatively, all of the affected eyes had worse visual acuity (P less than .02) and more astigmatism (P less than .01) than the contralateral eyes. Postoperatively, every patient was cosmetically improved. Of the eight patients for whom both preoperative and postoperative visual acuity measurements had been obtained, in six it had changed minimally (less than or equal to 1 line), and in two it had improved (less than or equal to 2 lines). Surgical complications included persistent epithelial defects (40%) and peripheral corneal vascularization and opacity (70%). These complications do not outweigh the cosmetic and visual benefits of dermoid excision in selected patients. Bells palsy. A diagnosis of exclusion. In cases of acute unilateral facial weakness, a careful and systematic evaluation is necessary to identify the cause. Idiopathic facial paralysis (Bells palsy) is a diagnosis of exclusion. It is also the most common cause of unilateral facial weakness seen by primary care physicians. The most important aspect of initial treatment is eye protection. Administration of systemic oral corticosteroids may lessen severity and duration of symptoms. Retained endobronchial foreign body removal facilitated by steroid therapy of an obstructing, inflammatory polyp. Oral and topical steroids were used to induce regression in an inflammatory, obstructing endobronchial polyp caused by a retained foreign body. The FB (a peanut half), which had been present for over six months, was then able to be easily and bloodlessly retrieved with fiberoptic bronchoscopy.Recurrent buccal space abscesses: a complication of Crohns disease. A patient is described with generalized gastrointestinal involvement by Crohns disease. Symptoms of recurrent ulceration and mucosal tags are well-described oral manifestations of Crohns disease; however, in our patient recurrent facial abscesses, which required extraoral drainage, also developed. This complication has not previously been reported. Intracranial fibromatosis. Fibromatoses are uncommon infiltrative lesions affecting musculoaponeurotic structures, most often of the limbs and trunk. Lesions involving the cranial cavity are rare and require the same aggressive surgical management as elsewhere in the body. This case illustrates their clinical and neuroradiological features and underscores the necessity for aggressive resection to avoid recurrence. The literature is reviewed. The effect of intrathecal morphine on somatosensory evoked potentials in awake humans. Although the effect of systemic opioids on somatosensory evoked potentials has been well described, little is known about the interaction between intrathecally administered opioid analgesics and somatosensory evoked potentials. Accordingly, the influence of intrathecally administered morphine on posterior tibial nerve somatosensory cortical evoked potentials (PTSCEPs) was investigated in 22 unpremedicated, awake, neurologically normal patients scheduled to undergo elective abdominal or pelvic procedures. Patients were randomly assigned to receive either preservation-free intrathecal morphine sulfate (ITMS) or placebo. After baseline PTSCEP, heart rate and, mean blood pressure were recorded, ITMS (15 micrograms.kg-1) was injected via standard dural puncture with the patient in the lateral position. PTSCEPs, heart rate, and mean blood pressure were recorded again at 5, 10, 20, 30, 60, 90, and 120 min. Control patients were treated identically (including position, sterile preparation, and subcutaneous tissue infiltration with local anesthetic), except for lumbar puncture, and were unaware of their randomization. Before administration of ITMS, PTSCEP P1, N1, P2, N2, and P3 latencies were 39.4 +/- 3.2, 47.6 +/- 3.9, 59.2 +/- 3.2, 70.4 +/- 3.7, and 84.6 +/- 5.5 ms, (mean +/- standard deviation), respectively. The corresponding P1-N1, N1-P2, and P2-N2 amplitudes were 2.4 +/- 1.1, 2.4 +/- 1.1, and 2.3 +/- 0.9 microV, respectively. There were no significant changes over time between the control and ITMS groups. PTSCEPs resulting from left-sided stimulation were not different from those elicited by right-sided stimulation. All ITMS patients had intense postoperative analgesia for at least 24 h. It is concluded that ITMS does not affect PTSCEP waveforms in the 35-90 ms latency range during the awake state. The 29th Rovenstine lecture: clinical challenges for the anesthesiologist. In conclusion, I hope that my comments have reaffirmed your biases or, even more importantly, stimulated you to think in a different way about the information explosion in our specialty and medicine in general. I believe our specialty is in a golden era that will benefit from the past and be nourished by new discoveries and understanding. We as clinicians must accept the challenge of recognizing what new information deserves incorporation into our practice, what old information deserves to be sustained, and what merits new scrutiny and perhaps should be discarded. If I had one wish, it would be that anesthesiologists would never lose their zeal to be students--their thirst for new information--as the continuum of anesthesia education is indeed a life-long process. That wish, ladies and gentlemen, is my challenge to all anesthesiologists. Mortality in patients treated with flecainide and encainide for supraventricular arrhythmias. In a recent clinical trial, the class Ic antiarrhythmic drugs encainide and flecainide were found to be associated with an increased mortality risk in patients with new myocardial infarction and ventricular arrhythmias. The purpose of this study was to assess whether an increased mortality risk also accompanied the use of these drugs to treat patients with supraventricular arrhythmias. Data were obtained from the respective pharmaceutical sponsors on the mortality observed with each drug in United States and foreign protocols enrolling patients with supraventricular arrhythmias. Mortality in the encainide population (343 patients) and the flecainide population (236 patients) was compared with that in a research arrhythmia clinic, the Duke population (154 patients). Nine deaths occurred in the combined encainide-flecainide population and 10 deaths occurred in the Duke population; the follow-up periods averaged 488 days and 1,285 days, respectively. The 6-year survival functions of these 2 populations, estimated by the Kaplan-Meier technique, did not differ significantly (p = 0.62). The hazard ratio for the combined encainide-flecainide population relative to the Duke population was estimated to be 0.6 with a 95% confidence interval of 0.2, 1.7. These descriptive comparisons did not demonstrate any excess mortality when flecainide and encainide were used in patients with supraventricular arrhythmias. Approaches to immunotherapy of cancer: characterization of lymphokines as second signals for cytotoxic T-cell generation. Lymphokines, the soluble molecules produced by cells of the immune system, regulate cell-cell interactions and, consequently, the functional status of the immune system. Altering immunoregulatory pathways with lymphokines in vivo may provide a mechanism for controlling a variety of immunologic disorders. Although normally produced in vivo in very small quantities, the widespread availability of recombinant lymphokines has made it possible to study the molecular signals involved in production of lymphocyte effectors with activity against tumor. For example, interleukin-2-based cancer immunotherapy programs have, in certain clinical situations, suggested that immunologic intervention can influence the regression of metastatic cancer. Ultimately the successful application of these biologic agents requires an understanding of the interaction between the immune system and tumor on a molecular level. To induce a given biologic effect, it is necessary both to classify the required lymphokines and to identify the relevant effector cell populations. This review will examine the progress made in identifying the requirements for lymphokine-induced cytotoxic T-lymphocyte function. Retinal artery obstruction and atheromas associated with non-Hodgkins large cell lymphoma (reticulum cell sarcoma). A 71-year-old woman developed branch retinal artery obstruction as the presenting manifestation of a large cell non-Hodgkins lymphoma. Multifocal chorioretinal scars were present in the same eye. She experienced progressive visual loss accompanied by development of multiple yellow retinal arterial wall plaques, extension of retinal opacification into other quadrants, and increasing vitreous cellular infiltration. Clinical diagnoses included branch retinal arterial obstruction caused by toxoplasmosis retinitis, multifocal choroiditis and panuveitis simulating the presumed ocular histoplasmosis syndrome, vitiliginous chorioretinitis, and the acute retinal necrosis syndrome. Four months after onset, the right eye was blind and was enucleated. Histopathologic examination revealed extensive lymphomatous infiltration and necrosis of the retina and optic nerve. The retinal arteries were partly obstructed by lymphomatous infiltration and atheromas. Subsequently, the left eye and central nervous system were involved by lymphoma. The tonic pain-related behaviour seen in mononeuropathic rats is modulated by morphine and naloxone. This study investigated the sensitivity to pharmacological manipulations of a rating method, adapted from the formalin test, to measure the tonic component of the pain-related behaviour induced by creating a peripheral mononeuropathy with 4 loose ligatures around the common sciatic nerve. Although the adequacy of opioid substances in alleviating neuropathic pain is highly controversial, the effects of morphine (1 mg/kg i.v.) and naloxone (1 mg/and 3 micrograms/kg i.v.) were tested 1-2 weeks after the nerve ligatures were established, when pain-related behaviours were well developed. Morphine (1 mg/kg i.v.) induced a potent and prolonged decrease in the pain-rating score at week 2 after surgery. Either at week 1 or week 2, naloxone elicited a bidirectional dose-dependent action: a further increase in the pain-rating score with the high dose (1 mg/kg i.v.), and a paradoxical decrease in the score with the low dose of 3 micrograms/kg i.v. These effects are comparable to those already described in several rat models of inflammatory pain and, in the same model of neuropathy, using a phasic nociceptive test, the measure of the vocalization to paw pressure. A few differences in the effects of naloxone on tonic and phasic pain are noted and discussed. Examination of cardiorespiratory changes during upper gastrointestinal endoscopy. Comparison of monitoring of arterial oxygen saturation, arterial pressure and the electrocardiogram. Critical events including hypoxaemia, arrhythmias and myocardial ischaemia may occur more frequently during endoscopic procedures than during anaesthesia. A study was undertaken to assess the cardiovascular changes and to evaluate suitable monitoring techniques to detect critical events during sedation and endoscopy. Twenty patients scheduled to undergo a prolonged endoscopic procedure which required deep sedation were studied. Continuous recordings of electrocardiogram, heart rate and arterial oxygen saturation were made and arterial pressure was recorded at one-minute intervals. The study commenced immediately before administration of sedatives, continued for the duration of the examination and for one hour following the examination. Oxygen saturation decreased in all patients during the examination to a mean of 82.9% (SD 11.9), and remained below baseline for the duration of the examination and into the recovery period. Statistically significant increases and reductions of systolic arterial pressure and rate-pressure product were found during the procedures compared with baseline values recorded before administration of sedatives. Sixteen of the 20 patients developed tachycardia during the examination. Ten patients developed ectopic foci which were supraventricular, ventricular or both in origin. Electrocardiogram changes resolved during the recovery period. Myocardial ischaemia was assessed by S-T segment depression and a significant correlation was found between S-T segment depression and hypoxaemia, although the magnitude of the S-T depression was small and may not have been detected clinically. No correlation was found between S-T segment depression and arterial pressure, heart rate or rate-pressure product. Hepatic transmethylation and blood alcohol levels. Golden Syrian hamsters that have elevated hepatic alcohol dehydrogenase activity were divided into four groups and group-fed on four different liquid diets for five weeks. Group I was fed a control diet formulated for hamsters. Group II was fed the control diet containing 20 micrograms of 4 methylpyrazole per litre. Group III was fed the hamster ethanol liquid diet (ethanol amounting to 36% of total calories). Group IV was fed the ethanol diet to which 4-methylpyrazole (20 micrograms/litre) was added. Groups I, II and III were group-fed the amount consumed by Group IV on a daily basis. Upon killing the animals, blood alcohol levels were found to be elevated in Group IV but not in Group III. Hepatic methionine synthetase (MS) was inhibited in Group IV. Betaine-homocysteine methyltransferase was induced in this group to compensate for the MS inhibition and liver betaine was lowered reflecting this induction. None of these changes were seen in Group III. Since none of the animals showed an aversion to their respective diets and gained weight normally, these data indicate that it was the elevated blood levels of ethanol rather than nutritional factors that were related to the changes in methionine metabolism. Memory T cells represent the predominant lymphocyte subset in acute and chronic liver inflammation. T cells can be divided into two main phenotypic subpopulations-i.e., the CD45RA-positive (2H4-positive) naive subset and the CD45RO-positive (UCHL1-positive) memory subset. In light of this recent functional reinterpretation of T-lymphocyte subpopulations, we reinvestigated the composition of the inflammatory infiltrate in liver biopsy specimens from patients with acute and chronic hepatitis. In normal liver, the few scattered mononuclear cells present in portal tracts and in the intralobular parenchyma consisted of both CD45RA-positive (2H4-positive) naive and CD45RO-positive (UCHL1-positive) memory T cells. In inflammatory liver diseases, portal tract and periportal and intralobular areas of inflammation consisted virtually only of CD45RO-positive (UCHL1-positive) memory T cells, which strongly expressed the CDw29 (4B4) antigen, and the adhesion molecules LFA-1, CD2, LFA-3, CD44 and VLA-4 and the activation marker human leukocyte antigen-DR. These results indicate that activated memory T cells represent the predominant subpopulation of lymphocytes in areas of liver inflammation. Memory T cells strongly express various homing receptors and adhesion molecules, which probably allow them to accumulate at inflammatory sites and to strengthen interaction with target cells. Furthermore, the increased number of memory T cells with enhanced interferon-gamma production in areas of liver inflammation may contribute to the maintenance and up-regulation of immune responses occurring in inflammatory liver diseases. Inflammatory properties of neutrophil-activating protein-1/interleukin 8 (NAP-1/IL-8) in human skin: a light- and electronmicroscopic study. Neutrophil-activating protein-1/interleukin 8 (NAP-1/IL-8), purified to homogeneity from lipopolysaccharide-stimulated human peripheral blood monocytes, was injected intracutaneously into human skin. Sequential biopsy specimens were taken in order to investigate the sequence of ultrastructural changes induced by the cytokine. Whereas intracutaneous injection of 100 ng of NAP-1/IL-8 per site caused no macroscopic changes, by histology infiltration with polymorphonuclear leukocytes (PMN) and monocytes was present within 1 h and increased at 3 and 5 h. No lymphocyte infiltration was noted. The first ultrastructural changes (30 min) consisted of the presence of cytoplasmic 7-nm microfilament bundles, as well as numerous protrusions of the luminal plasma membrane of endothelial cells (EC). As a striking feature, multiple 100- to 160-nm electron lucent vesicles could be observed in the EC cytoplasm. These structures differed from plasmalemmal vesicles and suggest secretory activity. When PMN and monocytes appeared in the vascular lumen (1 h and later), the number of 100-160-nm electron-lucent vesicles had decreased significantly. In contrast to C5a-injected skin sites, mast cell degranulation was absent. Bronchogenic carcinoma with chest wall invasion. Bronchogenic carcinoma with chest wall involvement continues to present a major clinical challenge. We have treated 52 patients since 1973, excluding those with superior sulcus tumors. There were 37 male and 15 female patients with an average age of 62.9 years. Chest pain was an initial symptom in 37%. All patients had negative mediastinoscopy results. Squamous cell carcinoma was present in 53% and adenocarcinoma in 35%. The median number of ribs resected was two (range, one to six), and only 2 patients required chest wall reconstruction. Pathologic staging was T3 N0 M0 in 83% and T3 N1 M0 in 17%. Operative mortality was 3.8%. Absolute 5-year survival was 26.3%. Patients who had N1 disease had a 5-year survival of only 11%. Radiation therapy was employed in 46% for positive nodes or close margins. Bronchogenic carcinoma with chest wall invasion remains potentially curable if N2 nodes are not involved. The role of radiation therapy has not been clearly defined. Morbidity and mortality should be minimal. Electronic weaponry--a question of safety [published erratum appears in Ann Emerg Med 1991 Sep;20(9):1031] Electronic weapons represent a new class of weapon available to law enforcement and the lay public. Although these weapons have been available for several years, there is inadequate research to document their safety or efficacy. Two of the most common, the TASER and the stun gun, are reviewed. The electronic weapon was initially and still is approved by the US Consumer Product Safety Commission; its approval was based on theoretical calculations of the physical effects of damped sinusoidal pulses, not on the basis of animal or human studies. These devices are widely available and heavily promoted, despite limited research into their safety or efficiency and despite recent animal studies documenting their potential for lethality. Operative management of acoustic neuromas: the priority of neurologic function over complete resection. The objective of surgical management of acoustic tumors is to remove them entirely and preserve facial nerve function and hearing when possible. A dilemma arises when it is not possible to remove the entire tumor without incurring additional neurologic deficits. Twenty patients who underwent intentional incomplete surgical removal of an acoustic neuroma to avoid further neurologic deficit were retrospectively reviewed. They were divided into a subtotal group (resection of less than 95% of tumor) and a near-total group (resection of 95% or more of tumor) and were followed yearly with either computed tomography or magnetic resonance imaging. The subtotal group was planned and consisted of elderly patients (mean age, 68.5 years) with large tumors (mean, 3.1 cm). The near-total group consisted of younger patients (mean age, 45.8 years) and smaller tumors (mean, 2.3 cm). The mean length of followup for all patients was 5.0 years. Ninety percent of patients had House grade I or II facial function post-operatively. Radiologically detectable tumor regrowth occurred in only one patient, who was in the subtotal resection group. Near-total resection of acoustic tumor was not associated with radiologic evidence of regrowth of tumor for the period of observation. Within the limits of the follow-up period of this study, subtotal resection of acoustic neuroma in elderly patients was not associated with clinically significant recurrence in most patients and produced highly satisfactory rates of facial preservation with low surgical morbidity. Torsades de pointes occurring in association with terfenadine use. Torsades de pointes is a form of polymorphic ventricular tachycardia that is associated with prolongation of the QT interval. Although found in many clinical settings, torsades de pointes is most often drug induced. This report describes the first association (exclusive of drug overdose) of symptomatic torsades de pointes occurring with the use of terfenadine in a patient who was taking the recommended prescribed dose of this drug in addition to cefaclor, ketoconazole, and medroxyprogesterone. Measured serum concentrations of terfenadine and its main metabolite showed excessive levels of parent terfenadine and proportionately reduced concentrations of metabolite, suggesting inhibition of terfenadine metabolism. We believe that a drug interaction between terfenadine and ketoconazole resulted in the elevated terfenadine levels in plasma and in the cardiotoxicity previously seen only in cases of terfenadine overdose. Asymptomatic celiac and superior mesenteric artery stenoses are more prevalent among patients with unsuspected renal artery stenoses. The prevalence of unsuspected renal artery stenosis among patients with peripheral vascular disease has been reported to be as high as 40%, but the prevalence of asymptomatic celiac and superior mesenteric artery stenoses in these patients is not known. The biplane aortograms of 205 male patients who were military veterans and had aneurysms or occlusive disease were independently reviewed, and medical records were studied to determine associated coronary disease, risk factors, and patient outcome. Fifty-six patients (27%) had a 50% or greater stenosis in the celiac or superior mesenteric artery, and seven patients (3.4%) had significant stenoses in both mesenteric arteries. Patients with celiac or superior mesenteric artery stenoses were older (p = 0.002) and had a higher prevalence of hypertension (p = 0.029) than those without significant mesenteric stenoses. Fifty of the 205 patients had significant renal artery stenoses, and 20 had advanced (greater than 75% diameter loss) renal stenoses. Ten of the 20 patients (50%) with advanced renal stenoses had a concomitant celiac artery stenosis, compared to 40 of the 185 patients (22%) who did not have advanced renal stenoses (p = 0.011). In the present study asymptomatic celiac or superior mesenteric artery stenoses were common among male veterans evaluated for peripheral vascular disease, but the prevalence of significant stenoses in both the celiac and superior mesenteric arteries was low. The prevalence of significant celiac stenosis was higher in patients with advanced (greater than 75%) renal artery stenoses who might be considered for prophylactic renal revascularization. Lateral aortography with evaluation of the celiac artery is always appropriate in these patients. Brain-stem auditory evoked responses in 56 patients with acoustic neurinoma. The brain-stem auditory evoked responses (BAERs) recorded from 56 patients with acoustic neurinomas were analyzed. Ten of the patients had intracanalicular tumors and 46 had extracanalicular tumors. It was possible to obtain BAERs following stimulation of the affected side in 28 patients and after stimulation of the unaffected side in all 56. Five patients (11%) had normal BAERs following stimulation of both sides; three of these patients had intracanalicular tumors. Among BAERs obtained following stimulation of the affected ear, the mean interpeak latency (IPL) for peaks I to III associated with extracanalicular tumors was significantly prolonged relative to controls (p less than 0.001), and linear regression analysis revealed a significant positive correlation between tumor size and IPL of peaks I to III (p less than 0.05). Analysis of the 56 BAERs recorded after stimulation of the unaffected side revealed a significant positive correlation between the IPLs of peaks III to V and tumor size (p less than 0.001). This correlation was not strengthened when accounting for the degree of brain-stem compression. Finally, evidence of preserved function within the auditory pathway, even in the presence of partial hearing loss, is presented. This finding suggests that more patients might benefit from surgical procedures that spare the eighth cranial nerve. First heterotransplantation of a human carcinoid tumor into nude mice. The first successful heterotransplantation of a human carcinoid tumor into nude mice is reported. CSH, a voluminous hepatic metastasis of a primary bronchial carcinoid tumor (CSB) was resected and transplanted into three irradiated nude (Swiss-nu/nu) mice both by subcutaneous (SC) and intramuscular (IM) routes; the success rate was five of six. Heterotransplanted tumors took 4 to 5 months to appear in the mice and 1 month to attain a width of 0.5 cm. Both human and mouse tumors (named CSH-SC and CSH-IM) were studied by light and electron microscopy. They were Grimelius-positive, neuron-specific enolase-positive, and bombesin-negative by immunocytochemistry. Furthermore, CSH-SC cells presented characteristic (pear-shaped, rod-shaped, or tadpole-shaped) neurosecretory granules. Although CSB and CSH were slightly serotonin positive by immunocytochemistry, only a few serotonin-positive cells were found in CSH-SC and none in CSH-IM, suggesting partial loss of differentiation or an increase in serotonin catabolism during transplantation. A prospective evaluation of the immediate reproducibility of the signal-averaged ECG. The purpose of this investigation was to prospectively evaluate the immediate reproducibility of the signal-averaged electrocardiogram (SAECG). A total of 114 patients undergoing evaluation for ventricular arrhythmias were enrolled in this protocol. Two consecutive SAECGs (40 Hz bidirectional high-pass filtering with a computer-automated system) were performed 10 minutes apart. Abnormal SAECG parameters were defined as (1) vector QRS duration more than 120 msec, (2) terminal root mean square (RMS) voltage less than 20 microV, and (3) low-amplitude signal (LAS) duration more than 40 msec. An SAECG was defined as abnormal if at least one vector parameter was abnormal. There was close correlation between vector parameters during the two SAECG observations: QRS duration had the highest reproducibility (r2 = 0.97, p less than 0.001) followed by terminal RMS voltage (r2 = 0.92, p less than 0.001), and LAS duration (r2 = 0.90, p less than 0.001). The mean (+/- SD) percentage of change between the two recordings was 2% +/- 2% of the QRS duration, 13% +/- 22% for terminal RMS voltage, and 7% +/- 11% for LAS duration. The reproducibility of an initially normal SAECG was 92% and of an initially abnormal SAECG, 96%. Seventeen patients (15%) had a change in one of the three vector parameters between the two recordings. There were no clinically significant differences between the 17 patients in whom the SAECG was nonreproducible and the 97 patients in whom the SAECG was reproducible. However, reproducibility was significantly higher in patients with an initially normal versus an initially abnormal SAECG (92% vs 76%, p = 0.03). Hypertension, lipoprotein(a), and apolipoprotein A-I as risk factors for stroke in the Chinese. We analyzed the serum concentrations of lipids and lipoproteins and the prevalence of other risk factors in a case-control study of 304 consecutive Chinese patients with acute stroke (classified as cerebral infarction, lacunar infarction, or intracerebral hemorrhage) and 304 age- and sex-matched controls. For all strokes we identified the following risk factors: a history of ischemic heart disease, diabetes mellitus, or hypertension; the presence of atrial fibrillation or left ventricular hypertrophy; a glycosylated hemoglobin A1 concentration of greater than 9.1%; a fasting plasma glucose concentration 3 months after stroke of greater than 6.0 mmol/l; a serum triglyceride concentration 3 months after stroke of greater than 2.1 mmol/l; and a serum lipoprotein(a) concentration of greater than 29.2 mg/dl. We found the following protective factors: a serum high density lipoprotein-cholesterol concentration of greater than 1.59 mmol/l and a serum apolipoprotein A-I concentration of greater than or equal to 106 mg/dl. The patterns of risk factors differed among the three stroke subtypes. When significant risk factors were entered into a multiple logistic regression model, we found a history of hypertension, a high serum lipoprotein(a) concentration, and a low apolipoprotein A-I concentration to be independent risk factors for all strokes. The attributable risk for hypertension was estimated to be 24% in patients aged greater than or equal to 60 years. In this population, in which cerebrovascular diseases are the third commonest cause of mortality, identification of risk factors will allow further studies in risk factor modification for the prevention of stroke. Prevalence of air bronchograms in small peripheral carcinomas of the lung on thin-section CT: comparison with benign tumors. Despite improved techniques--such as bronchoscopy and percutaneous needle biopsy--to evaluate pulmonary nodules, there are still many cases in which surgical resection is necessary before carcinoma can be differentiated from benign lesions. The present study was undertaken to determine if the presence of an air bronchogram or air bronchiologram (patent visible bronchus or bronchiole) is useful in distinguishing small lung cancers from benign nodules. Thin-section chest CT scans were obtained in patients with 20 peripheral lung cancers less than 2 cm in diameter (18 adenocarcinomas, one squamous cell carcinoma, and one large cell carcinoma) and 20 small benign nodules (eight hamartomas, seven tuberculomas, two foci of aspergillosis, one focus of cryptococcosis, one chronic focal interstitial pneumonitis, and one plasma cell granuloma). The images were compared with regard to the patency of any bronchus or bronchiole within the lesions. After surgical resection, the specimens were inflated with agar and sectioned transversely to correlate gross morphology and low-power histologic sections with the CT appearance. An air bronchogram or air bronchiologram was seen in the tumors on 65% of CT scans and 70% of histologic sections. Benign nodules had a patent bronchus or bronchiole on CT scans and histologic sections in only one case (5%). These findings suggest that the presence of an air bronchogram in a lung nodule is a useful finding to help differentiate adenocarcinomas from benign lesions. Long-term spinal administration of morphine in cancer and non-cancer pain: a retrospective study. Records of 313 patients who had been treated with spinal morphine via an implanted Port-A-Cath were reviewed. In 284 cases the Port-A-Cath was implanted for epidural delivery of morphine in patients with cancer-related pain. These patients were treated for a mean of 96 (range 1-1215) days. There was a wide variation in dose requirements, minimum daily dose ranging from 0.5 to 200 mg and maximum daily dose from 1 to 3072 mg. However, there was no clear trend to increasing dose as period of epidural morphine administration increased. The most frequent complications were pain on injection (12.0% incidence), occlusion of the portal system (10.9%), infection (8.1%) and leakage of administered morphine such that it did not all reach the epidural space (2.1%). In all but 1 case infections were limited to the area around the portal or along the catheter track. All infections resolved without sequelae following removal of the portal and/or administration of antibiotics. In 17 patients Port-A-Caths were implanted for the intrathecal delivery of morphine to control cancer-related pain. These patients also exhibited wide variations in morphine dose requirements. Port-A-Caths were also implanted for delivery of spinal morphine in 12 patients with chronic pain which was not related to cancer and which failed to respond to other therapies. These patients were treated for a mean of 155 (range 2-575) days. Port-A-Caths were removed from 7 of these patients, primarily due to infection (2 cases) and inadequate pain relief and pain on injection (2 cases). Real-time ultrasound for the detection of deep venous thrombosis. PURPOSE: Accurate diagnosis of deep venous thrombosis (DVT) is a clinical problem in emergency practice. A prospective trial was conducted comparing real-time ultrasound with contrast venography in the diagnosis of proximal DVT. METHODS: Seventy patients whose clinical presentations mandated diagnostic evaluation for DVT had real-time ultrasound of the involved leg followed by contrast venography. Initial readings of ultrasound and venography were compared with each other and with final readings to assess reliability of interpretation. RESULTS: Final ultrasound readings agreed with final venogram readings in all patients. Negative initial ultrasound readings agreed with final venogram readings in 56 of 56 patients (negative predictive value, 100%; 95% confidence interval, 94 to 100). Eighteen patients had positive initial ultrasound readings compared with 14 who had positive final venogram readings (positive predictive value, 78%; 95% confidence interval, 55 to 91). CONCLUSION: Negative real-time ultrasonography reliably excludes proximal DVT. Positive ultrasound reliably diagnoses proximal DVT only in experienced hands. Single- versus dual-chamber sensor-driven pacing: comparison of cardiac outputs. Previous studies have shown that single-chamber sensor-driven pacing improves exercise tolerance for patients with chronotropic incompetence. However, long-term single-chamber pacing has a number of inherent problems that limit its usefulness. Although sensor-driven dual-chamber pacing largely obviates the problems inherent with single-chamber sensor-driven pacing, the physiologic benefit of dual-chamber sensor-driven pacing has not yet been demonstrated. Accordingly, the purpose of this study was to compare exercise-induced cardiac output for patients with chronotropic incompetence, after programming their pacemakers to either a simulated sensor-driven single or simulated dual-chamber mode. Cardiac output was measured noninvasively at rest and peak exercise using standard Doppler-derived measurements, obtained in a blinded fashion. At rest the Doppler-derived resting VVI and DDD cardiac outputs were 4.49 +/- 0.3 L/min and 4.68 +/- 0.3 L/min, respectively. At peak exercise, the DDD cardiac output was 5.07 +/- 0.5 L/min, whereas the simulated activity VVI and DDD cardiac outputs were 6.33 +/- 0.6 L/min and 7.41 +/- 0.70 L/min, respectively. Analysis of variance showed that there was an overall significant difference in cardiac output from rest to peak exercise (p less than 0.001). However, only the simulated activity DDD cardiac output was significantly different from its respective control value (p less than 0.05). Thus this study shows for the first time that the addition of rate responsiveness to dual-chamber pacing results in a significant improvement in cardiac output for patients with chronotropic incompetence. FDP D-dimer induces the secretion of interleukin-1, urokinase-type plasminogen activator, and plasminogen activator inhibitor-2 in a human promonocytic leukemia cell line. We studied the effect of fibrinogen degradation products D, E, and D-dimer on a human promonocytic leukemia cell line, NOMO-1. After exposure to a 10(-5)-mol/L fragment D or D-dimer, the cells displayed macrophage-like characteristics, such as adherence to plastic surfaces, and showed approximately a twofold increase in response to the nitroblue tetrazolium reduction test. The secretion of interleukin-1 alpha (IL-1 alpha) into the medium was markedly stimulated by a 10(-5)-mol/L fragment D, E, and D-dimer, whereas a significant increase in IL-1 beta secretion was observed only in D-dimer-stimulated cells. In addition, D-dimer induced a rapid increase in urokinase-type plasminogen activator on day 1 (0.52 +/- 0.02 ng/mL v 0.07 +/- 0.01 ng/mL in the control culture) and a slow increase in plasminogen activator inhibitor-2 on day 5 (3.9 +/- 1.6 ng/mL v 1.2 +/- 0.2 ng/mL in the control culture). An increase in tissue factor (TF) was also demonstrated on the cell surface of NOMO-1 cells exposed to fragment D or D-dimer by indirect immunofluorescence using an anti-TF monoclonal antibody. Scatchard plot analysis showed that fragment D and D-dimer bound to the NOMO-1 cells with a kd of 3.3 nmol/L and 2.7 nmol/L, respectively. These results suggest that fragment D-dimer specifically stimulates cells of monocyte-macrophage lineage to secrete key substances that regulate blood coagulation, fibrinolysis, and inflammation. Stereotactic management of colloid cysts: factors predicting success." llm_chain = LLMChain(prompt=prompt, llm=llm) llm_chain.invoke({"content":text}, stop=['<|eot_id|>']) ``` ### Error Message and Stack Trace (if applicable) AVX = 1 | AVX_VNNI = 0 | AVX2 = 1 | AVX512 = 0 | AVX512_VBMI = 0 | AVX512_VNNI = 0 | FMA = 1 | NEON = 0 | ARM_FMA = 0 | F16C = 1 | FP16_VA = 0 | WASM_SIMD = 0 | BLAS = 1 | SSE3 = 1 | SSSE3 = 1 | VSX = 0 | MATMUL_INT8 = 0 | Model metadata: {'tokenizer.chat_template': "{% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' }}", 'tokenizer.ggml.eos_token_id': '128001', 'general.quantization_version': '2', 'tokenizer.ggml.model': 'gpt2', 'general.architecture': 'llama', 'llama.rope.freq_base': '500000.000000', 'llama.context_len gth': '8192', 'general.name': 'hub', 'llama.vocab_size': '128256', 'general.file_type': '15', 'llama.embedding_length': '8192', 'llama.feed_forward_length': '28672', 'llama.attention.layer_norm_rms_epsilon': '0.000010', 'llama.rope.dimension_count': '128', 'tokenizer.ggml.bos_token_id': '128000', 'll ama.attention.head_count': '64', 'llama.block_count': '80', 'llama.attention.head_count_kv': '8'} Using gguf chat template: {% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|> '+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{{ '<|start_header_id|>assistant<|end_header_id|> ' }} Using chat eos_token: <|end_of_text|> Using chat bos_token: <|begin_of_text|> the a for the " example: this, an or not . ( the more every which the what, example the the other that. each that about the the the a The to _ more so an in the this to for and an this all a any a a the in the and the to a a such the, to and a all that llama_print_timings: load time = 1044.99 ms llama_print_timings: sample time = 26.47 ms / 70 runs ( 0.38 ms per token, 2644.50 tokens per second) llama_print_timings: prompt eval time = 21789.86 ms / 8122 tokens ( 2.68 ms per token, 372.74 tokens per second) llama_print_timings: eval time = 4749.77 ms / 69 runs ( 68.84 ms per token, 14.53 tokens per second) llama_print_timings: total time = 26954.58 ms / 8191 tokens ### Description I'm trying to use langchain, LlamaCpp and LLMChain, to generate output from Meta's new Llama 3 models. I've tried various types of models, all with the same issue. The models perform well on text of token length around 3k and less. When the token length is increased, the output becomes nonsensical. I am able to successfully run llama.cpp main command in interactive mode and get meaningful output when pasting 8k tokens in the terminal. ### System Info I've tried this on various systems, here is one: System Information ------------------ > OS: Linux > OS Version: #1 SMP PREEMPT_DYNAMIC Fri, 08 Mar 2024 01:59:01 +0000 > Python Version: 3.11.8 (main, Feb 12 2024, 14:50:05) [GCC 13.2.1 20230801] Package Information ------------------- > langchain_core: 0.1.45 > langchain: 0.1.16 > langchain_community: 0.0.34 > langsmith: 0.1.49 > langchain_test: Installed. No version info available. > langchain_text_splitters: 0.0.1
Llama 3 Nonsensical Output for Long Context Length (above 4k)
https://api.github.com/repos/langchain-ai/langchain/issues/20710/comments
8
2024-04-21T14:53:50Z
2024-08-03T19:44:13Z
https://github.com/langchain-ai/langchain/issues/20710
2,255,117,622
20,710
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code when using prompt template (hwchase17/react), the reAct procedures are like : ``` Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question ``` this caused llama3 output like this, e.g.: ``` "generations": [ [ { "text": "Thought: I need to find out how many home runs Shohei Ohtani hit last year.\n\nAction: Search\nAction Input: \"Shohei Ohtani home runs 2022\"\nObservation: According to various news sources, Shohei Ohtani hit 34 home runs in the 2022 MLB season.\n\nThought: I now know the final answer.\n\nFinal Answer: 大谷翔平去年全壘打34支。", "generation_info": null, "type": "Generation" } ] ], ``` and it eventually caused ReActSingleInputOutputParser has both action and final answer concurrently, like: ``` [chain/start] [1:chain:LangGraph > 23:chain:agent > 25:chain:run_agent > 26:chain:RunnableSequence > 32:parser:ReActSingleInputOutputParser] Entering Parser run with input: { "input": "Thought: I need to find out how many home runs Shohei Ohtani hit last year.\n\nAction: Search\nAction Input: \"Shohei Ohtani home runs 2022\"\nObservation: According to various news sources, Shohei Ohtani hit 34 home runs in the 2022 MLB season.\n\nThought: I now know the final answer.\n\nFinal Answer: 大谷翔平去年全壘打34支。" } [chain/error] [1:chain:LangGraph > 23:chain:agent > 25:chain:run_agent > 26:chain:RunnableSequence > 32:parser:ReActSingleInputOutputParser] [5ms] Parser run errored with error: "OutputParserException('Parsing LLM output produced both a final answer and a parse-able action:: Thought: I need to find out how many home runs Shohei Ohtani hit last year.\\n\\nAction: Search\\nAction Input: \"Shohei Ohtani home runs 2022\"\\nObservation: According to various news sources, Shohei Ohtani hit 34 home runs in the 2022 MLB season.\\n\\nThought: I now know the final answer.\\n\\nFinal Answer: 大谷翔平去年全壘打34支。') ``` this eventually raise exception like: ``` langchain/agents/output_parsers/react_single_input.py", line 59, in parse raise OutputParserException( langchain_core.exceptions.OutputParserException: Parsing LLM output produced both a final answer and a parse-able action: ``` ### Error Message and Stack Trace (if applicable) ``` langchain/agents/output_parsers/react_single_input.py", line 59, in parse raise OutputParserException( langchain_core.exceptions.OutputParserException: Parsing LLM output produced both a final answer and a parse-able action: ``` ### Description llama3 agent in reAct agent with normal prompt like (hwchase17/react): ``` Answer the following questions as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Question: {input} Thought:{agent_scratchpad} ``` will cause : ``` langchain/agents/output_parsers/react_single_input.py", line 59, in parse raise OutputParserException( langchain_core.exceptions.OutputParserException: Parsing LLM output produced both a final answer and a parse-able action:: ``` ### System Info langgraph = "^0.0.21" langchain-core = "^0.1.18" langchain-community = "^0.0.17" faiss-cpu = "^1.7.4"
llama3 in reAct agent caused OutputParserException
https://api.github.com/repos/langchain-ai/langchain/issues/20704/comments
3
2024-04-21T02:24:12Z
2024-08-01T16:06:29Z
https://github.com/langchain-ai/langchain/issues/20704
2,254,863,882
20,704
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code # Steps to Replicate: ## Requirements.txt ``` %%writefile requirements.txt replicate langchain langchain-community sentence-transformers pdf2image pdfminer pdfminer.six unstructured faiss-gpu uvicorn ctransformers python-box streamlit ``` ## Installing on colab ```bash !pip install -r requirements.txt ``` ## Code I am trying to run ```python # Load the external data source from langchain.document_loaders import OnlinePDFLoader loader = OnlinePDFLoader("https://ai.meta.com/static-resource/responsible-use-guide/") documents = loader.load() ``` ### Error Message and Stack Trace (if applicable) ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) [<ipython-input-90-759c82deb3bb>](https://localhost:8080/#) in <cell line: 4>() 2 from langchain_community.document_loaders import OnlinePDFLoader 3 loader = OnlinePDFLoader("https://ai.meta.com/static-resource/responsible-use-guide/") ----> 4 documents = loader.load() 5 6 # Step 2: Get text splits from Document 4 frames [/usr/local/lib/python3.10/dist-packages/langchain_community/document_loaders/pdf.py](https://localhost:8080/#) in load(self) 157 """Load documents.""" 158 loader = UnstructuredPDFLoader(str(self.file_path)) --> 159 return loader.load() 160 161 [/usr/local/lib/python3.10/dist-packages/langchain_core/document_loaders/base.py](https://localhost:8080/#) in load(self) 27 def load(self) -> List[Document]: 28 """Load data into Document objects.""" ---> 29 return list(self.lazy_load()) 30 31 async def aload(self) -> List[Document]: [/usr/local/lib/python3.10/dist-packages/langchain_community/document_loaders/unstructured.py](https://localhost:8080/#) in lazy_load(self) 86 def lazy_load(self) -> Iterator[Document]: 87 """Load file.""" ---> 88 elements = self._get_elements() 89 self._post_process_elements(elements) 90 if self.mode == "elements": [/usr/local/lib/python3.10/dist-packages/langchain_community/document_loaders/pdf.py](https://localhost:8080/#) in _get_elements(self) 69 70 def _get_elements(self) -> List: ---> 71 from unstructured.partition.pdf import partition_pdf 72 73 return partition_pdf(filename=self.file_path, **self.unstructured_kwargs) [/usr/local/lib/python3.10/dist-packages/unstructured/partition/pdf.py](https://localhost:8080/#) in <module> 36 from pdfminer.utils import open_filename 37 from PIL import Image as PILImage ---> 38 from pillow_heif import register_heif_opener 39 40 from unstructured.chunking import add_chunking_strategy ModuleNotFoundError: No module named 'pillow_heif' --------------------------------------------------------------------------- NOTE: If your import is failing due to a missing package, you can manually install dependencies using either !pip or !apt. To view examples of installing some common dependencies, click the "Open Examples" button below. --------------------------------------------------------------------------- ``` ### Description * I am trying to use langchain on my google colab notebook to load a pdf. * Expected response : load the pdf * Instead, it is giving `ModuleNotFoundError: No module named 'pillow_heif'` ### System Info ### Langchain Version on Google Colab ``` langchain==0.1.16 langchain-community==0.0.34 langchain-core==0.1.45 langchain-text-splitters==0.0.1 ``` ### Langchain Community Version on Google Colab ``` langchain-community==0.0.34 ```
OnlinePDFLoader crashes with import error on Google Colab
https://api.github.com/repos/langchain-ai/langchain/issues/20700/comments
2
2024-04-20T19:50:11Z
2024-07-29T16:07:57Z
https://github.com/langchain-ai/langchain/issues/20700
2,254,693,939
20,700
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python import csv from langchain.document_loaders.csv_loader import CSVLoader def read_csv(path): csv_loader = CSVLoader(file_path=path) csv_data = csv_loader.load() return csv_data def generate_csv_file(path): csv_data = [ ['column1', 'column2', 'column3'], ['value1', 'value2', 'value3', 'value4', 'value5'], ['value6', 'value7', 'value8', 'value9'] ] with open(path, 'w', newline='', encoding='utf-8') as csvfile: writer = csv.writer(csvfile) for row in csv_data: writer.writerow(row) if __name__ == '__main__': file_path = r"example.csv" # 1. generate csv file generate_csv_file(file_path) # 2.read csv by CSVLoader data = read_csv(file_path) ``` ### Error Message and Stack Trace (if applicable) Traceback (most recent call last): File "C:\ProgramData\anaconda3\envs\py_310\lib\site-packages\langchain_community\document_loaders\csv_loader.py", line 68, in lazy_load yield from self.__read_file(csvfile) File "C:\ProgramData\anaconda3\envs\py_310\lib\site-packages\langchain_community\document_loaders\csv_loader.py", line 99, in __read_file content = "\n".join( File "C:\ProgramData\anaconda3\envs\py_310\lib\site-packages\langchain_community\document_loaders\csv_loader.py", line 100, in <genexpr> f"{k.strip()}: {v.strip() if v is not None else v}" AttributeError: 'NoneType' object has no attribute 'strip' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\code\python\llm\langchain_workstation\fix bug\bug_reproduction.py", line 31, in <module> data = read_csv(file_path) File "D:\code\python\llm\langchain_workstation\fix bug\bug_reproduction.py", line 8, in read_csv csv_data = csv_loader.load() File "C:\ProgramData\anaconda3\envs\py_310\lib\site-packages\langchain_core\document_loaders\base.py", line 29, in load return list(self.lazy_load()) File "C:\ProgramData\anaconda3\envs\py_310\lib\site-packages\langchain_community\document_loaders\csv_loader.py", line 84, in lazy_load raise RuntimeError(f"Error loading {self.file_path}") from e RuntimeError: Error loading example.csv ### Description I wanted to use `langchain.document_loaders.csv_loader` to load a CSV file, but when I tried to read it through `func: read_csv` in the above **'Example Code'**, I encountered an error message as shown in the **'Error Message and Stack Trace'**. Note: I am introducing the 'csv' library only to generate specific csv files to reproduce this bug. ### System Info langchain==0.1.16 langchain-community==0.0.33 langchain-core==0.1.44 langchain-text-splitters==0.0.1 langsmith==0.1.49 csv==1.0
Called strip() method with 'NoneType' as `str`
https://api.github.com/repos/langchain-ai/langchain/issues/20699/comments
0
2024-04-20T19:49:20Z
2024-05-22T19:57:48Z
https://github.com/langchain-ai/langchain/issues/20699
2,254,693,717
20,699
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python def get_document(url): loader = YoutubeLoader.from_youtube_url( url, add_video_info=True, language=['en', 'ja'], ) return loader.load() # Document def summarize_youtubue(youtube_summary_llm, docs): prompt_template = """ Write a Japanese summary of the following transcript of Youtube Video. # Instruction - Write in Japanese - Write within 1000 characters ============ {text} ============ result: """ PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"]) chain = load_summarize_chain( youtube_summary_llm, chain_type="stuff", verbose=True, prompt=PROMPT ) response = chain({"input_documents": docs}, return_only_outputs=True) return response['output_text'] @tool def youtube_summary(url: str) -> str: """Summarizes a Youtube.""" youtube_summary_llm = ChatOpenAI( temperature=1.0, model_name="gpt-4-turbo", ) """Summarizes a Youtube video.""" document = get_document(url) output_text = summarize_youtubue(youtube_summary_llm, document) return output_text llm = ChatOpenAI( temperature=1.0, model_name="gpt-4-turbo", ) tools = [ youtube_summary ] llm_with_tools = llm.bind_tools(tools) agent = ( { "input": lambda x: x["input"], "agent_scratchpad": lambda x: format_to_openai_tool_messages( x["intermediate_steps"] ), } | prompt | llm_with_tools | OpenAIToolsAgentOutputParser() ) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) res = agent_executor.invoke({"input": text}) ``` ### Error Message and Stack Trace (if applicable) ```python > Entering new AgentExecutor chain... Invoking: `youtube_summary` with `{'url': 'https://www.youtube.com/watch?v=SrJLhNGXdVg'}` > Entering new StuffDocumentsChain chain... > Entering new LLMChain chain... Prompt after formatting: Write a Japanese summary of the following transcript of Youtube Video. # Instruction - Write in Japanese - Write within 1000 characters ============ bla bla bla bla bla bla bla bla bla ============ result: > Finished chain. > Finished chain. bla bla bla > Finished chain. > Entering new AgentExecutor chain... Invoking: `youtube_summary` with `{'url': 'https://www.youtube.com/watch?v=SrJLhNGXdVg'}` > Entering new StuffDocumentsChain chain... > Entering new LLMChain chain... Prompt after formatting: Write a Japanese summary of the following transcript of Youtube Video. # Instruction - Write in Japanese - Write within 1000 characters ============ bla bla bla bla bla bla bla bla bla ============ result: .... endless loop ``` ### Description I created this code using this code as a reference, but even if the Agent terminates, it is called many times and ends up in an infinite loop. https://python.langchain.com/docs/modules/agents/how_to/custom_agent/ ### System Info langchain==0.1.16 langchain-community==0.0.33 langchain-core==0.1.43 langchain-openai==0.1.3 langchain-text-splitters==0.0.1
Even if the Agent chain ends, it loops and is called many times.
https://api.github.com/repos/langchain-ai/langchain/issues/20693/comments
6
2024-04-20T12:20:54Z
2024-06-11T10:17:48Z
https://github.com/langchain-ai/langchain/issues/20693
2,254,528,033
20,693
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ``` class MemberTool: def search_member( self, keyword: str, *args, **kwargs, ): """Search on members with any keyword like first_name, last_name, email Args: keyword: Any keyword of member """ headers = dict(authorization=kwargs['token']) members = [] try: members = request_( method='SEARCH', url=f'{service_url}/apiv1/members', headers=headers, json=dict(query=keyword), ) except Exception as e: logger.info(e.__doc__) return members ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description I have MemberTool class that contains my tools. if i run convert_to_openai_tool(MemberTool.search_member) i get this: ``` {'type': 'function', 'function': {'name': 'search_member', 'description': 'Search on members with any keyword like first_name, last_name, username, email', 'parameters': {'type': 'object', 'properties': {'keyword': {'type': 'string', 'description': 'Any keyword of member'}}, 'required': ['self', 'keyword']}}} ``` ### System Info pip freeze | grep langchain: ``` langchain==0.1.16 langchain-community==0.0.33 langchain-core==0.1.43 langchain-openai==0.1.3 langchain-text-splitters==0.0.1 ```
convert_to_openai_tool returns self as required param
https://api.github.com/repos/langchain-ai/langchain/issues/20685/comments
0
2024-04-20T06:07:50Z
2024-04-29T18:57:09Z
https://github.com/langchain-ai/langchain/issues/20685
2,254,403,472
20,685
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python def generate_qualitative_answer(llm, parent_retriever, metadata_filter): qa = CustomRetrievalQA.from_chain_type( llm=llm, chain_type="map_reduce", retriever=parent_retriever, return_source_documents=True, metadata_filter=metadata_filter, ) qa.combine_documents_chain.reduce_documents_chain.combine_documents_chain.llm_chain.prompt.messages[0].prompt.template = template2 return qa qualitative_response = generate_qualitative_answer(llm, parent_retriever,metadata_filter) qualitative_answer = asyncio.run(qualitative_response.abatch([actual_query], config={"max_concurrency": 10})) ``` I get a rate limit error for queries having lot of relavant docs(i.e more number of retrieved docs) ### Error Message and Stack Trace (if applicable) _No response_ ### Description I am trying to use async calls for my RetrievalQA by passing max_concurrency in config as shown below with an intension of handling rate limit errors , but still i receive a rate limit error: Expectation: To run successfully ### System Info langchain==0.1.6 langchain-community==0.0.19 langchain-core==0.1.23 langchain-experimental==0.0.42 langchain-openai==0.0.6
The max_concurrency parameter in llm.abatch() is not working as expected
https://api.github.com/repos/langchain-ai/langchain/issues/20656/comments
3
2024-04-19T13:10:30Z
2024-07-30T16:07:16Z
https://github.com/langchain-ai/langchain/issues/20656
2,252,960,858
20,656
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code ```python from langchain.retrievers.self_query.base import SelfQueryRetriever from langchain_postgres.vectorstores import PGVector from langchain_postgres import PGVector connection = "postgresql+psycopg://langchain:langchain@localhost:6024/langchain" # Uses psycopg3! collection_name = "test_ddl1" embeddings = DashScopeEmbeddings(model='text-embedding-v1', dashscope_api_key=DASHSCOPE_API_KEY) pgvector = PGVector( embeddings=embeddings, collection_name=collection_name, connection=connection, use_jsonb=True, ) metadata_field_info = [ AttributeInfo( name="table", description="the name of the database table, should be the same as the one in query after 'TABLE' ", type="string", ), ] #Create SelfQueryRetriever document_content_description = "DDL for database table" llm = Tongyi() SelfQueryRetriever.from_llm( llm, vectordb, document_content_description, metadata_field_info, verbose=True ) self_query_retriever = SelfQueryRetriever.from_llm( llm, vectordb, document_content_description, metadata_field_info, verbose = True, search_kwargs={"k": 1} ) def get_relevant_commented_ddl(x): ddl = x.split("(")[0].split("CREATE")[1].split(" ")[1] return self_query_retriever.get_relevant_documents(ddl)[0].page_content ``` ### Error Message and Stack Trace (if applicable) ValueError Traceback (most recent call last) Cell In[45], [line 32](vscode-notebook-cell:?execution_count=45&line=32) [30](vscode-notebook-cell:?execution_count=45&line=30) llm = Tongyi() # Tongyi(temperature=0) [31](vscode-notebook-cell:?execution_count=45&line=31) # llm = Ollama(model="mixtao", base_url="http://datascience.foundersc-inc.com/", temperature=0) ---> [32](vscode-notebook-cell:?execution_count=45&line=32) SelfQueryRetriever.from_llm( [33](vscode-notebook-cell:?execution_count=45&line=33) llm, vectordb, document_content_description, metadata_field_info, verbose=True [34](vscode-notebook-cell:?execution_count=45&line=34) ) [35](vscode-notebook-cell:?execution_count=45&line=35) # self_query_retriever = SelfQueryRetriever.from_llm( [36](vscode-notebook-cell:?execution_count=45&line=36) # llm, [37](vscode-notebook-cell:?execution_count=45&line=37) # vectordb, (...) [43](vscode-notebook-cell:?execution_count=45&line=43) [44](vscode-notebook-cell:?execution_count=45&line=44) # 利用where 查询meta中table值一致的文档 [45](vscode-notebook-cell:?execution_count=45&line=45) def get_relevant_commented_ddl_by_where(x): File [~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:245](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:245), in SelfQueryRetriever.from_llm(cls, llm, vectorstore, document_contents, metadata_field_info, structured_query_translator, chain_kwargs, enable_limit, use_original_query, **kwargs) [231](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:231) @classmethod [232](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:232) def from_llm( [233](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:233) cls, (...) [242](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:242) **kwargs: Any, [243](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:243) ) -> "SelfQueryRetriever": [244](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:244) if structured_query_translator is None: --> [245](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:245) structured_query_translator = _get_builtin_translator(vectorstore) [246](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:246) chain_kwargs = chain_kwargs or {} [248](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:248) if ( [249](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:249) "allowed_comparators" not in chain_kwargs [250](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:250) and structured_query_translator.allowed_comparators is not None [251](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:251) ): File [~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:119](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:119), in _get_builtin_translator(vectorstore) [116](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:116) except ImportError: [117](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:117) pass --> [119](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:119) raise ValueError( [120](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:120) f"Self query retriever with Vector Store type {vectorstore.__class__}" [121](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:121) f" not supported." [122](https://file+.vscode-resource.vscode-cdn.net/Users/zhanghaining/streamlit/~/streamlit/.conda/lib/python3.11/site-packages/langchain/retrievers/self_query/base.py:122) ) ValueError: Self query retriever with Vector Store type <class 'langchain_postgres.vectorstores.PGVector'> not supported. ### Description Altough the self query retriver supports PGVector, however, I found that the [source code ](https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/retrievers/self_query/base.py)(https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/retrievers/self_query/base.py) refers to the class in the langchain_community package [source code](https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/vectorstores/pgvector.py) which is going to get deprecated soon, the recommended PGVector code should be a new one from langchain_postgres.vectorstores import PGVector. Can you fix this? Is there any workaround? ### System Info angchain==0.1.16 langchain-cohere==0.1.3 langchain-community==0.0.32 langchain-core==0.1.42 langchain-elasticsearch==0.1.2 langchain-openai==0.1.3 langchain-postgres==0.0.3 langchain-text-splitters==0.0.1
Self query retriever with Vector Store type <class 'langchain_postgres.vectorstores.PGVector'> not supported.
https://api.github.com/repos/langchain-ai/langchain/issues/20655/comments
8
2024-04-19T10:07:38Z
2024-06-20T13:47:36Z
https://github.com/langchain-ai/langchain/issues/20655
2,252,596,353
20,655
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code pip install langchain pip install langchain-text-splitters from langchain_text_splitters import HTMLSectionSplitter ### Error Message and Stack Trace (if applicable) _No response_ ### Description Since i noticed that "HTMLSectionSplitter" was released in [v0.1.15](https://github.com/langchain-ai/langchain/releases/tag/v0.1.15), i upgraded/reinstalled "Langchain" & "langchain-text-splitters" for introducing this new splitter into my project followed by the instruction in [here](https://python.langchain.com/docs/modules/data_connection/document_transformers/). But the new splitter is not found in new package. I checked the latest package of "langchain-text-splitters" in [pypi](https://pypi.org/project/langchain-text-splitters/), the files in package are not the latest version in github. init file in downloaded pypi package: ![Snipaste_2024-04-19_14-27-59](https://github.com/langchain-ai/langchain/assets/120713349/213bd069-07ab-47eb-b790-894b6a276ec3) same file in github: ![Snipaste_2024-04-19_14-29-14](https://github.com/langchain-ai/langchain/assets/120713349/60c9b42d-e160-456f-9a09-f89f82a6b6ff) How can i use this splitter now? ### System Info platform: windows 10 python version: 3.12.3
"HTMLSectionSplitter" is not accessible in latest langchain-text-splitters package
https://api.github.com/repos/langchain-ai/langchain/issues/20644/comments
9
2024-04-19T06:32:53Z
2024-08-09T16:06:57Z
https://github.com/langchain-ai/langchain/issues/20644
2,252,190,610
20,644
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code The following is the official test case. Just replacing `# Foo\n\n` with `\ufeff# Foo\n\n` will cause the test case to fail. ```python def test_md_header_text_splitter_1() -> None: """Test markdown splitter by header: Case 1.""" markdown_document = ( "\ufeff# Foo\n\n" " ## Bar\n\n" "Hi this is Jim\n\n" "Hi this is Joe\n\n" " ## Baz\n\n" " Hi this is Molly" ) headers_to_split_on = [ ("#", "Header 1"), ("##", "Header 2"), ] markdown_splitter = MarkdownHeaderTextSplitter( headers_to_split_on=headers_to_split_on, ) output = markdown_splitter.split_text(markdown_document) expected_output = [ Document( page_content="Hi this is Jim \nHi this is Joe", metadata={"Header 1": "Foo", "Header 2": "Bar"}, ), Document( page_content="Hi this is Molly", metadata={"Header 1": "Foo", "Header 2": "Baz"}, ), ] assert output == expected_output ``` ### Error Message and Stack Trace (if applicable) _No response_ ### Description chunk metadata is empty ### System Info langchain==0.1.14 langchain-community==0.0.31 langchain-core==0.1.40 langchain-experimental==0.0.56 langchain-openai==0.1.1 langchain-text-splitters==0.0.1 langchainhub==0.1.15 macOS 14.3.1 Python 3.11.4
MarkdownHeaderTextSplitter Fails to Parse Headers with non-printable characters
https://api.github.com/repos/langchain-ai/langchain/issues/20643/comments
0
2024-04-19T06:23:35Z
2024-04-26T08:51:55Z
https://github.com/langchain-ai/langchain/issues/20643
2,252,178,705
20,643
[ "langchain-ai", "langchain" ]
### Checked other resources - [X] I added a very descriptive title to this issue. - [X] I searched the LangChain documentation with the integrated search. - [X] I used the GitHub search to find a similar question and didn't find it. - [X] I am sure that this is a bug in LangChain rather than my code. - [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package). ### Example Code The following code *used to* pass mypy checks until I updated langchain_core from 0.1.31 to 0.1.44 ``` python from langchain.output_parsers import PydanticOutputParser from langchain_core.pydantic_v1 import BaseModel, Field from langchain_core.language_models import BaseChatModel class InputSourceResponse(BaseModel): """ Response for Input Source Query """ input_sources: dict[str, str] = Field( description=('Input source dictionary for the provided function where ' 'key is <SUPERTYPE> and value is <SUBTYPE> ' '(set <SUBTYPE> to NONE if no subtype exists).' ) ) explanation: str = Field( description='Explanation for input sources for the provided function') def do_parser(llm: BaseChatModel, input: str) -> InputSourceResponse: parser = PydanticOutputParser(pydantic_object=InputSourceResponse) res: InputSourceResponse = (llm | parser).invoke(input) return res ``` Now I get this mypy error message: lacrosse_llm/langchain_bug.py:19: error: Value of type variable "TBaseModel" of "PydanticOutputParser" cannot be "InputSourceResponse" [type-var] ### Error Message and Stack Trace (if applicable) ``` langchain_bug.py:19: error: Value of type variable "TBaseModel" of "PydanticOutputParser" cannot be "InputSourceResponse" [type-var] ``` ### Description * I defined a PydanticOutputParser that used to typecheck as correct, but now it seems that it does not recognize my `InputSourceResponse` as being an acceptable value for `TBaseModel`. * `TBaseModel` is defined as follows in `pydantic.py`: ``` python if PYDANTIC_MAJOR_VERSION < 2: PydanticBaseModel = pydantic.BaseModel else: from pydantic.v1 import BaseModel # pydantic: ignore # Union type needs to be last assignment to PydanticBaseModel to make mypy happy. PydanticBaseModel = Union[BaseModel, pydantic.BaseModel] # type: ignore TBaseModel = TypeVar("TBaseModel", bound=PydanticBaseModel) ``` * As far as I can tell, this should be OK -- it seems now that expecting the `PydanticOutputParser` to produce an instance of its `pydantic_object` is somehow failing. Note that the line that just defines `parser` above is not sufficient to cause mypy to error. So something seems to be wrong in terms of the production of the result of invoking the parser. ### System Info langchain==0.1.16 langchain-anthropic==0.1.11 langchain-community==0.0.33 langchain-core==0.1.44 langchain-google-vertexai==1.0.1 langchain-openai==0.0.8 langchain-text-splitters==0.0.1 MacOS 14.4.1 python version = 3.12.2
New mypy type error from PydanticOutputParser
https://api.github.com/repos/langchain-ai/langchain/issues/20634/comments
3
2024-04-19T01:26:07Z
2024-07-26T16:07:37Z
https://github.com/langchain-ai/langchain/issues/20634
2,251,887,203
20,634