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"
] | ### Issue you'd like to raise.
pip list:
- langchain 0.0.314
- langchain-core 0.0.8
```python
prompt_template = """
### [INST]
Assistant is a large language model trained by Mistral.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.
Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
Context:
------
Assistant has access to the following tools:
{tools}
To use a tool, please use the following format:
'''
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
'''
When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
'''
Thought: Do I need to use a tool? No
Final Answer: [your response here]
'''
Begin!
Previous conversation history:
{chat_history}
New input: {input}
Current Scratchpad:
{agent_scratchpad}
[/INST]
"""
# Create prompt from prompt template
prompt = PromptTemplate(
input_variables=['agent_scratchpad', 'chat_history', 'input', 'tool_names', 'tools'],
template=prompt_template,
)
prompt = prompt.partial(
tools=render_text_description(tools),
tool_names=", ".join([t.name for t in tools]),
)
# Create llm chain
llm_chain = LLMChain(llm=mistral_llm, prompt=prompt)
from langchain.agents import AgentOutputParser
from langchain_core.agents import AgentAction, AgentFinish
import re
from typing import List, Union
class CustomOutputParser(AgentOutputParser):
def parse(self, output) -> Union[AgentAction, AgentFinish]:
print(output)
output = ' '.join(output.split())
# Check if the output contains 'Final Answer:'
if 'Final Answer:' in output:
# Extract the final answer from the output
final_answer = output.split('Final Answer:')[1].strip()
print(final_answer)
agent_finish = AgentFinish(
# Return values is generally always a dictionary with a single `output` key
# It is not recommended to try anything else at the moment :)
return_values={"output": final_answer},
log=output,
)
print(agent_finish)
return agent_finish
else:
# Handle other cases or raise an error
raise ValueError("Unexpected output format")
output_parser = CustomOutputParser()
# Create an agent with your LLMChain
agent = ConversationalAgent(llm_chain=llm_chain , output_parser=output_parser)
memory = ConversationBufferMemory(memory_key="chat_history")
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, memory=memory)
agent_executor.run("Hi, I'm Madhav?")
```
I get the following output:
```python
> Entering new AgentExecutor chain...
Error in StdOutCallbackHandler.on_agent_action callback: 'tuple' object has no attribute 'log'
Thought: Do I need to use a tool? No
Final Answer: Hello, Madhav! How can I assist you today?
Hello, Madhav! How can I assist you today?
return_values={'output': 'Hello, Madhav! How can I assist you today?'} log='Thought: Do I need to use a tool? No Final Answer: Hello, Madhav! How can I assist you today?'
File /opt/conda/lib/python3.10/site-packages/langchain/agents/agent.py:1141, in AgentExecutor._call(self, inputs, run_manager)
1139 # We now enter the agent loop (until it returns something).
1140 while self._should_continue(iterations, time_elapsed):
-> 1141 next_step_output = self._take_next_step(
1142 name_to_tool_map,
1143 color_mapping,
1144 inputs,
1145 intermediate_steps,
1146 run_manager=run_manager,
1147 )
1148 if isinstance(next_step_output, AgentFinish):
1149 return self._return(
1150 next_step_output, intermediate_steps, run_manager=run_manager
1151 )
File /opt/conda/lib/python3.10/site-packages/langchain/agents/agent.py:983, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager)
981 run_manager.on_agent_action(agent_action, color="green")
982 # Otherwise we lookup the tool
--> 983 if agent_action.tool in name_to_tool_map:
984 tool = name_to_tool_map[agent_action.tool]
985 return_direct = tool.return_direct
AttributeError: 'tuple' object has no attribute 'tool'
...
```
I'm having trouble understading what is happening here. I'm certain my output contains `Final Answer` so I'd assume I need an `ActionFinish` as per [this tutorial](https://python.langchain.com/docs/modules/agents/how_to/custom_llm_agent#output-parser).
Any tips would be much appreciated!
### Suggestion:
_No response_ | Issue: Unable to properly parse output of custom chat agent. | https://api.github.com/repos/langchain-ai/langchain/issues/14185/comments | 5 | 2023-12-02T22:59:44Z | 2024-07-02T16:08:07Z | https://github.com/langchain-ai/langchain/issues/14185 | 2,022,245,713 | 14,185 |
[
"langchain-ai",
"langchain"
] | ### Feature request
I think Langchain should have a Document Loader that would allow reading all issues from provided project as documents.
### Motivation
Langchain currently has agent for JIRA, but there is no Document Loader that would allow to read all issues from specified project and store them in Vector database. This could be a very useful tool for RAG usecases and building internal knowledge bases in the companies.
### Your contribution
I can create a PR for this issue. | Add new Document Loader for JIRA | https://api.github.com/repos/langchain-ai/langchain/issues/14180/comments | 1 | 2023-12-02T20:48:41Z | 2024-03-17T16:08:07Z | https://github.com/langchain-ai/langchain/issues/14180 | 2,022,198,845 | 14,180 |
[
"langchain-ai",
"langchain"
] | ### Feature request
Looks like it should be doable to have Cloudflare Vectorize support, as there's a HTTP API for Vectorize.
https://developers.cloudflare.com/api/operations/vectorize-list-vectorize-indexes
### Motivation
Similar to langchain-js, it would be nice if we could use Cloudflare Vectorize when using LangChain with Python. It would allow us to use the same vector store for both our TypeScript Workers and Python Lambdas.
https://js.langchain.com/docs/integrations/vectorstores/cloudflare_vectorize
### Your contribution
N/A sadly | Cloudflare Vectorize Support | https://api.github.com/repos/langchain-ai/langchain/issues/14179/comments | 4 | 2023-12-02T20:43:58Z | 2024-07-30T03:32:28Z | https://github.com/langchain-ai/langchain/issues/14179 | 2,022,197,127 | 14,179 |
[
"langchain-ai",
"langchain"
] | ### System Info
- LangChain - 0.0.344
- python version - 3.11.6
- platform - windows11
### Who can help?
https://python.langchain.com/docs/modules/agents/agent_types/openai_functions_agent
When running the above example, the following error occurs.
-----------------------------------------------------------------
```shell
> Entering new AgentExecutor chain...
Invoking: `Search` with `Leo DiCaprio girlfriend`
Vittoria Ceretti
Invoking: `Calculator` with `age ^ 0.43`
> Entering new LLMMathChain chain...
age ^ 0.43```text
Traceback (most recent call last):
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\numexpr\necompiler.py", line 760, in getArguments
a = local_dict[name]
~~~~~~~~~~^^^^^^
KeyError: 'age'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\llm_math\base.py", line 89, in _evaluate_expression
numexpr.evaluate(
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\numexpr\necompiler.py", line 975, in evaluate
raise e
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\numexpr\necompiler.py", line 874, in validate
arguments = getArguments(names, local_dict, global_dict, _frame_depth=_frame_depth)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\numexpr\necompiler.py", line 762, in getArguments
a = global_dict[name]
~~~~~~~~~~~^^^^^^
KeyError: 'age'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\hyung\GitHubProjects\LangChainStudy\agent\openai_functions.py", line 76, in <module>
agent_executor.invoke(
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\base.py", line 89, in invoke
return self(
^^^^^
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\base.py", line 312, in __call__
raise e
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\base.py", line 306, in __call__
self._call(inputs, run_manager=run_manager)
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\agents\agent.py", line 1312, in _call
next_step_output = self._take_next_step(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\agents\agent.py", line 1038, in _take_next_step
[
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\agents\agent.py", line 1038, in <listcomp>
[
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\agents\agent.py", line 1134, in _iter_next_step
observation = tool.run(
^^^^^^^^^
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain_core\tools.py", line 365, in run
raise e
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain_core\tools.py", line 337, in run
self._run(*tool_args, run_manager=run_manager, **tool_kwargs)
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain_core\tools.py", line 510, in _run
self.func(
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\base.py", line 507, in run
age ** 0.43
'''
...numexpr.evaluate("age ** 0.43")...
return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\base.py", line 312, in __call__
raise e
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\base.py", line 306, in __call__
self._call(inputs, run_manager=run_manager)
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\llm_math\base.py", line 158, in _call
return self._process_llm_result(llm_output, _run_manager)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\llm_math\base.py", line 112, in _process_llm_result
output = self._evaluate_expression(expression)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hyung\AppData\Local\pypoetry\Cache\virtualenvs\langchainstudy-esJm8fcP-py3.11\Lib\site-packages\langchain\chains\llm_math\base.py", line 96, in _evaluate_expression
raise ValueError(
ValueError: LLMMathChain._evaluate("
age ** 0.43
") raised error: 'age'. Please try again with a valid numerical expression
Process finished with exit code 1
'''
```
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [X] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [X] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
https://python.langchain.com/docs/modules/agents/agent_types/openai_functions_agent
Run the example
### Expected behavior
```shell
> Entering new AgentExecutor chain...
Invoking: `Search` with `Leo DiCaprio girlfriend`
Vittoria Ceretti
Invoking: `Calculator` with `25 ^ 0.43`
> Entering new LLMMathChain chain...
25 ^ 0.43'''text
/25 ** 0.43
'''
...numexpr.evaluate("25 ** 0.43")...
Answer: 3.991298452658078
> Finished chain.
Answer: 3.991298452658078Leo DiCaprio's girlfriend is Vittoria Ceretti. Her current age raised to the power of 0.43 is approximately 3.99.
> Finished chain.
``` | Issues: OpenAI functions Agent official example Error | https://api.github.com/repos/langchain-ai/langchain/issues/14177/comments | 1 | 2023-12-02T19:29:23Z | 2023-12-05T04:53:44Z | https://github.com/langchain-ai/langchain/issues/14177 | 2,022,175,407 | 14,177 |
[
"langchain-ai",
"langchain"
] | ### Issue with current documentation:
Is there a way to conditionally create a Pandas agent using `create_pandas_dataframe_agent` or update the DataFrame the agent has access to?
Say I have an agent that has access to tools like so:
```python
@tool()
def f(query: str) -> pd.DataFrame:
...
agent = initialize_agent(
tools=[f, PythonREPLTool()],
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
handle_parsing_errors=True,
)
```
Since `create_pandas_dataframe_agent` takes the `df` argument, I can't create this agent unless/until the tool `f` is called, producing the DataFrame. But without the specialized Pandas agent, the regular agent seems to be producing bad/bogus Python, trying to filter the DataFrame (either with syntax errors or just doing the wrong thing). Is there a way to either 1) call`create_pandas_dataframe_agent` ahead of time and then later update the contents of the `df` after the function call or 2) create a Pandas agent on-the-fly inside `f` to answer the question (I haven't found a way to pass the current `Thought` content to the nested agent in this case)?
### Idea or request for content:
It would be helpful to see how to work with Pandas data when reading dynamically created DataFrames coming from functions that agents may or may not call. | DOC: Is there a way to conditionally create/update a Pandas DataFrame agent? | https://api.github.com/repos/langchain-ai/langchain/issues/14176/comments | 2 | 2023-12-02T17:08:46Z | 2024-03-17T16:07:57Z | https://github.com/langchain-ai/langchain/issues/14176 | 2,022,127,350 | 14,176 |
[
"langchain-ai",
"langchain"
] | ### System Info
platform: Vagrant - Ubuntu 2204
python: 3.9.18
langchain version: 0.0.344
langchain core: 0.0.8
clarifai: 9.10.4
### Who can help?
@hwchase17 @agola11
### Information
- [X] The official example notebooks/scripts
- [x] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
1. Install the latest version of clarifai (9.10.4)
2. Run the example: https://python.langchain.com/docs/integrations/llms/clarifai
``` bash
Could not import clarifai python package. Please install it with `pip install clarifai`.
File 'clarifai.py', line 77, in validate_environment:
raise ImportError( Traceback (most recent call last):
File "/home/vagrant/.virtualenvs/env/lib/python3.9/site-packages/langchain/llms/clarifai.py", line 74, in validate_environment
from clarifai.auth.helper import ClarifaiAuthHelper
ModuleNotFoundError: No module named 'clarifai.auth'
```
### Expected behavior
I expect **ClarifaiAuthHelper** to import correctly.
In the latest version of clarifai **ClarifaiAuthHelper** is imported in this way:
``` python
from clarifai.client.auth.helper import ClarifaiAuthHelper
``` | ModuleNotFoundError: No module named 'clarifai.auth' | https://api.github.com/repos/langchain-ai/langchain/issues/14175/comments | 1 | 2023-12-02T15:28:09Z | 2023-12-18T20:34:37Z | https://github.com/langchain-ai/langchain/issues/14175 | 2,022,085,674 | 14,175 |
[
"langchain-ai",
"langchain"
] | ### System Info
langchain version :
langchain 0.0.344
langchain-core 0.0.8
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [X] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
code:
from langchain.document_loaders.csv_loader import CSVLoader
loader = CSVLoader(file_path='./test.csv')
data = loader.load()
### Expected behavior
exception:
Traceback (most recent call last):
File "/Users/liucong/opt/miniconda3/envs/310-test/lib/python3.10/site-packages/langchain_core/__init__.py", line 4, in <module>
__version__ = metadata.version(__package__)
AttributeError: partially initialized module 'importlib.metadata' has no attribute 'version' (most likely due to a circular import)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Users/liucong/opt/miniconda3/envs/310-test/lib/python3.10/site-packages/langchain/__init__.py", line 4, in <module>
from importlib import metadata
File "/Users/liucong/opt/miniconda3/envs/310-test/lib/python3.10/importlib/metadata/__init__.py", line 4, in <module>
import csv
File "/Users/liucong/PycharmProjects/llm_learn/lang_chain/data_connection/csv.py", line 1, in <module>
from langchain.document_loaders.csv_loader import CSVLoader
File "/Users/liucong/opt/miniconda3/envs/310-test/lib/python3.10/site-packages/langchain/document_loaders/__init__.py", line 18, in <module>
from langchain.document_loaders.acreom import AcreomLoader
File "/Users/liucong/opt/miniconda3/envs/310-test/lib/python3.10/site-packages/langchain/document_loaders/acreom.py", line 5, in <module>
from langchain_core.documents import Document
File "/Users/liucong/opt/miniconda3/envs/310-test/lib/python3.10/site-packages/langchain_core/__init__.py", line 5, in <module>
except metadata.PackageNotFoundError:
AttributeError: partially initialized module 'importlib.metadata' has no attribute 'PackageNotFoundError' (most likely due to a circular import) | BUG: csv loader exception, AttributeError: partially initialized module 'importlib.metadata' has no attribute 'version' (most likely due to a circular import) | https://api.github.com/repos/langchain-ai/langchain/issues/14173/comments | 3 | 2023-12-02T12:42:14Z | 2024-04-07T16:06:39Z | https://github.com/langchain-ai/langchain/issues/14173 | 2,022,026,571 | 14,173 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Please help!
Error:
GGML_ASSERT: C:\Users\user\AppData\Local\Temp\pip-install-l0_yao9s\llama-cpp-python_686671b6d7b8440a98e23acb5bc6a41a\vendor\llama.cpp\ggml.c:15149: cgraph->nodes[cgraph->n_nodes - 1] == tensor
GGML_ASSERT: C:\Users\user\AppData\Local\Temp\pip-install-l0_yao9s\llama-cpp-python_686671b6d7b8440a98e23acb5bc6a41a\vendor\llama.cpp\ggml.c:4326: ggml_nelements(a) == (ne0ne1ne2*ne3)
Repeated trials yield same results.
Local llm: TheBloke/Llama-2-7B-Chat-GGUF (llama-2-7b-chat.Q6_K.gguf)
Embedding: BAAI/bge-large-en-v1.5
```
import os
os.environ['OPENAI_API_KEY'] = 'dummy_key'
# import paperscraper
from paperqa import Docs
from langchain.llms.llamacpp import LlamaCpp
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain.callbacks.manager import CallbackManager
from langchain.embeddings import LlamaCppEmbeddings
from langchain.embeddings import HuggingFaceBgeEmbeddings
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
# Make sure the model path is correct for your system!
llm = LlamaCpp(
model_path="C:/paper-qa/models/llama-2-7b-chat.Q6_K.gguf", callbacks=[StreamingStdOutCallbackHandler()],
)
model_name = "BAAI/bge-large-en-v1.5"
model_kwargs = {'device': 'cpu'}
encode_kwargs = {'normalize_embeddings': True}
embeddings = HuggingFaceBgeEmbeddings(
model_name=model_name,
# model_kwargs=model_kwargs,
# encode_kwargs=encode_kwargs,
cache_folder="C:\paper-qa\models"
)
# embeddings = LlamaCppEmbeddings(
# model_path="C:/paper-qa/models/bge-large-en-v1_5_pytorch_model.bin"
# )
# model_name = "BAAI/bge-large-en-v1.5"
# model_kwargs = {'device': 'cpu'}
# encode_kwargs = {'normalize_embeddings': False}
# hf = HuggingFaceEmbeddings(
# model_name=model_name,
# model_kwargs=model_kwargs,
# encode_kwargs=encode_kwargs
# )
docs = Docs(llm=llm, embeddings=embeddings)
# keyword_search = 'bispecific antibody manufacture'
# papers = paperscraper.search_papers(keyword_search, limit=2)
# for path,data in papers.items():
# try:
# docs.add(path,chunk_chars=500)
# except ValueError as e:
# print('Could not read', path, e)
path = "C:\\paper-qa\\Source\\The Encyclopedia of the Cold War_90-95.pdf"
print("Before adding document")
docs.add(path,chunk_chars=500)
print("Document added")
answer = docs.query("Summarize 2 interesting events of the cold war from the book.")
print("Queried.")
print(answer)
```
whole output
```
llama_model_loader: loaded meta data with 19 key-value pairs and 291 tensors from C:/paper-qa/models/llama-2-7b-chat.Q6_K.gguf (version GGUF V2)
llama_model_loader: - tensor 0: token_embd.weight q6_K [ 4096, 32000,
1, 1 ]
llama_model_loader: - tensor 1: blk.0.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 2: blk.0.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 3: blk.0.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 4: blk.0.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 5: blk.0.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 6: blk.0.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 7: blk.0.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 8: blk.0.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 9: blk.0.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 10: blk.1.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 11: blk.1.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 12: blk.1.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 13: blk.1.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 14: blk.1.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 15: blk.1.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 16: blk.1.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 17: blk.1.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 18: blk.1.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 19: blk.10.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 20: blk.10.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 21: blk.10.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 22: blk.10.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 23: blk.10.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 24: blk.10.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 25: blk.10.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 26: blk.10.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 27: blk.10.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 28: blk.11.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 29: blk.11.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 30: blk.11.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 31: blk.11.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 32: blk.11.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 33: blk.11.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 34: blk.11.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 35: blk.11.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 36: blk.11.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 37: blk.12.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 38: blk.12.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 39: blk.12.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 40: blk.12.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 41: blk.12.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 42: blk.12.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 43: blk.12.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 44: blk.12.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 45: blk.12.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 46: blk.13.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 47: blk.13.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 48: blk.13.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 49: blk.13.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 50: blk.13.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 51: blk.13.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 52: blk.13.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 53: blk.13.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 54: blk.13.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 55: blk.14.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 56: blk.14.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 57: blk.14.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 58: blk.14.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 59: blk.14.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 60: blk.14.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 61: blk.14.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 62: blk.14.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 63: blk.14.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 64: blk.15.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 65: blk.15.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 66: blk.15.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 67: blk.15.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 68: blk.15.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 69: blk.15.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 70: blk.15.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 71: blk.15.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 72: blk.15.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 73: blk.16.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 74: blk.16.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 75: blk.16.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 76: blk.16.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 77: blk.16.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 78: blk.16.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 79: blk.16.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 80: blk.16.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 81: blk.16.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 82: blk.17.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 83: blk.17.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 84: blk.17.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 85: blk.17.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 86: blk.17.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 87: blk.17.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 88: blk.17.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 89: blk.17.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 90: blk.17.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 91: blk.18.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 92: blk.18.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 93: blk.18.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 94: blk.18.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 95: blk.18.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 96: blk.18.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 97: blk.18.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 98: blk.18.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 99: blk.18.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 100: blk.19.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 101: blk.19.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 102: blk.19.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 103: blk.19.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 104: blk.19.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 105: blk.19.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 106: blk.19.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 107: blk.19.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 108: blk.19.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 109: blk.2.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 110: blk.2.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 111: blk.2.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 112: blk.2.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 113: blk.2.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 114: blk.2.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 115: blk.2.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 116: blk.2.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 117: blk.2.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 118: blk.20.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 119: blk.20.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 120: blk.20.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 121: blk.20.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 122: blk.20.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 123: blk.20.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 124: blk.20.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 125: blk.20.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 126: blk.20.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 127: blk.21.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 128: blk.21.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 129: blk.21.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 130: blk.21.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 131: blk.21.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 132: blk.21.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 133: blk.21.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 134: blk.21.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 135: blk.21.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 136: blk.22.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 137: blk.22.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 138: blk.22.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 139: blk.22.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 140: blk.22.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 141: blk.22.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 142: blk.22.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 143: blk.22.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 144: blk.22.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 145: blk.23.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 146: blk.23.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 147: blk.23.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 148: blk.23.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 149: blk.23.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 150: blk.23.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 151: blk.23.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 152: blk.23.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 153: blk.23.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 154: blk.3.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 155: blk.3.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 156: blk.3.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 157: blk.3.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 158: blk.3.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 159: blk.3.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 160: blk.3.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 161: blk.3.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 162: blk.3.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 163: blk.4.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 164: blk.4.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 165: blk.4.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 166: blk.4.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 167: blk.4.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 168: blk.4.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 169: blk.4.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 170: blk.4.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 171: blk.4.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 172: blk.5.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 173: blk.5.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 174: blk.5.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 175: blk.5.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 176: blk.5.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 177: blk.5.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 178: blk.5.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 179: blk.5.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 180: blk.5.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 181: blk.6.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 182: blk.6.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 183: blk.6.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 184: blk.6.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 185: blk.6.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 186: blk.6.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 187: blk.6.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 188: blk.6.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 189: blk.6.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 190: blk.7.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 191: blk.7.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 192: blk.7.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 193: blk.7.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 194: blk.7.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 195: blk.7.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 196: blk.7.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 197: blk.7.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 198: blk.7.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 199: blk.8.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 200: blk.8.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 201: blk.8.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 202: blk.8.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 203: blk.8.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 204: blk.8.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 205: blk.8.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 206: blk.8.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 207: blk.8.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 208: blk.9.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 209: blk.9.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 210: blk.9.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 211: blk.9.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 212: blk.9.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 213: blk.9.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 214: blk.9.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 215: blk.9.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 216: blk.9.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 217: output.weight q6_K [ 4096, 32000,
1, 1 ]
llama_model_loader: - tensor 218: blk.24.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 219: blk.24.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 220: blk.24.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 221: blk.24.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 222: blk.24.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 223: blk.24.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 224: blk.24.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 225: blk.24.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 226: blk.24.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 227: blk.25.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 228: blk.25.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 229: blk.25.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 230: blk.25.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 231: blk.25.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 232: blk.25.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 233: blk.25.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 234: blk.25.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 235: blk.25.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 236: blk.26.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 237: blk.26.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 238: blk.26.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 239: blk.26.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 240: blk.26.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 241: blk.26.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 242: blk.26.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 243: blk.26.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 244: blk.26.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 245: blk.27.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 246: blk.27.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 247: blk.27.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 248: blk.27.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 249: blk.27.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 250: blk.27.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 251: blk.27.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 252: blk.27.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 253: blk.27.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 254: blk.28.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 255: blk.28.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 256: blk.28.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 257: blk.28.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 258: blk.28.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 259: blk.28.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 260: blk.28.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 261: blk.28.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 262: blk.28.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 263: blk.29.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 264: blk.29.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 265: blk.29.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 266: blk.29.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 267: blk.29.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 268: blk.29.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 269: blk.29.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 270: blk.29.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 271: blk.29.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 272: blk.30.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 273: blk.30.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 274: blk.30.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 275: blk.30.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 276: blk.30.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 277: blk.30.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 278: blk.30.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 279: blk.30.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 280: blk.30.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 281: blk.31.attn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 282: blk.31.ffn_down.weight q6_K [ 11008, 4096,
1, 1 ]
llama_model_loader: - tensor 283: blk.31.ffn_gate.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 284: blk.31.ffn_up.weight q6_K [ 4096, 11008,
1, 1 ]
llama_model_loader: - tensor 285: blk.31.ffn_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - tensor 286: blk.31.attn_k.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 287: blk.31.attn_output.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 288: blk.31.attn_q.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 289: blk.31.attn_v.weight q6_K [ 4096, 4096,
1, 1 ]
llama_model_loader: - tensor 290: output_norm.weight f32 [ 4096, 1,
1, 1 ]
llama_model_loader: - kv 0: general.architecture str = llama
llama_model_loader: - kv 1: general.name str = LLaMA v2
llama_model_loader: - kv 2: llama.context_length u32 = 4096
llama_model_loader: - kv 3: llama.embedding_length u32 = 4096
llama_model_loader: - kv 4: llama.block_count u32 = 32llama_model_loader: - kv 5: llama.feed_forward_length u32 = 11008
llama_model_loader: - kv 6: llama.rope.dimension_count u32 = 128
llama_model_loader: - kv 7: llama.attention.head_count u32 = 32llama_model_loader: - kv 8: llama.attention.head_count_kv u32 = 32llama_model_loader: - kv 9: llama.attention.layer_norm_rms_epsilon f32 = 0.000001
llama_model_loader: - kv 10: general.file_type u32 = 18llama_model_loader: - kv 11: tokenizer.ggml.model str = llama
llama_model_loader: - kv 12: tokenizer.ggml.tokens arr[str,32000] = ["<unk>", "<s>", "</s>", "<0x00>", "<...
llama_model_loader: - kv 13: tokenizer.ggml.scores arr[f32,32000] = [0.000000, 0.000000, 0.000000, 0.0000...
llama_model_loader: - kv 14: tokenizer.ggml.token_type arr[i32,32000] = [2, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...
llama_model_loader: - kv 15: tokenizer.ggml.bos_token_id u32 = 1
llama_model_loader: - kv 16: tokenizer.ggml.eos_token_id u32 = 2
llama_model_loader: - kv 17: tokenizer.ggml.unknown_token_id u32 = 0
llama_model_loader: - kv 18: general.quantization_version u32 = 2
llama_model_loader: - type f32: 65 tensors
llama_model_loader: - type q6_K: 226 tensors
llm_load_vocab: special tokens definition check successful ( 259/32000 ).
llm_load_print_meta: format = GGUF V2
llm_load_print_meta: arch = llama
llm_load_print_meta: vocab type = SPM
llm_load_print_meta: n_vocab = 32000
llm_load_print_meta: n_merges = 0
llm_load_print_meta: n_ctx_train = 4096
llm_load_print_meta: n_embd = 4096
llm_load_print_meta: n_head = 32
llm_load_print_meta: n_head_kv = 32
llm_load_print_meta: n_layer = 32
llm_load_print_meta: n_rot = 128
llm_load_print_meta: n_gqa = 1
llm_load_print_meta: f_norm_eps = 0.0e+00
llm_load_print_meta: f_norm_rms_eps = 1.0e-06
llm_load_print_meta: f_clamp_kqv = 0.0e+00
llm_load_print_meta: f_max_alibi_bias = 0.0e+00
llm_load_print_meta: n_ff = 11008
llm_load_print_meta: rope scaling = linear
llm_load_print_meta: freq_base_train = 10000.0
llm_load_print_meta: freq_scale_train = 1
llm_load_print_meta: n_yarn_orig_ctx = 4096
llm_load_print_meta: rope_finetuned = unknown
llm_load_print_meta: model type = 7B
llm_load_print_meta: model ftype = mostly Q6_K
llm_load_print_meta: model params = 6.74 B
llm_load_print_meta: model size = 5.15 GiB (6.56 BPW)
llm_load_print_meta: general.name = LLaMA v2
llm_load_print_meta: BOS token = 1 '<s>'
llm_load_print_meta: EOS token = 2 '</s>'
llm_load_print_meta: UNK token = 0 '<unk>'
llm_load_print_meta: LF token = 13 '<0x0A>'
llm_load_tensors: ggml ctx size = 0.11 MiB
llm_load_tensors: mem required = 5272.45 MiB
....................................................................................................
llama_new_context_with_model: n_ctx = 512
llama_new_context_with_model: freq_base = 10000.0
llama_new_context_with_model: freq_scale = 1
llama_new_context_with_model: kv self size = 256.00 MiB
llama_build_graph: non-view tensors processed: 740/740
llama_new_context_with_model: compute buffer total size = 4.16 MiB
AVX = 1 | 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 = 0 | SSE3 = 1 | SSSE3 = 0 | VSX = 0
|
Before adding document
Abdullah I of Jordan. "Soldier, Diplomat, and King of Jordan." The Oxford Encyclopedia of the
Modern World, vol. 1, Oxford University Press, 2023, pp. 56-57.
llama_print_timings: load time = 7311.60 ms
llama_print_timings: sample time = 18.23 ms / 55 runs ( 0.33 ms per token,
3016.67 tokens per second)
llama_print_timings: prompt eval time = 53923.10 ms / 190 tokens ( 283.81 ms per token,
3.52 tokens per second)
llama_print_timings: eval time = 19552.25 ms / 54 runs ( 362.08 ms per token,
2.76 tokens per second)
llama_print_timings: total time = 73785.66 ms
Document added
Llama.generate: prefix-match hit
Llama.generate: prefix-match hit
Llama.generate: prefix-match hit
Llama.generate: prefix-match hit
Llama.generate: prefix-match hit
GGML_ASSERT: C:\Users\user\AppData\Local\Temp\pip-install-l0_yao9s\llama-cpp-python_686671b6d7b8440a98e23acb5bc6a41a\vendor\llama.cpp\ggml.c:15149: cgraph->nodes[cgraph->n_nodes - 1] == tensor
GGML_ASSERT: C:\Users\user\AppData\Local\Temp\pip-install-l0_yao9s\llama-cpp-python_686671b6d7b8440a98e23acb5bc6a41a\vendor\llama.cpp\ggml.c:4326: ggml_nelements(a) == (ne0*ne1*ne2*ne3)
PS C:\paper-qa>
```
### Suggestion:
_No response_ | Local LLM ISSUE GGML_ASSERT | https://api.github.com/repos/langchain-ai/langchain/issues/14169/comments | 6 | 2023-12-02T09:07:35Z | 2024-03-18T16:07:14Z | https://github.com/langchain-ai/langchain/issues/14169 | 2,021,955,776 | 14,169 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
```python
from langchain.chains import create_extraction_chain
from langchain.chat_models import ChatOpenAI
import dotenv
dotenv.load_dotenv()
# Schema
schema = {
"properties": {
"name": {"type": "string"},
"education": {"type": "string"},
"company": {"type": "string"},
},
"required": ["name", "education"],
}
# Input
inp = """小明毕业于北京大学,在微软上班\n小李毕业于清华大学在阿里巴巴上班\n小王毕业于浙江大学在烟草局上班"""
# Run chain
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-1106")
chain = create_extraction_chain(schema, llm)
print(chain.run(inp)[0])
```
```shell
#output
{'name': 'å°\x8fæ\x98\x8e', 'education': 'å\x8c\x97京大å\xad¦', 'company': '微软'}
```
How to fix this Chinese `encoding/decoding` problem?
### Suggestion:
_No response_ | Question about runing Langchain Extraction Demo in Chinese text. | https://api.github.com/repos/langchain-ai/langchain/issues/14168/comments | 4 | 2023-12-02T09:01:35Z | 2023-12-04T02:10:15Z | https://github.com/langchain-ai/langchain/issues/14168 | 2,021,953,293 | 14,168 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Code:
retriever = BM25Retriever.from_documents(
[
Document(page_content="foo"),
Document(page_content="bar"),
Document(page_content="world"),
Document(page_content="hello"),
Document(page_content="foo bar"),
]
)
Error:
---> 30 retriever = BM25Retriever.from_documents(
31 [
32 Document(page_content="foo"),
33 Document(page_content="bar"),
34 Document(page_content="world"),
35 Document(page_content="hello"),
36 Document(page_content="foo bar"),
37 ]
38 )
AttributeError: type object 'BM25Retriever' has no attribute 'from_documents'
### Suggestion:
_No response_ | Issue: 'BM25Retriever' has no attribute 'from_documents' | https://api.github.com/repos/langchain-ai/langchain/issues/14167/comments | 4 | 2023-12-02T08:44:31Z | 2024-03-25T16:06:57Z | https://github.com/langchain-ai/langchain/issues/14167 | 2,021,948,035 | 14,167 |
[
"langchain-ai",
"langchain"
] | ### System Info
langchain: 0.0.339
Python: 3.11.6
I followed instructions in
[https://docs.smith.langchain.com/evaluation/evaluator-implementations](https://docs.smith.langchain.com/evaluation/evaluator-implementations)
`from langsmith import Client
from langchain.smith import RunEvalConfig, run_on_dataset
from backend.tools.self_query_tool import do_self_query
evaluation_config = RunEvalConfig(
evaluators=[
"cot_qa",
]
)
client = Client()
run_on_dataset(
dataset_name="self_query_tool",
llm_or_chain_factory=do_self_query,
client=client,
evaluation=evaluation_config,
verbose=True,
project_name="default",
)`
got this blob code. I used the langsmith UI to create a dataset and a single example.
However when i run the test with
python test/self_query_tool_test.py
i get
`
File "/home/dharshana/.local/share/virtualenvs/turners-virtual-assistant-QSiRQ3G1/lib/python3.11/site-packages/langsmith/client.py", line 1113, in create_project
ls_utils.raise_for_status_with_text(response)
File "/home/dharshana/.local/share/virtualenvs/turners-virtual-assistant-QSiRQ3G1/lib/python3.11/site-packages/langsmith/utils.py", line 85, in raise_for_status_with_text
raise requests.HTTPError(str(e), response.text) from e
requests.exceptions.HTTPError: [Errno 409 Client Error: Conflict for url: https://api.langchain.plus/sessions] {"detail":"Session already exists."}
❯
`
I have never attempted an evaluation of my chain before. Im just calling a function which creates its own llm client and runs
`llm = ChatOpenAI(temperature=0, model="gpt-4-1106-preview")
retriever = SelfQueryRetriever.from_llm(
llm,
vectordb,
document_content_description,
metadata_field_info,
enable_limit=True,
verbose=True
)`
Is there an issue with doign this? I have been using langsmith successfully to log my llm calls and agent actions
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Create a function which does
`
llm = ChatOpenAI(temperature=0, model="gpt-4-1106-preview")
retriever = SelfQueryRetriever.from_llm(
llm,
vectordb,
document_content_description,
metadata_field_info,
enable_limit=True,
verbose=True
)
`
then evaluate the function with
`
evaluation_config = RunEvalConfig(
evaluators=[
"cot_qa",
]
)
client = Client()
run_on_dataset(
dataset_name="self_query_tool",
llm_or_chain_factory=do_self_query,
client=client,
evaluation=evaluation_config,
verbose=True,
project_name="default",
)
`
### Expected behavior
The function is evaluated with test results in the UI | run_on_dataset: Errno 409 Client Error: Session already exists. | https://api.github.com/repos/langchain-ai/langchain/issues/14161/comments | 1 | 2023-12-02T01:44:13Z | 2023-12-02T01:52:08Z | https://github.com/langchain-ai/langchain/issues/14161 | 2,021,798,420 | 14,161 |
[
"langchain-ai",
"langchain"
] | ### System Info
[pydantic_chain_test_code.txt](https://github.com/langchain-ai/langchain/files/13532796/pydantic_chain_test_code.txt)
[error_log.txt](https://github.com/langchain-ai/langchain/files/13532799/error_log.txt)
### Who can help?
@agola11 @hwchase17
The attached code is adopted from the official example from https://python.langchain.com/docs/use_cases/tagging. I am using the AzureChatOpenAI API, but I don't think the cause is related to that. I added an example prompt to ensure that the llm is working properly.
It appears that even when passing in a confirmed subclass of BaseModel, which is pydantic_schema, create_tagging_chain_pydantic(Tags, llm) is triggering validation errors. Please see the attached test code and error log.
### Information
- [X] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [X] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Run the attached code and match it with the attached error log, which shows the version numbers of Python, Langchain and Pydantic. I am running on WIndows 11.:
Python version: 3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23) [MSC v.1916 64 bit (AMD64)]
Langchain version: 0.0.344
Pydantic version: 2.5.2
### Expected behavior
Expected behavior is as shown in the last example on https://python.langchain.com/docs/use_cases/tagging
Tags(sentiment='sad', aggressiveness=5, language='spanish') | create_tagging_chain_pydantic() pydantic schema validation errors | https://api.github.com/repos/langchain-ai/langchain/issues/14159/comments | 2 | 2023-12-02T00:35:53Z | 2023-12-04T20:06:05Z | https://github.com/langchain-ai/langchain/issues/14159 | 2,021,770,513 | 14,159 |
[
"langchain-ai",
"langchain"
] | ### System Info
conda 23.3.1
Python 3.10.6
angchain 0.0.344 pypi_0 pypi
langchain-core 0.0.8 pypi_0 pypi
langchain-experimental 0.0.43 pypi_0 pypi
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [X] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
#This Notebook will show the integration between Generative AI with SAP HANA Cloud
!pip install -q --upgrade langchain boto3 awscli botocore
!pip install -q sqlalchemy-hana langchain_experimental hdbcli
import langchain
from langchain.sql_database import SQLDatabase
from langchain_experimental.sql import SQLDatabaseChain
from langchain.prompts.prompt import PromptTemplate
from langchain.llms.sagemaker_endpoint import LLMContentHandler
from langchain import SagemakerEndpoint
from langchain.llms import bedrock
from urllib.parse import quote
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, select, Table, MetaData, Column, String
import hdbcli
import json
#Next step is to prepare the template for prompt and input to be used by the Generative AI
table_info = "Table Hotel has fields Name, Address, City, State, Zip code. \
Table Room has fields Free or Available, Price. \
Table Customer has fields Customer Number, title, first name, name, address, zip code. \
Table Reservation has fields Reservation Number,Arrival Date, Departure Date. \
Table Maintenance has fields Description, Date performed, Performed by."
_DEFAULT_TEMPLATE = """
Given an input question, create a syntactically correct {dialect} SQL query to run without comments, then provide answer to the question in english based on the result of SQL Query.
Always use schema USER1. You DO NOT need to check on the SQL Query for common mistake.
{table_info}
Question: {input}"""
PROMPT = PromptTemplate(
input_variables=["input", "table_info", "dialect"], template=_DEFAULT_TEMPLATE
)
#Next let's instatiate the bedrock and the handler treatment of input and output
class ContentHandler(LLMContentHandler):
content_type = "application/json"
accepts = "application/json"
def transform_input(self, prompt: str, model_kwargs: dict) -> bytes:
input_str = json.dumps({"text_inputs": prompt, **model_kwargs})
return input_str.encode('utf-8')
def transform_output(self, output: bytes) -> str:
response_json = json.loads(output.read().decode("utf-8"))
return response_json["generated_texts"][0]
content_handler = ContentHandler()
model_parameter = {"temperature": 0, "max_tokens_to_sample": 4000}
#Make sure your account has access to anthropic claude access. This can be enabled from Bedrock console. Access is auto approved.
llm = bedrock.Bedrock(model_id="anthropic.claude-v2:1", model_kwargs=model_parameter, region_name="us-west-2")
#Let's connect to the SAP HANA Database and then execute langchain SQL Database Chain to query from the Generative AI
db = SQLDatabase.from_uri("hana://USER:Password@<mydb>.hana.trial-us10.hanacloud.ondemand.com:443")
db_chain = SQLDatabaseChain.from_llm(llm=llm, db=db, prompt=PROMPT, verbose=True, use_query_checker=True, top_k=5 )
Execute the first query, this is a simple English to text SQL
db_chain.run("How many Hotels are there ?")
UNEXPECTED OUTPUT *****************
> Entering new SQLDatabaseChain chain...
How many Hotels are there ?
SQLQuery:I don't see any issues with the original SQL query. It looks good as written. Here is the query again:
```sql
SELECT COUNT(*) AS num_hotels
FROM hotel;
```
This counts the number of rows in the hotel table to get the number of unique hotels and returns the result in the num_hotels column alias. The query follows proper practices and does not contain any of the common mistakes listed.
---------------------------------------------------------------------------
ProgrammingError Traceback (most recent call last)
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/engine/base.py:1819, in Connection._execute_context(self, dialect, constructor, statement, parameters, execution_options, *args, **kw)
1818 if not evt_handled:
-> 1819 self.dialect.do_execute(
1820 cursor, statement, parameters, context
1821 )
1823 if self._has_events or self.engine._has_events:
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/engine/default.py:732, in DefaultDialect.do_execute(self, cursor, statement, parameters, context)
731 def do_execute(self, cursor, statement, parameters, context=None):
--> 732 cursor.execute(statement, parameters)
ProgrammingError: (257, 'sql syntax error: incorrect syntax near "I": line 1 col 1 (at pos 1)')
The above exception was the direct cause of the following exception:
ProgrammingError Traceback (most recent call last)
Cell In[43], line 2
1 #Execute the first query, this is a simple English to text SQL
----> 2 db_chain.run("How many Hotels are there ?")
File /opt/conda/lib/python3.10/site-packages/langchain/chains/base.py:507, in Chain.run(self, callbacks, tags, metadata, *args, **kwargs)
505 if len(args) != 1:
506 raise ValueError("`run` supports only one positional argument.")
--> 507 return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[
508 _output_key
509 ]
511 if kwargs and not args:
512 return self(kwargs, callbacks=callbacks, tags=tags, metadata=metadata)[
513 _output_key
514 ]
File /opt/conda/lib/python3.10/site-packages/langchain/chains/base.py:312, in Chain.__call__(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)
310 except BaseException as e:
311 run_manager.on_chain_error(e)
--> 312 raise e
313 run_manager.on_chain_end(outputs)
314 final_outputs: Dict[str, Any] = self.prep_outputs(
315 inputs, outputs, return_only_outputs
316 )
File /opt/conda/lib/python3.10/site-packages/langchain/chains/base.py:306, in Chain.__call__(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)
299 run_manager = callback_manager.on_chain_start(
300 dumpd(self),
301 inputs,
302 name=run_name,
303 )
304 try:
305 outputs = (
--> 306 self._call(inputs, run_manager=run_manager)
307 if new_arg_supported
308 else self._call(inputs)
309 )
310 except BaseException as e:
311 run_manager.on_chain_error(e)
File /opt/conda/lib/python3.10/site-packages/langchain_experimental/sql/base.py:198, in SQLDatabaseChain._call(self, inputs, run_manager)
194 except Exception as exc:
195 # Append intermediate steps to exception, to aid in logging and later
196 # improvement of few shot prompt seeds
197 exc.intermediate_steps = intermediate_steps # type: ignore
--> 198 raise exc
File /opt/conda/lib/python3.10/site-packages/langchain_experimental/sql/base.py:168, in SQLDatabaseChain._call(self, inputs, run_manager)
162 _run_manager.on_text(
163 checked_sql_command, color="green", verbose=self.verbose
164 )
165 intermediate_steps.append(
166 {"sql_cmd": checked_sql_command}
167 ) # input: sql exec
--> 168 result = self.database.run(checked_sql_command)
169 intermediate_steps.append(str(result)) # output: sql exec
170 sql_cmd = checked_sql_command
File /opt/conda/lib/python3.10/site-packages/langchain/utilities/sql_database.py:433, in SQLDatabase.run(self, command, fetch)
423 def run(
424 self,
425 command: str,
426 fetch: Union[Literal["all"], Literal["one"]] = "all",
427 ) -> str:
428 """Execute a SQL command and return a string representing the results.
429
430 If the statement returns rows, a string of the results is returned.
431 If the statement returns no rows, an empty string is returned.
432 """
--> 433 result = self._execute(command, fetch)
434 # Convert columns values to string to avoid issues with sqlalchemy
435 # truncating text
436 res = [
437 tuple(truncate_word(c, length=self._max_string_length) for c in r.values())
438 for r in result
439 ]
File /opt/conda/lib/python3.10/site-packages/langchain/utilities/sql_database.py:411, in SQLDatabase._execute(self, command, fetch)
409 else: # postgresql and other compatible dialects
410 connection.exec_driver_sql("SET search_path TO %s", (self._schema,))
--> 411 cursor = connection.execute(text(command))
412 if cursor.returns_rows:
413 if fetch == "all":
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/engine/base.py:1306, in Connection.execute(self, statement, *multiparams, **params)
1302 util.raise_(
1303 exc.ObjectNotExecutableError(statement), replace_context=err
1304 )
1305 else:
-> 1306 return meth(self, multiparams, params, _EMPTY_EXECUTION_OPTS)
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/sql/elements.py:332, in ClauseElement._execute_on_connection(self, connection, multiparams, params, execution_options, _force)
328 def _execute_on_connection(
329 self, connection, multiparams, params, execution_options, _force=False
330 ):
331 if _force or self.supports_execution:
--> 332 return connection._execute_clauseelement(
333 self, multiparams, params, execution_options
334 )
335 else:
336 raise exc.ObjectNotExecutableError(self)
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/engine/base.py:1498, in Connection._execute_clauseelement(self, elem, multiparams, params, execution_options)
1486 compiled_cache = execution_options.get(
1487 "compiled_cache", self.engine._compiled_cache
1488 )
1490 compiled_sql, extracted_params, cache_hit = elem._compile_w_cache(
1491 dialect=dialect,
1492 compiled_cache=compiled_cache,
(...)
1496 linting=self.dialect.compiler_linting | compiler.WARN_LINTING,
1497 )
-> 1498 ret = self._execute_context(
1499 dialect,
1500 dialect.execution_ctx_cls._init_compiled,
1501 compiled_sql,
1502 distilled_params,
1503 execution_options,
1504 compiled_sql,
1505 distilled_params,
1506 elem,
1507 extracted_params,
1508 cache_hit=cache_hit,
1509 )
1510 if has_events:
1511 self.dispatch.after_execute(
1512 self,
1513 elem,
(...)
1517 ret,
1518 )
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/engine/base.py:1862, in Connection._execute_context(self, dialect, constructor, statement, parameters, execution_options, *args, **kw)
1859 branched.close()
1861 except BaseException as e:
-> 1862 self._handle_dbapi_exception(
1863 e, statement, parameters, cursor, context
1864 )
1866 return result
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/engine/base.py:2043, in Connection._handle_dbapi_exception(self, e, statement, parameters, cursor, context)
2041 util.raise_(newraise, with_traceback=exc_info[2], from_=e)
2042 elif should_wrap:
-> 2043 util.raise_(
2044 sqlalchemy_exception, with_traceback=exc_info[2], from_=e
2045 )
2046 else:
2047 util.raise_(exc_info[1], with_traceback=exc_info[2])
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/util/compat.py:208, in raise_(***failed resolving arguments***)
205 exception.__cause__ = replace_context
207 try:
--> 208 raise exception
209 finally:
210 # credit to
211 # https://cosmicpercolator.com/2016/01/13/exception-leaks-in-python-2-and-3/
212 # as the __traceback__ object creates a cycle
213 del exception, replace_context, from_, with_traceback
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/engine/base.py:1819, in Connection._execute_context(self, dialect, constructor, statement, parameters, execution_options, *args, **kw)
1817 break
1818 if not evt_handled:
-> 1819 self.dialect.do_execute(
1820 cursor, statement, parameters, context
1821 )
1823 if self._has_events or self.engine._has_events:
1824 self.dispatch.after_cursor_execute(
1825 self,
1826 cursor,
(...)
1830 context.executemany,
1831 )
File /opt/conda/lib/python3.10/site-packages/sqlalchemy/engine/default.py:732, in DefaultDialect.do_execute(self, cursor, statement, parameters, context)
731 def do_execute(self, cursor, statement, parameters, context=None):
--> 732 cursor.execute(statement, parameters)
ProgrammingError: (hdbcli.dbapi.ProgrammingError) (257, 'sql syntax error: incorrect syntax near "I": line 1 col 1 (at pos 1)')
[SQL: I don't see any issues with the original SQL query. It looks good as written. Here is the query again:
```sql
SELECT COUNT(*) AS num_hotels
FROM hotel;
```
This counts the number of rows in the hotel table to get the number of unique hotels and returns the result in the num_hotels column alias. The query follows proper practices and does not contain any of the common mistakes listed.]
(Background on this error at: https://sqlalche.me/e/14/f405)
### Expected behavior
The select statement is produced correct, it just that the LLM perform checks on the SQL Statement and comment it before passing it to SQLAlchemy for execution. When i used Claude v2, 75% SQLDatabaseChain is successful, however 25% always gets back to the behaviour providing comments about whether the SQL Query has common mistakes.
Now with Claude v2.1, ALL of the questions are checked, and failing when passing to SQLAlchemy. It seems there is a problem with the SQLDatabaseChain, either the prompt or something else. Please help to fix this.
[Lab2.ipynb.zip](https://github.com/langchain-ai/langchain/files/13532157/Lab2.ipynb.zip)
| Claude v2.1 SQLDatabaseChain produces comments mixed with SQL Statements | https://api.github.com/repos/langchain-ai/langchain/issues/14150/comments | 11 | 2023-12-01T21:48:33Z | 2024-05-07T16:07:28Z | https://github.com/langchain-ai/langchain/issues/14150 | 2,021,628,680 | 14,150 |
[
"langchain-ai",
"langchain"
] | ### Feature request
Adding [IBM Watson Discovery Service](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-getting-started) as an additional retriever might be a useful extension to enable RAG-use cases or supporting RetrievalChains.
IBM Watson Discovery Service can find relevant documents based on natural language queries and understand document structures such as tables.
### Motivation
Currently, there is no support for IBM Watson Discovery Service (WDS) as a retriever which requires external scripts to use WDS as a source for a RetrievalChain e.g.
### Your contribution
I'm able to contribute a IbM Watson Discovery Service retriever. | Add Retriever for Knowledge Base IBM Watson Discovery Service | https://api.github.com/repos/langchain-ai/langchain/issues/14145/comments | 1 | 2023-12-01T21:01:46Z | 2024-03-16T16:09:11Z | https://github.com/langchain-ai/langchain/issues/14145 | 2,021,577,501 | 14,145 |
[
"langchain-ai",
"langchain"
] | ### System Info
It seems the typing of my index is lost when I save and load it. This is me creating the FAISS vector store with the MAX_INNER_PRODUCT flag.
```python
# Saving
save_db = FAISS.from_texts(texts, embedding_function, metadatas=metadatas, distance_strategy="MAX_INNER_PRODUCT", normalize_L2=True)
save_db.save_local(db_directory)
print(save_db.index, save_db.distance_strategy)
# <faiss.swigfaiss_avx2.IndexFlatIP; proxy of <Swig Object of type 'faiss::IndexFlatIP *' at 0x7f4e0402e4b0> > MAX_INNER_PRODUCT
# Loading
load_db = FAISS.load_local(db_directory, embedding_function, distance_strategy="MAX_INNER_PRODUCT")
print(load_db .index, load_db .distance_strategy)
# <faiss.swigfaiss_avx2.IndexFlat; proxy of <Swig Object of type 'faiss::IndexFlat *' at 0x7f4dd0accdb0> > MAX_INNER_PRODUCT
```
I have looked through FAISS API documentation and can't tell if this is an abstracted class.
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [X] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [X] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
1. Create a FAISS vector store passing distance_strategy = "MAX_INNER_PRODUCT". This should create an index with FAISS.IndexFlatIP.
2. Save the FAISS vector store.
3. Load the FAISS vector store with the distance_strategy = "MAX_INNER_PRODUCT"
4. Compare the saved.index and loaded.index objects. One is IndexFlatIP and the other is an IndexFlat class.
### Expected behavior
When loading the index from load_local, it should still be an IndexFlatIP. | FAISS.load_local does not keep the typing of the saved Index | https://api.github.com/repos/langchain-ai/langchain/issues/14141/comments | 3 | 2023-12-01T20:31:24Z | 2024-01-11T22:59:40Z | https://github.com/langchain-ai/langchain/issues/14141 | 2,021,543,545 | 14,141 |
[
"langchain-ai",
"langchain"
] | ### Feature request
Amazon DocumentDB has launched its vector search feature recently. Let us add Amazon DocumentDB as vector store in langchain.
### Motivation
This will help large customer base of Amazon DocumentDB to adopt langchain and seamlessly build AI/ML apps
### Your contribution
Amazon DocumentDB team can help with testing and technical help.
https://aws.amazon.com/about-aws/whats-new/2023/11/vector-search-amazon-documentdb/
https://docs.aws.amazon.com/documentdb/latest/developerguide/vector-search.html | Amazon DocumentDB Vector Store | https://api.github.com/repos/langchain-ai/langchain/issues/14140/comments | 8 | 2023-12-01T20:20:11Z | 2024-06-01T00:07:37Z | https://github.com/langchain-ai/langchain/issues/14140 | 2,021,530,789 | 14,140 |
[
"langchain-ai",
"langchain"
] | ### System Info
Python 3.11, `langchain==0.0.340`
### Who can help?
@hwchase17
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [X] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [X] Callbacks/Tracing
- [ ] Async
### Reproduction
Before LCEL, there is lots of logging:
```python
from langchain.chains import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.schema.callbacks.stdout import StdOutCallbackHandler
prompt = PromptTemplate.from_template(
"What is a good name for a company that makes {product}?"
)
chain = LLMChain(prompt=prompt, llm=ChatOpenAI(), callbacks=[StdOutCallbackHandler()])
chain.run(product="colorful socks")
```
```none
> Entering new LLMChain chain...
Prompt after formatting:
What is a good name for a company that makes colorful socks?
> Finished chain.
```
After LCEL, there is less logging:
```python
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.schema.callbacks.stdout import StdOutCallbackHandler
prompt = PromptTemplate.from_template(
"What is a good name for a company that makes {product}?"
)
runnable = prompt | ChatOpenAI()
runnable.invoke(
input={"product": "colorful socks"}, config={"callbacks": [StdOutCallbackHandler()]}
)
```
Leads to this output:
```none
> Entering new RunnableSequence chain...
> Entering new PromptTemplate chain...
> Finished chain.
> Finished chain.
```
### Expected behavior
To migrate from `LLMChain` to LCEL, I want the logging statements/verbosity to remain in tact | Bug: LCEL prompt template not logging | https://api.github.com/repos/langchain-ai/langchain/issues/14135/comments | 2 | 2023-12-01T18:30:40Z | 2024-03-17T16:07:47Z | https://github.com/langchain-ai/langchain/issues/14135 | 2,021,388,401 | 14,135 |
[
"langchain-ai",
"langchain"
] | ### Issue with current documentation:
https://python.langchain.com/docs/modules/callbacks/
This doc doesn't mention how to use callbacks with LCEL. It would be good to add that, to help with the migration from `LLMChain` to `LCEL`.
### Idea or request for content:
https://python.langchain.com/docs/modules/chains/ does a nice job of showing code pre-LCEL and code post-LCEL.
https://github.com/langchain-ai/langchain/discussions/12670 shows how to pass the callback to `invoke`, but ideally the example shows how to `bind` the callback once (as opposed to passing to each `invoke`). | DOC: documenting callbacks with LCEL | https://api.github.com/repos/langchain-ai/langchain/issues/14134/comments | 8 | 2023-12-01T18:21:00Z | 2023-12-04T18:34:07Z | https://github.com/langchain-ai/langchain/issues/14134 | 2,021,375,012 | 14,134 |
[
"langchain-ai",
"langchain"
] | ### System Info
langchain 0.0.335
macOS 14.1.1 / Windows 10.0.19045
Python 3.11.6 / 3.10.9
### Who can help?
@naveentatikonda
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [X] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Install dependencies
```shell
pip install langchain opensearch-py boto3
```
Import packages
```python
import boto3
from langchain.embeddings import FakeEmbeddings
from langchain.vectorstores.opensearch_vector_search import OpenSearchVectorSearch
from opensearchpy import RequestsAWSV4SignerAuth, RequestsHttpConnection
```
Create AOSS auth
```python
boto_session = boto3.Session()
aoss_auth = RequestsAWSV4SignerAuth(credentials=boto_session.get_credentials(), region=boto_session.region_name, service="aoss")
```
Create AOSS vector search class
```python
embeddings = FakeEmbeddings(size=42)
database = OpenSearchVectorSearch(
opensearch_url="https://some_aoss_endpoint:443",
http_auth=aoss_auth,
connection_class=RequestsHttpConnection,
index_name="test",
embedding_function=embeddings,
```
Check if AOSS vector search identifies itself as AOSS
```python
database.is_aoss
```
Returns **False**
### Expected behavior
AOSS should correctly identify itself as AOSS given the configuration above, which means that `database.is_aoss` should return **True** in this case.
The issue is related to how the internal `_is_aoss_enabled` method works:
```python
def _is_aoss_enabled(http_auth: Any) -> bool:
"""Check if the service is http_auth is set as `aoss`."""
if (
http_auth is not None
and hasattr(http_auth, "service")
and http_auth.service == "aoss"
):
return True
return False
```
The `RequestsAWSV4SignerAuth` does not expose the _service_ property directly, but via the _signer_ attribute. In order to respect that, `is_aoss_enabled` should be adapted as following:
```python
def _is_aoss_enabled(http_auth: Any) -> bool:
"""Check if the service set via http_auth equals `aoss`."""
if http_auth is not None:
if hasattr(http_auth, "service") and http_auth.service == "aoss":
return True
elif hasattr(http_auth, "signer") and http_auth.signer.service == "aoss":
return True
else:
return False
return False
```
| OpenSearchVectorSearch fails to detect AOSS is enabled when using RequestAWS4SignerAuth from opensearch-py | https://api.github.com/repos/langchain-ai/langchain/issues/14129/comments | 3 | 2023-12-01T15:53:57Z | 2024-01-09T10:12:53Z | https://github.com/langchain-ai/langchain/issues/14129 | 2,021,147,121 | 14,129 |
[
"langchain-ai",
"langchain"
] | ### System Info
Using latest docker versions for langchain templates
### Who can help?
@hwchase17
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
First, following the quickstart for Templates until it gets to LangSmith deployment:
1. `pip install -U langchain-cli`
2. `langchain app new my-app`
3. `cd my-app`
4. `langchain app add pirate-speak`
Then, since I don't have access to LangServe, follow the template README for docker deployment:
5. `docker build . -t my-langserve-app`
6. `docker run -e OPENAI_API_KEY=$OPENAI_API_KEY -p 8080:8080 my-langserve-app`
Results in error:
```
Traceback (most recent call last):
File "/usr/local/bin/uvicorn", line 8, in <module>
sys.exit(main())
^^^^^^
File "/usr/local/lib/python3.11/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/click/core.py", line 1078, in main
rv = self.invoke(ctx)
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/click/core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/uvicorn/main.py", line 416, in main
run(
File "/usr/local/lib/python3.11/site-packages/uvicorn/main.py", line 587, in run
server.run()
File "/usr/local/lib/python3.11/site-packages/uvicorn/server.py", line 61, in run
return asyncio.run(self.serve(sockets=sockets))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/uvicorn/server.py", line 68, in serve
config.load()
File "/usr/local/lib/python3.11/site-packages/uvicorn/config.py", line 467, in load
self.loaded_app = import_from_string(self.app)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/uvicorn/importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/code/app/server.py", line 14, in <module>
add_routes(app, NotImplemented)
File "/usr/local/lib/python3.11/site-packages/langserve/server.py", line 627, in add_routes
input_type_ = _resolve_model(runnable.get_input_schema(), "Input", model_namespace)
^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NotImplementedType' object has no attribute 'get_input_schema'
```
I also tried the `research-assistant` template and got a similar `get_input_schema` error.
Am I missing a setup step?
### Expected behavior
Deploying the solution locally | AttributeError: 'NotImplementedType' object has no attribute 'get_input_schema' | https://api.github.com/repos/langchain-ai/langchain/issues/14128/comments | 7 | 2023-12-01T15:26:49Z | 2024-05-10T16:08:40Z | https://github.com/langchain-ai/langchain/issues/14128 | 2,021,099,502 | 14,128 |
[
"langchain-ai",
"langchain"
] | ### System Info
* Windows 11 Home (build 22621.2715)
* Python 3.12.0
* Clean virtual environment using Poetry with following dependencies:
```
python = "3.12.0"
langchain = "0.0.344"
spacy = "3.7.2"
spacy-llm = "0.6.4"
```
### Who can help?
@h3l As the creator of the pull request where VolcEngine was introduced
@baskaryan As tag handler of that pull request
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Anything that triggers spaCy's registry to make an inventory, for example:
```python
import spacy
spacy.blank("en")
```
With the last part of the Traceback being:
```
File "PROJECT_FOLDER\.venv\Lib\site-packages\langchain\llms\__init__.py", line 699, in __getattr__
k: v() for k, v in get_type_to_cls_dict().items()
^^^
File "PROJECT_FOLDER\.venv\Lib\site-packages\langchain_core\load\serializable.py", line 97, in __init__
super().__init__(**kwargs)
File "PROJECT_FOLDER\.venv\Lib\site-packages\pydantic\v1\main.py", line 341, in __init__
raise validation_error
pydantic.v1.error_wrappers.ValidationError: 1 validation error for VolcEngineMaasLLM
__root__
Did not find volc_engine_maas_ak, please add an environment variable `VOLC_ACCESSKEY` which contains it, or pass `volc_engine_maas_ak` as a named parameter. (type=value_error)
```
#### What I think causes this
I am quite certain that this is caused by [`langchain.llms.__init__.py:869 (for commit b161f30)`](https://github.com/langchain-ai/langchain/blob/b161f302ff56a14d8d0331cbec4a3efa23d06e1a/libs/langchain/langchain/llms/__init__.py#L869C51-L869C51):
```python
def get_type_to_cls_dict() -> Dict[str, Callable[[], Type[BaseLLM]]]:
return {
"ai21": _import_ai21,
"aleph_alpha": _import_aleph_alpha,
"amazon_api_gateway": _import_amazon_api_gateway,
...
"qianfan_endpoint": _import_baidu_qianfan_endpoint,
"yandex_gpt": _import_yandex_gpt,
# Line below is the only that actually calls the import function, returning a class instead of an import function
"VolcEngineMaasLLM": _import_volcengine_maas(),
}
```
The Volc Engine Maas LLM is the only in this dict to actually call the import function, while all other entries only the function itself, and do not call it.
### Expected behavior
Class to type dict only returns import functions, not actual classes:
```python
def get_type_to_cls_dict() -> Dict[str, Callable[[], Type[BaseLLM]]]:
return {
"ai21": _import_ai21,
"aleph_alpha": _import_aleph_alpha,
"amazon_api_gateway": _import_amazon_api_gateway,
...
"qianfan_endpoint": _import_baidu_qianfan_endpoint,
"yandex_gpt": _import_yandex_gpt,
# What I think would be correct (now without function call)
"VolcEngineMaasLLM": _import_volcengine_maas,
}
```
Unfortunately I don't have time to put in a PR myself, but I hope this helps finding the solution!
| Volc Engine MaaS has wrong entry in LLM type to class dict (causing SpaCy to not work with LangChain anymore) | https://api.github.com/repos/langchain-ai/langchain/issues/14127/comments | 4 | 2023-12-01T13:58:13Z | 2023-12-04T08:58:10Z | https://github.com/langchain-ai/langchain/issues/14127 | 2,020,934,355 | 14,127 |
[
"langchain-ai",
"langchain"
] | ### Feature request
Currently, the ConversationSummaryBufferMemory only supports the GPT2TokenizerFast and there is no option to pass a custom tokenizer. Different models have different corresponding tokenizers, so it makes sense to allow the option to specify a custom tokenizer.
The tokenizer fetching is implemented in langchain/schema/language_model.py:
@lru_cache(maxsize=None) # Cache the tokenizer
def get_tokenizer() -> Any:
try:
from transformers import GPT2TokenizerFast
except ImportError:
raise ImportError(
"Could not import transformers python package. "
"This is needed in order to calculate get_token_ids. "
"Please install it with `pip install transformers`."
)
# create a GPT-2 tokenizer instance
return GPT2TokenizerFast.from_pretrained("gpt2")
### Motivation
Using the exact tokenizer which the model uses will help in being more accurate in the context summarization cutoff.
### Your contribution
I could suggest a solution. | Specify a custom tokenizer for the ConversationSummaryBufferMemory | https://api.github.com/repos/langchain-ai/langchain/issues/14124/comments | 1 | 2023-12-01T10:43:31Z | 2024-03-16T16:09:01Z | https://github.com/langchain-ai/langchain/issues/14124 | 2,020,608,208 | 14,124 |
[
"langchain-ai",
"langchain"
] |
qa = RetrievalQA.from_chain_type(llm=llm, retriever=docsearch.as_retriever(
search_kwargs={"k": 1}), verbose=True)
How can we add the prompts like systemPromptTemplate and humanPromptTemplate in the above code.
### Suggestion:
_No response_ | How can we add Prompt in RetrievalQA | https://api.github.com/repos/langchain-ai/langchain/issues/14123/comments | 1 | 2023-12-01T10:41:14Z | 2024-03-17T16:07:41Z | https://github.com/langchain-ai/langchain/issues/14123 | 2,020,604,255 | 14,123 |
[
"langchain-ai",
"langchain"
] | ### Feature request
Amazon Bedrock now provides some useful metrics when it has finished:
`"completion":"Response from Bedrock...","stop_reason":"stop_sequence","stop":"\n\nHuman:","amazon-bedrock-invocationMetrics":{"inputTokenCount":16,"outputTokenCount":337,"invocationLatency":4151,"firstByteLatency":136}}`
It would be good to expose these via LangChain, similar to how OpenAI API provides them.
### Motivation
To make it easier to calculate the cost of Amazon Bedrock queries.
### Your contribution
I'm happy to test any solution. I'd look to existing developers to guide us how best to expose them. | Expose Amazon Bedrock amazon-bedrock-invocationMetrics in response | https://api.github.com/repos/langchain-ai/langchain/issues/14120/comments | 4 | 2023-12-01T09:41:44Z | 2024-06-18T16:09:25Z | https://github.com/langchain-ai/langchain/issues/14120 | 2,020,491,917 | 14,120 |
[
"langchain-ai",
"langchain"
] | I am currently operating a chroma docker on port 8001 and using it for my node js application with the URL CHROMA_URI=http://localhost:8001/, which allows me to read the vectors.
However, when I try to use the same chroma_URI with langchain chroma, I encounter an error message. The error message reads: **{"lc":1,"type":"not_implemented","id":["langchain","vectorstores","chroma","Chroma"]}**.



The above screenshots are my codes.
does anyone face this issue? | Trouble Connecting Langchain Chroma to Existing ChromaDB on Port 8001 | https://api.github.com/repos/langchain-ai/langchain/issues/14119/comments | 1 | 2023-12-01T09:09:40Z | 2024-03-17T16:07:36Z | https://github.com/langchain-ai/langchain/issues/14119 | 2,020,436,621 | 14,119 |
[
"langchain-ai",
"langchain"
] | ### System Info
- Python 3.9.13
- langchain==0.0.344
- langchain-core==0.0.8
### Who can help?
@agola11
@hwchase17
@agola11
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [X] Tools / Toolkits
- [ ] Chains
- [X] Callbacks/Tracing
- [ ] Async
### Reproduction
1. Define a Custom Tool which useses some sort of OpenAI Model. For example GPT 3.5
2. Define a Tool agent which uses this Tool
3. Call the Agent inside a with Block with `get_openai_callback()`
4. The agent should now call the tool which uses an OpenAI Model
5. Calculate the Total Cost. By using the `get_openai_callback` variable. The cost does only include tokens used by the tool agent
### Expected behavior
It should Include all Cost. Including the one from the tool | Cost doesnt work when used inside Tool | https://api.github.com/repos/langchain-ai/langchain/issues/14117/comments | 2 | 2023-12-01T08:37:47Z | 2023-12-01T13:40:19Z | https://github.com/langchain-ai/langchain/issues/14117 | 2,020,382,738 | 14,117 |
[
"langchain-ai",
"langchain"
] | ### System Info
I was just trying to run the LLMs tutorial.
```
from langchain.llms import VertexAI
llm = VertexAI()
print(llm("What are some of the pros and cons of Python as a programming language?"))
```
I got this error.
```
File "C:\Users\******\anaconda3\envs\vertex-ai\Lib\site-packages\langchain_core\load\serializable.py", line 97, in __init__
super().__init__(**kwargs)
File "C:\Users\******\anaconda3\envs\vertex-ai\Lib\site-packages\pydantic\v1\main.py", line 339, in __init__
values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\******\anaconda3\envs\vertex-ai\Lib\site-packages\pydantic\v1\main.py", line 1102, in validate_model
values = validator(cls_, values)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\******\anaconda3\envs\vertex-ai\Lib\site-packages\langchain\llms\vertexai.py", line 249, in validate_environment
cls._try_init_vertexai(values)
File "C:\Users\******\anaconda3\envs\vertex-ai\Lib\site-packages\langchain\llms\vertexai.py", line 216, in _try_init_vertexai
init_vertexai(**params)
File "C:\Users\******\anaconda3\envs\vertex-ai\Lib\site-packages\langchain\utilities\vertexai.py", line 42, in init_vertexai
import vertexa
```
I try to install an older version of pydantic like pip install pydantic == 1.10 or 1.10.10, but still error about "validation_error" .
### Who can help?
_No response_
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Anaconda Navigator
1.Python version == 3.12.0
2.Langchain version == 0.0.344
3.Google-cloud-aiplatform version == 1.36.4
4.Pydantic version == 2.5.2
### Expected behavior
Running code without any issues. | Google Cloud Vertex AI Throws AttributeError: partially initialized module 'vertexai' has no attribute 'init' | https://api.github.com/repos/langchain-ai/langchain/issues/14114/comments | 2 | 2023-12-01T07:13:02Z | 2024-03-17T16:07:31Z | https://github.com/langchain-ai/langchain/issues/14114 | 2,020,257,158 | 14,114 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I am in need to get all the pages and page id of a particular Confluence Spaces, How can I get all the page id?
### Suggestion:
_No response_ | Issue:How to get all the Pages of Confluence Spaces. | https://api.github.com/repos/langchain-ai/langchain/issues/14113/comments | 9 | 2023-12-01T07:07:47Z | 2024-04-18T16:28:00Z | https://github.com/langchain-ai/langchain/issues/14113 | 2,020,249,681 | 14,113 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I want to connect my ConversationChain to Metaphor. Please help me on how to do it! Thanks
### Suggestion:
_No response_ | How to connect an LLM Chain to Metaphor | https://api.github.com/repos/langchain-ai/langchain/issues/14112/comments | 1 | 2023-12-01T06:47:10Z | 2024-03-16T16:08:41Z | https://github.com/langchain-ai/langchain/issues/14112 | 2,020,223,271 | 14,112 |
[
"langchain-ai",
"langchain"
] | ### Issue with current documentation:
The link to subscribe to the "newsletter" at the bottom of Community page (`/docs/docs/community.md`) is no longer available.

As the image above indicates, the "form has moved to a new address", and the new address (https://form.typeform.com/to/KjZB1auB?typeform-source=6w1pwbss0py.typeform.com) gives "This typeform is now closed", as the image shown below:

### Idea or request for content:
If the newsletter is still operating, replace the current link with a new one where people can subscribe to it.
If the newsletter is no longer running, replace the text with something else (eg. the link to langchain blogs). | DOC: Link to subscribe to the "newsletter" on Community page is no longer valid | https://api.github.com/repos/langchain-ai/langchain/issues/14108/comments | 1 | 2023-12-01T04:52:55Z | 2024-02-25T15:14:52Z | https://github.com/langchain-ai/langchain/issues/14108 | 2,020,059,736 | 14,108 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
i am using load_qa_chain()
chain=load_qa_chain(OpenAI(temperature=0.25,model_name="gpt-3.5-turbo-1106"), chain_type="stuff", prompt=PROMPT)
i got the following error
"""
APIRemovedInV1:
You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at
https://github.com/openai/openai-python for the API.
You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface.
Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`
A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742
"""
and the line that raised the error is
anaconda3/envs/Doc2/lib/site-packages/langchain/llms/openai.py:115
### Suggestion:
_No response_ | Issue: openai.ChatCompletion is no longer supported in openai>=1.0.0 | https://api.github.com/repos/langchain-ai/langchain/issues/14107/comments | 4 | 2023-12-01T03:57:52Z | 2023-12-11T05:58:02Z | https://github.com/langchain-ai/langchain/issues/14107 | 2,020,008,509 | 14,107 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
langchain_core.runnables.base.RunnableMap
Im trying use this and i want to know is there any way that i can give different input for each chain
### Suggestion:
_No response_ | Runnablemap different input for each chain | https://api.github.com/repos/langchain-ai/langchain/issues/14098/comments | 6 | 2023-12-01T01:09:07Z | 2024-04-12T13:52:30Z | https://github.com/langchain-ai/langchain/issues/14098 | 2,019,840,343 | 14,098 |
[
"langchain-ai",
"langchain"
] | ### System Info
langchain 0.0.343
langchain-core 0.0.7
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [X] Document Loaders
- [X] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
```
retriever = AzureCognitiveSearchRetriever(content_key="content", top_k=5)
llm = AzureChatOpenAI(
openai_api_version="2023-05-15",
azure_deployment="larger-chat-35",
)
template = """
I want you to act as a research assistant. you will answer questions about the context.
Context: {context}
Question: {question}?
"""
prompt = PromptTemplate(
input_variables=["question", "context"],
template=template,
)
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressors=compressor,
base_retriever=retriever)
```
### Expected behavior
I'd expect the compression_retriever to be instantiated. But instead I receive the following error:
```
pydantic.v1.error_wrappers.ValidationError: 1 validation error for ContextualCompressionRetriever
base_compressor
field required (type=value_error.missing)
``` | Pydantic error field required (type=value_error.missing) in LLMChainExtractor or ContextualCompressionRetriever | https://api.github.com/repos/langchain-ai/langchain/issues/14088/comments | 3 | 2023-11-30T20:53:24Z | 2023-11-30T22:24:23Z | https://github.com/langchain-ai/langchain/issues/14088 | 2,019,492,749 | 14,088 |
[
"langchain-ai",
"langchain"
] | ### Feature request
The `invoke()` method for RunnableWithFallbacks is only raising the first_error caught in the runnables. I would like to have an option to choose whether to raise the first error or last error.
Can this be a parameter for `invoke()`?
### Motivation
When using fallbacks, the first error could be related to the first Runnable. However, the error I'm actually interested to handle is the last error from the end of my fallbacks.
The last error is the most downstream error from my chains, and it's the error I want to handle in my app business logic.
### Your contribution
N/A | RunnableWithFallbacks should have a parameter to choose whether to raise first error or last error | https://api.github.com/repos/langchain-ai/langchain/issues/14085/comments | 1 | 2023-11-30T20:12:47Z | 2024-03-16T16:08:31Z | https://github.com/langchain-ai/langchain/issues/14085 | 2,019,431,096 | 14,085 |
[
"langchain-ai",
"langchain"
] | ### System Info
langchain== 0.0.340
pydantic==2.4.2
pydantic_core==2.10.1
### Who can help?
@hwchase17 @eyur
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [X] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
```python
from langchain.schema import BaseOutputParser
from pydantic import PrivateAttr
class MyParser(BaseOutputParser[list[int]]):
_list: list[int] = PrivateAttr(default_factory=list)
def parse(self, text: str) -> list[int]:
return self._list
parser = MyParser()
assert parser.parse("test") == []
```
### Expected behavior
I expect `PrivateAttr` to still work within `BaseOutputParser`. | `BaseOutputParser` breaks pydantic `PrivateAttr` | https://api.github.com/repos/langchain-ai/langchain/issues/14084/comments | 4 | 2023-11-30T19:56:09Z | 2023-12-02T18:33:06Z | https://github.com/langchain-ai/langchain/issues/14084 | 2,019,400,383 | 14,084 |
[
"langchain-ai",
"langchain"
] | ### System Info
in AWS langchain Bedrock, how do I set temperature?
### Who can help?
_No response_
### Information
- [X] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Tried putting it as a parameter of Bedrock and gave error that such parameter does not exist. Then put is as paramenters of kwargs and it had no effect
### Expected behavior
Expected this to be a direct parameter of Bedrock, but it seems that it is not | in AWS langchain Bedrock, how do I set temperature? | https://api.github.com/repos/langchain-ai/langchain/issues/14083/comments | 19 | 2023-11-30T19:51:15Z | 2024-05-23T10:16:06Z | https://github.com/langchain-ai/langchain/issues/14083 | 2,019,393,730 | 14,083 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I am using ConversationalRetrievalChain. I have created two vector stores and I want the query from ConversationalRetrievalChain to be compared against both vector stores and results from both vector stores to be used to create the final answer.
So I have decided to create two retrievers
retriever1 = vectorstore1.as_retriever()
retriever2 = vectorstore2.as_retriever()
How can I now override the Retriever class so that when the query is compared against my custom_retriever, it is compared against documents from both retrievers, and documents from both retrievers are used to create the prompt.
Note: i don't want to merge the vectorstores because that messes up the similarity search.
### Suggestion:
_No response_ | Combine langchain retrievers | https://api.github.com/repos/langchain-ai/langchain/issues/14082/comments | 9 | 2023-11-30T19:39:09Z | 2024-03-18T16:07:04Z | https://github.com/langchain-ai/langchain/issues/14082 | 2,019,376,935 | 14,082 |
[
"langchain-ai",
"langchain"
] | ### System Info
Mac OS
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [X] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
When I am using Agent, random seed doesn't work.
model_kwargs = {
"seed": 2139
}
llm_agent = ChatOpenAI(temperature=0,
openai_api_key='sk-',
model_name='gpt-4-1106-preview',
model_kwargs=model_kwargs)
llm_cypher = ChatOpenAI(temperature=0,
openai_api_key='sk-',
model_name='gpt-4-1106-preview',
model_kwargs=model_kwargs)
llm_graph = ChatOpenAI(temperature=0,
openai_api_key='sk-',
model_name='gpt-4-1106-preview',
model_kwargs=model_kwargs)
tools = [
Tool(
name="GraphDB Search tool",
func=chain,
description=tool_description
)
]
chain = CustomGraphCypherQAChain.from_llm(
top_k=100,
llm=llm_graph,
return_direct=True, # this return the observation from cypher query directly without rethinking over observation
return_intermediate_steps=True, # this is only returned when it's call by chain() not by chain.run()
cypher_llm=llm_cypher,
graph=graph,
verbose=True,
cypher_prompt=CYPHER_GENERATION_PROMPT
)
def init_agent():
agent = initialize_agent(
tools,
llm_agent,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
handle_errors=True,
handle_parsing_errors=True,
return_intermediate_steps=True,
max_iterations=10,
)
return agent
this agent don't reproduce for same input
### Expected behavior
I expect Agent keep resulting in same answer for the same input prompt | Random Seed when using LLM Agent | https://api.github.com/repos/langchain-ai/langchain/issues/14080/comments | 1 | 2023-11-30T18:56:50Z | 2024-03-17T16:07:12Z | https://github.com/langchain-ai/langchain/issues/14080 | 2,019,317,039 | 14,080 |
[
"langchain-ai",
"langchain"
] | ### Feature request
Support for Perplexity's new [PPLX models](https://blog.perplexity.ai/blog/introducing-pplx-online-llms).
### Motivation
Boosting online LLM support, particularly for Perplexity-based models, would be highly impactful and useful.
### Your contribution
Currently working on a PR! | Support for Perplexity's PPLX models: `pplx-7b-online` and `pplx-70b-online` | https://api.github.com/repos/langchain-ai/langchain/issues/14079/comments | 2 | 2023-11-30T18:41:11Z | 2024-05-01T16:05:38Z | https://github.com/langchain-ai/langchain/issues/14079 | 2,019,294,151 | 14,079 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Hello everyone,
We are having request timeout on our calls and they are being getting retries after failing but we want to see how many times doing these retries and all their logs.
When the requests are timing out, nothing has been sending callbackhandler and we want to see how many retries had been done under the ChatOpenAI LLM model.
### Suggestion:
_No response_ | MyCallbackHandler can't show logs explicitly | https://api.github.com/repos/langchain-ai/langchain/issues/14077/comments | 1 | 2023-11-30T18:20:20Z | 2024-03-16T16:08:11Z | https://github.com/langchain-ai/langchain/issues/14077 | 2,019,257,671 | 14,077 |
[
"langchain-ai",
"langchain"
] | ### System Info
Regardless of the text length, the QAGenerationChain consistently generates only one question.
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
```
from langchain.chains import QAGenerationChain
from langchain.llms import OpenAI
# Initialize the language model
lm = OpenAI()
# Create the QA Generator Chain
qa_chain = QAGenerationChain.from_llm(llm=lm)
qa_chain.k = 4
# Example usage
context = """
Introduction
LangChain is a framework for developing applications powered by language models. It enables applications that:
Are context-aware: connect a language model to sources of context (prompt instructions, few shot examples, content to ground its response in, etc.)
Reason: rely on a language model to reason (about how to answer based on provided context, what actions to take, etc.)
This framework consists of several parts.
LangChain Libraries: The Python and JavaScript libraries. Contains interfaces and integrations for a myriad of components, a basic run time for combining these components into chains and agents, and off-the-shelf implementations of chains and agents.
LangChain Templates: A collection of easily deployable reference architectures for a wide variety of tasks.
LangServe: A library for deploying LangChain chains as a REST API.
LangSmith: A developer platform that lets you debug, test, evaluate, and monitor chains built on any LLM framework and seamlessly integrates with LangChain.
LangChain Diagram
Together, these products simplify the entire application lifecycle:
Develop: Write your applications in LangChain/LangChain.js. Hit the ground running using Templates for reference.
Productionize: Use LangSmith to inspect, test and monitor your chains, so that you can constantly improve and deploy with confidence.
Deploy: Turn any chain into an API with LangServe.
LangChain Libraries
The main value props of the LangChain packages are:
Components: composable tools and integrations for working with language models. Components are modular and easy-to-use, whether you are using the rest of the LangChain framework or not
Off-the-shelf chains: built-in assemblages of components for accomplishing higher-level tasks
Off-the-shelf chains make it easy to get started. Components make it easy to customize existing chains and build new ones.
Get started
Here’s how to install LangChain, set up your environment, and start building.
We recommend following our Quickstart guide to familiarize yourself with the framework by building your first LangChain application.
Read up on our Security best practices to make sure you're developing safely with LangChain.
NOTE
These docs focus on the Python LangChain library. Head here for docs on the JavaScript LangChain library.
LangChain Expression Language (LCEL)
LCEL is a declarative way to compose chains. LCEL was designed from day 1 to support putting prototypes in production, with no code changes, from the simplest “prompt + LLM” chain to the most complex chains.
Overview: LCEL and its benefits
Interface: The standard interface for LCEL objects
How-to: Key features of LCEL
Cookbook: Example code for accomplishing common tasks
Modules
LangChain provides standard, extendable interfaces and integrations for the following modules:
Model I/O
Interface with language models
Retrieval
Interface with application-specific data
Agents
Let models choose which tools to use given high-level directives
Examples, ecosystem, and resources
Use cases
Walkthroughs and techniques for common end-to-end use cases, like:
Document question answering
Chatbots
Analyzing structured data
and much more...
Integrations
LangChain is part of a rich ecosystem of tools that integrate with our framework and build on top of it. Check out our growing list of integrations.
Guides
Best practices for developing with LangChain.
API reference
Head to the reference section for full documentation of all classes and methods in the LangChain and LangChain Experimental Python packages.
Developer's guide
Check out the developer's guide for guidelines on contributing and help getting your dev environment set up.
Community
Head to the Community navigator to find places to ask questions, share feedback, meet other developers, and dream about the future of LLM’s.
"""
questions = qa_chain.run(context)
print(questions)
```
output
```
[{'question': 'What are the main value props of the LangChain packages?', 'answer': 'The main value props of the LangChain packages are composable tools and integrations for working with language models, off-the-shelf chains for accomplishing higher-level tasks, and the ability to easily deploy chains as a REST API.'}]
```
### Expected behavior
I expect to specify the number of responses by setting the 'k' value. | Regardless of the text length, the QAGenerationChain consistently generates only one question. | https://api.github.com/repos/langchain-ai/langchain/issues/14074/comments | 1 | 2023-11-30T17:21:42Z | 2024-03-16T16:08:06Z | https://github.com/langchain-ai/langchain/issues/14074 | 2,019,146,581 | 14,074 |
[
"langchain-ai",
"langchain"
] | ### System Info
LangChain Version: 0.0.339
ChromaDB 0.4.18
sentence-transformers 2.2.1
Python 3.12.0
### Who can help?
@hwchase17
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [X] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [X] Document Loaders
- [X] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Create a requirements file with these entries:
langchain
chromadb
sentence-transformers
Run pip install -r requirements.txt
### Expected behavior
I expect the install to complete correctly. | Dependency Issues with sentence-transformers and chromadb | https://api.github.com/repos/langchain-ai/langchain/issues/14073/comments | 1 | 2023-11-30T15:52:09Z | 2024-03-16T16:08:01Z | https://github.com/langchain-ai/langchain/issues/14073 | 2,018,961,211 | 14,073 |
[
"langchain-ai",
"langchain"
] | ### System Info
Python 3.11.5
langchain 0.0.343
langchain-core 0.0.7
sqlalchemy 2.0.21
### Who can help?
_No response_
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [X] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
```
# make a little database
import sqlite3
con = sqlite3.connect("test.db")
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS test_table")
cur.execute("CREATE TABLE test_table(a, b, c, d)")
cur.execute("INSERT INTO test_table VALUES (1,2,3,4)")
cur.execute("INSERT INTO test_table VALUES (4,5,6,7)")
cur.execute("INSERT INTO test_table VALUES (8,9,10,11)")
con.commit()
# then...
from langchain.sql_database import SQLDatabase
db = SQLDatabase.from_uri("sqlite:///test.db", include_tables=["test_table"], sample_rows_in_table_info=2)
print(db.table_info)
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/base.py:1965, in Connection._exec_single_context(self, dialect, context, statement, parameters)
1964 if not evt_handled:
-> 1965 self.dialect.do_execute(
1966 cursor, str_statement, effective_parameters, context
1967 )
1969 if self._has_events or self.engine._has_events:
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/default.py:921, in DefaultDialect.do_execute(self, cursor, statement, parameters, context)
920 def do_execute(self, cursor, statement, parameters, context=None):
--> 921 cursor.execute(statement, parameters)
OperationalError: near "FROM": syntax error
The above exception was the direct cause of the following exception:
OperationalError Traceback (most recent call last)
Cell In[23], line 3
1 from langchain.sql_database import SQLDatabase
2 db = SQLDatabase.from_uri("sqlite:///test.db", include_tables=["test_table"], sample_rows_in_table_info=2)
----> 3 print(db.table_info)
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/langchain/utilities/sql_database.py:286, in SQLDatabase.table_info(self)
283 @property
284 def table_info(self) -> str:
285 """Information about all tables in the database."""
--> 286 return self.get_table_info()
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/langchain/utilities/sql_database.py:334, in SQLDatabase.get_table_info(self, table_names)
332 table_info += f"\n{self._get_table_indexes(table)}\n"
333 if self._sample_rows_in_table_info:
--> 334 table_info += f"\n{self._get_sample_rows(table)}\n"
335 if has_extra_info:
336 table_info += "*/"
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/langchain/utilities/sql_database.py:357, in SQLDatabase._get_sample_rows(self, table)
354 try:
355 # get the sample rows
356 with self._engine.connect() as connection:
--> 357 sample_rows_result = connection.execute(command) # type: ignore
358 # shorten values in the sample rows
359 sample_rows = list(
360 map(lambda ls: [str(i)[:100] for i in ls], sample_rows_result)
361 )
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/base.py:1412, in Connection.execute(self, statement, parameters, execution_options)
1410 raise exc.ObjectNotExecutableError(statement) from err
1411 else:
-> 1412 return meth(
1413 self,
1414 distilled_parameters,
1415 execution_options or NO_OPTIONS,
1416 )
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/sql/elements.py:516, in ClauseElement._execute_on_connection(self, connection, distilled_params, execution_options)
514 if TYPE_CHECKING:
515 assert isinstance(self, Executable)
--> 516 return connection._execute_clauseelement(
517 self, distilled_params, execution_options
518 )
519 else:
520 raise exc.ObjectNotExecutableError(self)
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/base.py:1635, in Connection._execute_clauseelement(self, elem, distilled_parameters, execution_options)
1623 compiled_cache: Optional[CompiledCacheType] = execution_options.get(
1624 "compiled_cache", self.engine._compiled_cache
1625 )
1627 compiled_sql, extracted_params, cache_hit = elem._compile_w_cache(
1628 dialect=dialect,
1629 compiled_cache=compiled_cache,
(...)
1633 linting=self.dialect.compiler_linting | compiler.WARN_LINTING,
1634 )
-> 1635 ret = self._execute_context(
1636 dialect,
1637 dialect.execution_ctx_cls._init_compiled,
1638 compiled_sql,
1639 distilled_parameters,
1640 execution_options,
1641 compiled_sql,
1642 distilled_parameters,
1643 elem,
1644 extracted_params,
1645 cache_hit=cache_hit,
1646 )
1647 if has_events:
1648 self.dispatch.after_execute(
1649 self,
1650 elem,
(...)
1654 ret,
1655 )
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/base.py:1844, in Connection._execute_context(self, dialect, constructor, statement, parameters, execution_options, *args, **kw)
1839 return self._exec_insertmany_context(
1840 dialect,
1841 context,
1842 )
1843 else:
-> 1844 return self._exec_single_context(
1845 dialect, context, statement, parameters
1846 )
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/base.py:1984, in Connection._exec_single_context(self, dialect, context, statement, parameters)
1981 result = context._setup_result_proxy()
1983 except BaseException as e:
-> 1984 self._handle_dbapi_exception(
1985 e, str_statement, effective_parameters, cursor, context
1986 )
1988 return result
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/base.py:2339, in Connection._handle_dbapi_exception(self, e, statement, parameters, cursor, context, is_sub_exec)
2337 elif should_wrap:
2338 assert sqlalchemy_exception is not None
-> 2339 raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
2340 else:
2341 assert exc_info[1] is not None
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/base.py:1965, in Connection._exec_single_context(self, dialect, context, statement, parameters)
1963 break
1964 if not evt_handled:
-> 1965 self.dialect.do_execute(
1966 cursor, str_statement, effective_parameters, context
1967 )
1969 if self._has_events or self.engine._has_events:
1970 self.dispatch.after_cursor_execute(
1971 self,
1972 cursor,
(...)
1976 context.executemany,
1977 )
File ~/miniconda3/envs/forScience/lib/python3.11/site-packages/sqlalchemy/engine/default.py:921, in DefaultDialect.do_execute(self, cursor, statement, parameters, context)
920 def do_execute(self, cursor, statement, parameters, context=None):
--> 921 cursor.execute(statement, parameters)
OperationalError: (sqlite3.OperationalError) near "FROM": syntax error
[SQL: SELECT
FROM test_table
LIMIT ? OFFSET ?]
[parameters: (2, 0)]
(Background on this error at: https://sqlalche.me/e/20/e3q8)
```
### Expected behavior
From https://python.langchain.com/docs/use_cases/qa_structured/sql I expect:
```
CREATE TABLE "test_table" (
"a" INTEGER,
"b" INTEGER,
"c" INTEGER,
"d" INTEGER
)
/*
2 rows from test_table table:
a b c d
1 2 3 4
5 6 7 8
*/
```
| SQLDatabase.get_table_info is not returning useful information | https://api.github.com/repos/langchain-ai/langchain/issues/14071/comments | 5 | 2023-11-30T15:03:55Z | 2023-12-03T10:30:35Z | https://github.com/langchain-ai/langchain/issues/14071 | 2,018,865,714 | 14,071 |
[
"langchain-ai",
"langchain"
] | ### System Info
When I use below snippet of code
```
import os
from azure.identity import DefaultAzureCredential
from azure.identity import get_bearer_token_provider
from langchain.llms import AzureOpenAI
from langchain.chat_models import AzureChatOpenAI
credential = DefaultAzureCredential(interactive_browser_tenant_id=tenant_id,
interactive_browser_client_id=client_id,
client_secret=client_secret)
token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")
endpoint = "https://xxxx.openai.azure.com"
client = AzureOpenAI( azure_endpoint=endpoint,
api_version="2023-05-15",
azure_deployment="example-gpt-4",
azure_ad_token_provider=token_provider)
```
I get error :
```---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[36], line 21
18 # api_version = "2023-05-15"
19 endpoint = "https://xxxx.openai.azure.com"
---> 21 client = AzureOpenAI(
22 azure_endpoint=endpoint,
23 api_version="2023-05-15",
24 azure_deployment="example-gpt-4",
25 azure_ad_token_provider=token_provider,
26 )
File ~/PycharmProjects/aicc/env/lib/python3.9/site-packages/langchain_core/load/serializable.py:97, in Serializable.__init__(self, **kwargs)
96 def __init__(self, **kwargs: Any) -> None:
---> 97 super().__init__(**kwargs)
98 self._lc_kwargs = kwargs
File ~/PycharmProjects/aicc/env/lib/python3.9/site-packages/pydantic/v1/main.py:339, in BaseModel.__init__(__pydantic_self__, **data)
333 """
334 Create a new model by parsing and validating input data from keyword arguments.
335
336 Raises ValidationError if the input data cannot be parsed to form a valid model.
337 """
338 # Uses something other than `self` the first arg to allow "self" as a settable attribute
--> 339 values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data)
340 if validation_error:
341 raise validation_error
File ~/PycharmProjects/aicc/env/lib/python3.9/site-packages/pydantic/v1/main.py:1102, in validate_model(model, input_data, cls)
1100 continue
1101 try:
-> 1102 values = validator(cls_, values)
1103 except (ValueError, TypeError, AssertionError) as exc:
1104 errors.append(ErrorWrapper(exc, loc=ROOT_KEY))
File ~/PycharmProjects/aicc/env/lib/python3.9/site-packages/langchain/llms/openai.py:887, in AzureOpenAI.validate_environment(cls, values)
877 values["openai_api_base"] += (
878 "/deployments/" + values["deployment_name"]
879 )
880 values["deployment_name"] = None
881 client_params = {
882 "api_version": values["openai_api_version"],
883 "azure_endpoint": values["azure_endpoint"],
884 "azure_deployment": values["deployment_name"],
885 "api_key": values["openai_api_key"],
886 "azure_ad_token": values["azure_ad_token"],
--> 887 "azure_ad_token_provider": values["azure_ad_token_provider"],
888 "organization": values["openai_organization"],
889 "base_url": values["openai_api_base"],
890 "timeout": values["request_timeout"],
891 "max_retries": values["max_retries"],
892 "default_headers": values["default_headers"],
893 "default_query": values["default_query"],
894 "http_client": values["http_client"],
895 }
896 values["client"] = openai.AzureOpenAI(**client_params).completions
897 values["async_client"] = openai.AsyncAzureOpenAI(
898 **client_params
899 ).completions
KeyError: 'azure_ad_token_provider'
```
Ive also tried AzureChatOpenAI , and I get the same error back.
The error is not reproduced when I use openai library AzureOpenAI .
Also on openai the azure_ad_token_provider has type azure_ad_token_provider: 'AzureADTokenProvider | None' = None while in langchain it has type azure_ad_token_provider: Optional[str] = None which also makes me wonder if it would take as input a different type than string to work with.
any ideas on how to fix this? Im actually using Azure Service principal authentication, and if I use as alternative field azure_ad_token = credential.get_token(“https://cognitiveservices.azure.com/.default”).token I get token expired after 60min which does not happen with a bearer token, so It is important to me to make the token_provider work.
libraries :
pydantic 1.10.12
pydantic_core 2.10.1
openai 1.2.0
langchain 0.0.342
langchain-core 0.0.7
### Who can help?
@hwchase17 @agola11
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
import os
from azure.identity import DefaultAzureCredential
from azure.identity import get_bearer_token_provider
from langchain.llms import AzureOpenAI
from langchain.chat_models import AzureChatOpenAI
credential = DefaultAzureCredential(interactive_browser_tenant_id=tenant_id,
interactive_browser_client_id=client_id,
client_secret=client_secret)
token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")
endpoint = "https://xxxx.openai.azure.com"
client = AzureOpenAI( azure_endpoint=endpoint,
api_version="2023-05-15",
azure_deployment="example-gpt-4",
azure_ad_token_provider=token_provider)
### Expected behavior
client = AzureOpenAI( azure_endpoint=endpoint,
api_version="2023-05-15",
azure_deployment="example-gpt-4",
azure_ad_token_provider=token_provider)
should return a Runnable instance which I can use for LLMChain | AzureOpenAI azure_ad_token_provider Keyerror | https://api.github.com/repos/langchain-ai/langchain/issues/14069/comments | 6 | 2023-11-30T13:39:55Z | 2023-12-05T23:54:12Z | https://github.com/langchain-ai/langchain/issues/14069 | 2,018,694,209 | 14,069 |
[
"langchain-ai",
"langchain"
] | ### Issue with current documentation:
At end of [summarization documentation](https://python.langchain.com/docs/use_cases/summarization) the output is shown with a ValueError. Line that fail:
```python
summarize_document_chain.run(docs[0])
```
### Idea or request for content:
Looks like the docs[0] object is not what excepected. | DOC: Summarization output broken | https://api.github.com/repos/langchain-ai/langchain/issues/14066/comments | 0 | 2023-11-30T11:35:27Z | 2024-03-18T16:06:59Z | https://github.com/langchain-ai/langchain/issues/14066 | 2,018,460,541 | 14,066 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
When using `langchain.chat_models` such as `ChatAnthropic` and `ChatOpenAI`, I am seeing a bunch of HTTP logs that look like the following:
`2023-11-30 16:43:09 httpx INFO: HTTP Request: POST https://api.anthropic.com/v1/complete "HTTP[/1.1] 200 OK"`
Any suggestions on how to disable them?
### Suggestion:
_No response_ | Disable HTTP Request logging in Langchain | https://api.github.com/repos/langchain-ai/langchain/issues/14065/comments | 3 | 2023-11-30T11:22:43Z | 2024-07-26T11:15:51Z | https://github.com/langchain-ai/langchain/issues/14065 | 2,018,435,817 | 14,065 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I've created a custom tool to query the equity daily quote, I would like to have two parameters in the tool function: stock_name and trade_date, and I would expect LLM Agent will automatically decide how many days quotes or which day's quote it should retrieve.
```
class SearchSchema(BaseModel):
stock_name: str = Field(description="should be the name of the equity.")
trade_date: str = Field(description="should be the trading date of the equity.")
class DailyQuoteSearch(BaseTool):
name = "equity daily quote search"
description = "useful for equity daily quote retrieval"
return_direct = False
args_schema: Type[SearchSchema] = SearchSchema
def _run(self, stock_name: str, trade_date: str) -> str:
output = self.query_equity_daily_quote(stock_name, trade_date)
return output
```
However, LLM doesn't seem to know how to pass in the trade date? Is it possible to have LLM think about the what trade_date should be passed? or I expect too much on agent intelligence?
```
pydantic_core._pydantic_core.ValidationError: 1 validation error for SearchSchema
trade_date
Field required [type=missing, input_value={'stock_name': 'xxxx'}, input_type=dict]
```
### Suggestion:
_No response_ | How to have agent decide what param should be pass into a tool? | https://api.github.com/repos/langchain-ai/langchain/issues/14064/comments | 2 | 2023-11-30T10:31:15Z | 2024-03-17T16:06:57Z | https://github.com/langchain-ai/langchain/issues/14064 | 2,018,340,971 | 14,064 |
[
"langchain-ai",
"langchain"
] | ### System Info
I am using gpt-4 deployed on AzureOpenAI.
I want to get the model used. From openai, I will get the model we used. But when I tried with langchain I got an older model.
Basically, I am integrating with other services. So it is essential to get the model name intact for the cost calculations.
What could be the issue with the langcahin?
It works great with openai chat completion.
### Who can help?
@hwchase17 @agola11
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [X] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Steps to reproduce:
```
import os
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = "{}",
api_key="{}",
api_version="{}",
azure_deployment="gpt4",
)
response = client.chat.completions.create(
model="gpt4",
messages=[{"role": "user", "content": "tell me a joke"}]
)
response.model
```
> 'gpt-4'
```
from langchain.schema import HumanMessage
from langchain.chat_models.azure_openai import AzureChatOpenAI
llm = AzureChatOpenAI(
azure_endpoint = "{}",
openai_api_key="{}",
openai_api_version="{}",
azure_deployment="gpt4",
model_version="0613",
temperature=0
)
response = llm.generate(messages=[[HumanMessage(content="tell me a joke")]])
response.llm_output["model_name"]
```
> 'gpt-3.5-turbo'
```
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
prompt = PromptTemplate(
input_variables=["joke"],
template="Tell me a {joke}?",
)
chain = LLMChain(llm=llm, prompt=prompt)
response = chain.generate([{"joke":"joke"}])
response.llm_output["model_name"]
```
> 'gpt-3.5-turbo'
### Expected behavior
From all we should be getting gpt-4 as I have deployed only got-4 on azure openai | Azure OpenAI, gpt-4 model returns gpt-35-turbo | https://api.github.com/repos/langchain-ai/langchain/issues/14062/comments | 3 | 2023-11-30T09:38:58Z | 2023-12-01T07:08:48Z | https://github.com/langchain-ai/langchain/issues/14062 | 2,018,246,092 | 14,062 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I want to customize a LLM (a GPT-3.5-turbo) for chatting but don't proceed with chatting until the user provides his name and his phone number and validates the count of his phone number.
Please help me I tried many methods but without any significant result
### Suggestion:
_No response_ | Don't proceed with chatting until the user provides his name and phone number | https://api.github.com/repos/langchain-ai/langchain/issues/14057/comments | 5 | 2023-11-30T03:53:16Z | 2023-12-10T16:35:42Z | https://github.com/langchain-ai/langchain/issues/14057 | 2,017,823,760 | 14,057 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Do you have a new url?
https://python.langchain.com/docs/modules/chains/popular/
thank you
### Suggestion:
_No response_ | Issue: I can't visit the page of popular chains | https://api.github.com/repos/langchain-ai/langchain/issues/14054/comments | 1 | 2023-11-30T02:16:12Z | 2024-03-17T16:06:51Z | https://github.com/langchain-ai/langchain/issues/14054 | 2,017,743,973 | 14,054 |
[
"langchain-ai",
"langchain"
] | ### System Info
Python 3.11 running locally in PyCharm.
### Who can help?
@hwchase17 @agola11
### Information
- [x] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [X] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
```
def research_tool(input, thread_id=None):
# Initialize Tavily Search
search = TavilySearchAPIWrapper()
tavily_tool = TavilySearchResults(api_wrapper=search)
salesforce_history_tool = create_pinecone_tool()
# Initialize PlayWright Web Browser
sync_browser = create_sync_playwright_browser()
toolkit = PlayWrightBrowserToolkit.from_browser(sync_browser=sync_browser)
# Initialize the Toolkit
tools = toolkit.get_tools()
tools.append(tavily_tool) # Add Tavily Search to the Toolkit
tools.append(salesforce_history_tool) # Add Salesforce History to the Toolkit
tools.extend(sf_tools) # Add Salesforce Tools to the Toolkit
agent = OpenAIAssistantRunnable.create_assistant(
name="Research Assistant",
instructions="You are a personal research assistant on company information",
tools=tools,
model="gpt-4-1106-preview",
as_agent=True,
)
agent_executor = AgentExecutor(agent=agent, tools=tools)
if thread_id:
result = agent_executor.invoke({"content": input, "thread_id": thread_id})
else:
result = agent_executor.invoke({"content": input})
output = result['output']
thread_id = result['thread_id']
return output, thread_id
```
### Expected behavior
I am looking to have my agent run using the Assistants API. Instead, I receive the following error:
```
[chain/start] [1:chain:AgentExecutor > 4:chain:OpenAIAssistantRunnable] Entering Chain run with input:
[inputs]
[chain/error] [1:chain:AgentExecutor > 4:chain:OpenAIAssistantRunnable] [315ms] Chain run errored with error:
"BadRequestError(\"Error code: 400 - {'error': {'message': '1 validation error for Request\\\\nbody -> tool_outputs -> 0 -> output\\\\n str type expected (type=type_error.str)', 'type': 'invalid_request_error', 'param': None, 'code': None}}\")"
``` | OpenAIAssistantRunnable input validation error | https://api.github.com/repos/langchain-ai/langchain/issues/14050/comments | 2 | 2023-11-30T01:00:23Z | 2024-04-05T16:06:49Z | https://github.com/langchain-ai/langchain/issues/14050 | 2,017,681,132 | 14,050 |
[
"langchain-ai",
"langchain"
] | ### System Info
Python 3.10, mac OS
### Who can help?
@agola11 @hwchase17
### Information
- [X] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [X] Callbacks/Tracing
- [ ] Async
### Reproduction
With this script
```
from langchain.chains import RefineDocumentsChain, LLMChain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
document_prompt = PromptTemplate.from_template("{page_content}")
document_variable_name = "context"
llm = OpenAI()
# The prompt here should take as an input variable the
# `document_variable_name`
prompt = PromptTemplate.from_template(
"Summarize this content: {context}"
)
initial_llm_chain = LLMChain(llm=llm, prompt=prompt)
initial_response_name = "prev_response"
# The prompt here should take as an input variable the
# `document_variable_name` as well as `initial_response_name`
prompt_refine = PromptTemplate.from_template(
"Here's your first summary: {prev_response}. "
"Now add to it based on the following context: {context}"
)
refine_llm_chain = LLMChain(llm=llm, prompt=prompt_refine)
chain = RefineDocumentsChain(
initial_llm_chain=initial_llm_chain,
refine_llm_chain=refine_llm_chain,
document_prompt=document_prompt,
document_variable_name=document_variable_name,
initial_response_name=initial_response_name,
)
from langchain.schema import Document
text = """Nuclear power in space is the use of nuclear power in outer space, typically either small fission systems or radioactive decay for electricity or heat. Another use is for scientific observation, as in a Mössbauer spectrometer. The most common type is a radioisotope thermoelectric generator, which has been used on many space probes and on crewed lunar missions. Small fission reactors for Earth observation satellites, such as the TOPAZ nuclear reactor, have also been flown.[1] A radioisotope heater unit is powered by radioactive decay and can keep components from becoming too cold to function, potentially over a span of decades.[2]
The United States tested the SNAP-10A nuclear reactor in space for 43 days in 1965,[3] with the next test of a nuclear reactor power system intended for space use occurring on 13 September 2012 with the Demonstration Using Flattop Fission (DUFF) test of the Kilopower reactor.[4]
After a ground-based test of the experimental 1965 Romashka reactor, which used uranium and direct thermoelectric conversion to electricity,[5] the USSR sent about 40 nuclear-electric satellites into space, mostly powered by the BES-5 reactor. The more powerful TOPAZ-II reactor produced 10 kilowatts of electricity.[3]
Examples of concepts that use nuclear power for space propulsion systems include the nuclear electric rocket (nuclear powered ion thruster(s)), the radioisotope rocket, and radioisotope electric propulsion (REP).[6] One of the more explored concepts is the nuclear thermal rocket, which was ground tested in the NERVA program. Nuclear pulse propulsion was the subject of Project Orion.[7]
"""
docs = [
Document(
page_content=split,
metadata={"source": "https://en.wikipedia.org/wiki/Nuclear_power_in_space"},
)
for split in text.split("\n\n")
]
```
When I attach a callback that prints the [inputs](https://github.com/langchain-ai/langchain/blob/00a6e8962cc778cd8f6268cefc304465598c02cf/libs/core/langchain_core/callbacks/base.py#L197) in `on_chain_start`, even if every sub-chain only uses one Document, the `inputs` is always the full Document list.
### Expected behavior
I expect the `inputs` in `on_chain_start` only includes the inputs that are used by this chain, not always the full list, otherwise it's totally meaningless to duplicate the same inputs many times. | Callback.on_chain_start has wrong "inputs" in RefineDocumentsChain | https://api.github.com/repos/langchain-ai/langchain/issues/14048/comments | 1 | 2023-11-29T23:49:27Z | 2023-11-30T19:01:31Z | https://github.com/langchain-ai/langchain/issues/14048 | 2,017,623,699 | 14,048 |
[
"langchain-ai",
"langchain"
] | ### Issue with current documentation:
The current [section on Amazon OpenSearch Serverless][1] (AOSS) vector store uses the `AWS4Auth` class to authenticate to AOSS, yet the official [OpenSearch documentation][2] suggests using the `AWS4SignerAuth` class instead.
Further, the notebook lacks information on where to import the `AWS4Auth` class from and how to configure it with different AWS credentials (static access key/secret key, temporary credentials, etc.). It also lacks references on how to configure access policies (IAM, AOSS data access policies, etc.)
[1]: https://github.com/langchain-ai/langchain/blob/master/docs/docs/integrations/vectorstores/opensearch.ipynb
[2]: https://opensearch.org/docs/latest/clients/python-low-level/#connecting-to-amazon-opensearch-serverless
### Idea or request for content:
Add installation instructions for the [requests_aws4auth][1] package and links to its [Github repo][2] in order to showcase configuration with different AWS credentials. Additionally reference [AWS documentation for AOSS][3] in order to get started [setting up permissions][4]
[1]: https://pypi.org/project/requests-aws4auth/
[2]: https://github.com/tedder/requests-aws4auth#basic-usage
[3]: https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-getting-started.html
[4]: https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-data-access.html | DOC: Expand documentation on how to authenticate and connect to Amazon OpenSearch Serverless | https://api.github.com/repos/langchain-ai/langchain/issues/14042/comments | 2 | 2023-11-29T20:15:29Z | 2024-05-01T16:05:33Z | https://github.com/langchain-ai/langchain/issues/14042 | 2,017,348,030 | 14,042 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I only see `metadata` as parameter for few callback handler methods, but I would like to have access to metadata in other methods such as `on_chain_error()` and `on_llm_error()`.
Currently, I can only see the `tags` in these methods.
I have error handling in my callback handler using `on_chain_error()` and I'd like to add information in my metadata dictionary to my exceptions (such as LLM name, model, things related to my chain, etc...).
I can put a list of tags, but I'd much prefer to use a dictionary to get certain keys and have my exceptions instantiated properly.
### Suggestion:
Please make both tags and metadata available for all callback handler methods. | Missing metadata in some callback handler methods | https://api.github.com/repos/langchain-ai/langchain/issues/14041/comments | 2 | 2023-11-29T20:08:28Z | 2024-03-13T21:58:22Z | https://github.com/langchain-ai/langchain/issues/14041 | 2,017,338,609 | 14,041 |
[
"langchain-ai",
"langchain"
] | ### Feature request
I notice the other functions, such as add_texts and add_embeddings allow you to pass a unique list of IDs that can get paired with your embedding. There is no such parameter for the add_documents function. This means when you delete a document and add an updated version of it using add_documents, its unique ID won't be added to the vector store.
### Motivation
Inability to add unique ID to document after calling the add_documents function from FAISS
### Your contribution
Not sure as far as I know. If I can, let me know what you need from me. | Add Optional Parameter for Unique IDs in FAISS.add_documents Function | https://api.github.com/repos/langchain-ai/langchain/issues/14038/comments | 1 | 2023-11-29T18:48:20Z | 2024-03-13T21:58:17Z | https://github.com/langchain-ai/langchain/issues/14038 | 2,017,209,201 | 14,038 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Would be great to add the support for Azure GPT latest models in the get_openai_callback() --> https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/callbacks/openai_info.py
https://github.com/langchain-ai/langchain/issues/12994
### Suggestion:
Please add the Azure GPT models (latest) https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/callbacks/openai_info.py | Issue: support for Azure Open AI latest GPT models like, GPT 4 turpo in the get_openai_callback() | https://api.github.com/repos/langchain-ai/langchain/issues/14036/comments | 1 | 2023-11-29T18:08:30Z | 2024-03-13T21:58:12Z | https://github.com/langchain-ai/langchain/issues/14036 | 2,017,151,134 | 14,036 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Is it possible to convert a Conversation Chain into an Agent?
### Suggestion:
_No response_ | ConversationChain to Agent | https://api.github.com/repos/langchain-ai/langchain/issues/14034/comments | 2 | 2023-11-29T17:07:22Z | 2024-05-22T16:07:43Z | https://github.com/langchain-ai/langchain/issues/14034 | 2,017,049,508 | 14,034 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I want to integrate ConversationalRetrievalChain with history into Gradio app.
For now I have the following approach:
```
# Memory buffer
memory = ConversationBufferWindowMemory(k=2,memory_key="chat_history", return_messages=True)
# LLM chain
chain = ConversationalRetrievalChain.from_llm(llm=llm, chain_type='stuff',
retriever=vector_store.as_retriever(
search_kwargs={"k": 2}),
memory=memory)
with gr.Blocks() as demo:
gr.Markdown("# SageMaker Docs Chat 🤗")
gr.Markdown("### Ask me question about Amazon SageMaker!")
chatbot = gr.Chatbot(label="Chat history")
message = gr.Textbox(label="Ask me a question!")
clear = gr.Button("Clear")
def user(user_message, chat_history):
return gr.update(value="", interactive=False), chat_history + [[user_message, None]]
def bot(chat_history):
user_message = chat_history[-1][0]
llm_response = qa({"question": user_message})
bot_message = llm_response["answer"]
chat_history[-1][1] = ""
for character in bot_message:
chat_history[-1][1] += character
time.sleep(0.005)
yield chat_history
response = message.submit(user, [message, chatbot], [message, chatbot], queue=False).then(
bot, chatbot, chatbot
)
response.then(lambda: gr.update(interactive=True), None, [message], queue=False)
demo.queue()
demo.launch()
```
which works fine for the simple question answer without history. I tried to implement something similar to this guide (https://github.com/facebookresearch/llama-recipes/blob/main/demo_apps/Llama2_Gradio.ipynb), but failed to do so. Do you have any solution for this use-case or any specific guide?
### Suggestion:
_No response_ | Optimal Integration of the ConversationalRetrievalChain (Open source llama-2) into gradio. | https://api.github.com/repos/langchain-ai/langchain/issues/14033/comments | 1 | 2023-11-29T16:50:09Z | 2024-03-13T20:00:16Z | https://github.com/langchain-ai/langchain/issues/14033 | 2,017,018,704 | 14,033 |
[
"langchain-ai",
"langchain"
] | ### System Info
langchain==0.0.330, python 3.9
### Who can help?
@hwchase17 @agola11
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [X] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
I created an agent as follows:
```
def batch_embedding(node_label:str, text_node_properties:list):
vector_index = Neo4jVector.from_existing_graph(
OpenAIEmbeddings(),
url=URL_DB_GRAPH,
username=USERNAME,
password=PASSWORD,
index_name= node_label,
node_label= node_label,
text_node_properties=text_node_properties,
embedding_node_property='embedding',
)
return vector_index
```
model_name= "gpt-4"
llm= ChatOpenAI(temperature=0, model_name=model_name)
vector_index = batch_embedding("Alarms", ["solution", "description", "type"])
vector_qa = RetrievalQA.from_chain_type(
llm=llm, chain_type="stuff", retriever=vector_index.as_retriever())
```
cypher_chain = GraphCypherQAChain.from_llm(
cypher_llm = llm,
qa_llm = ChatOpenAI(temperature=0), graph=graph, verbose=True, cypher_prompt=CYPHER_GENERATION_PROMPT
)
```
tools = [
Tool(
name="Alarms",
func=vector_qa.run,
description=prompt_per_alarms,
),
Tool(
name="Graph",
func=cypher_chain.run,
description=prompt_per_Graph,
),
]
mrkl = initialize_agent(
tools, ChatOpenAI(temperature=0, model_name=model_name), agent=AgentType.OPENAI_FUNCTIONS, verbose=True, memory=memory
)
message = request.form['message']
response = mrkl.run(message)
When I receive an answer from cypher_chain.run I can see that I've a full context with an output but the finished chain says "I'm sorry, but I don't have the information.." (see the image attached)

.
I noticed that this issue come back when I have a full context with an array of data.
### Expected behavior
Finished chain contains the full context and write the answer. | Finished chain without an answer but full context have results | https://api.github.com/repos/langchain-ai/langchain/issues/14031/comments | 3 | 2023-11-29T16:24:00Z | 2024-07-31T17:55:02Z | https://github.com/langchain-ai/langchain/issues/14031 | 2,016,963,828 | 14,031 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I am currently piecing together some of the tutorials on the langchain documentation page to use a CustomOutputParser and a CustomPrompt Template similar to the ZeroShotReact Template.
While parsing the actions, I have a scenario where, the model returns Action as None & Action Input as None. In that case, I would like access to the dynamically created prompt with in the CustomOutputParser to call another LLM and return the action as call to another LLM to complete the action.
**Current Approach:**
```python
# Set up a prompt template
class CustomPromptTemplatePirate(StringPromptTemplate):
# The template to use
template: str
# The list of tools available
tools: List[Tool]
def format(self, **kwargs) -> str:
# Get the intermediate steps (AgentAction, Observation tuples)
# Format them in a particular way
intermediate_steps = kwargs.pop("intermediate_steps")
thoughts = ""
for action, observation in intermediate_steps:
thoughts += action.log
thoughts += f"\nObservation: {observation}\nThought: "
# Set the agent_scratchpad variable to that value
kwargs["agent_scratchpad"] = thoughts
# Create a tools variable from the list of tools provided
kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools])
# Create a list of tool names for the tools provided
kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools])
return self.template.format(**kwargs)
class CustomOutputParserPirate(AgentOutputParser):
def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:
# Check if agent should finish
if "Final Answer:" in llm_output:
return AgentFinish(
# Return values is generally always a dictionary with a single `output` key
# It is not recommended to try anything else at the moment :)
return_values={"output": llm_output.split("Final Answer:")[-1].strip()},
log=llm_output,
)
# Parse out the action and action input
regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
match = re.search(regex, llm_output, re.DOTALL)
if not match:
raise OutputParserException(f"Could not parse LLM output: `{llm_output}`")
action = match.group(1).strip()
action_input = match.group(2)
# Return the action and action input
return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output)
# Set up the base template
template = """Complete the objective 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
These were previous tasks you completed:
Begin!
Question: {input}
{agent_scratchpad}"""
search = SerpAPIWrapper()
tools= [Tool(
name="Search",
func=search.run,
description="useful for when you need to answer questions about current events",
)]
prompt = CustomPromptTemplatePirate(
template=template,
tools=tools,
# This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically
# This includes the `intermediate_steps` variable because that is needed
input_variables=["input", "intermediate_steps"]
)
output_parser = CustomOutputParserPirate()
# LLM chain consisting of the LLM and a prompt
llm_chain = LLMChain(llm=llm, prompt=prompt)
tool_names = [tool.name for tool in tools]
agent = LLMSingleActionAgent(
llm_chain=llm_chain,
output_parser=output_parser,
stop=["\nObservation:"],
allowed_tools=tool_names
)
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
agent_executor.run("How many people live in canada as of 2023?")
```
**Challenges Faced:**
I am unable to figure out how to access the callback or any other similar approach to use the complete Prompt/User Input with in the context of the CustomOutputParser
**Desired Outcome:**
```python
def parse(self, llm_output: str, prompt:start) -> Union[AgentAction, AgentFinish]:
# Check if agent should finish
.....
if not 'Action' & not 'Action Input' :
call AgentAction with another llm fine_tuned defined as tool with the user question as input ex: Write a summary on Canada. I need a way to access the user question here.
```
I would greatly appreciate any advice, documentation, or examples that could assist me in accomplishing this task. Thank you very much for your time and support.
### Suggestion:
_No response_ | Issue: Request: Need Help with CustomAgentExecutor for Accessing Dynamically Created Prompts | https://api.github.com/repos/langchain-ai/langchain/issues/14027/comments | 3 | 2023-11-29T15:19:25Z | 2024-03-17T16:06:46Z | https://github.com/langchain-ai/langchain/issues/14027 | 2,016,824,570 | 14,027 |
[
"langchain-ai",
"langchain"
] | ### System Info
Python 3.10
Langchain 0.0.311
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [X] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
```python
from langchain.text_splitter import RecursiveCharacterTextSplitter
url = "https://plato.stanford.edu/entries/goedel/"
headers_to_split_on = [
("h1", "Header 1"),
("h2", "Header 2"),
("h3", "Header 3"),
("h4", "Header 4"),
]
html_splitter = HTMLHeaderTextSplitter(headers_to_split_on=headers_to_split_on)
# for local file use html_splitter.split_text_from_file(<path_to_file>)
html_header_splits = html_splitter.split_text_from_url(url)
chunk_size = 500
chunk_overlap = 30
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size, chunk_overlap=chunk_overlap
)
# Split
splits = text_splitter.split_documents(html_header_splits)
splits[80:85]
```
[Reference](https://python.langchain.com/docs/modules/data_connection/document_transformers/text_splitters/HTML_header_metadata#2-pipelined-to-another-splitter-with-html-loaded-from-a-web-url)
The bug seems to be in [etree](https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/text_splitter.py#L586). A simple fix is perhaps like below:
```python
from lxml import etree
from pathlib import Path
path = Path(".../langchain/document_transformers/xsl/html_chunks_with_headers.xslt")
# etree.parse(path) Throws
etree.parse(str(path))
```
### Expected behavior
The code in the reproducer should work. | HTMLHeaderTextSplitter throws TypeError: cannot parse from 'PosixPath' | https://api.github.com/repos/langchain-ai/langchain/issues/14024/comments | 1 | 2023-11-29T13:17:28Z | 2024-03-13T19:57:17Z | https://github.com/langchain-ai/langchain/issues/14024 | 2,016,575,594 | 14,024 |
[
"langchain-ai",
"langchain"
] | > langchain-experimental : 0.0.42
> langchain : 0.0.340
> gpt4all : 2.0.2
> PostgreSQL : 15.5
I am trying to query my postgres db using the following code:
```
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain_experimental.sql import SQLDatabaseChain
from langchain.memory import ConversationBufferMemory
from langchain import SQLDatabase
from langchain.llms import GPT4All
from langchain.prompts import PromptTemplate
from langchain.globals import set_verbose
import os
username = "postgres"
password = "password"
host = "127.0.0.1" # internal IP
port = "5432"
mydatabase = "reporting_db"
pg_uri = f'postgresql://{username}:{password}@{host}:{port}/{mydatabase}'
my_db = SQLDatabase.from_uri(pg_uri)
_DEFAULT_TEMPLATE = '''Given an input question, first create a syntactically correct {dialect} query to run,
then look at the results of the query and return the answer.
Use the following format:
Question: "Question here"
SQLQuery: "SQL Query to run"
SQLResult: "Result of the SQLQuery"
Answer: "Final answer here"
Only use the following tables:
{table_info}
If someone asks for the book written, they really mean the work table.
Question: {input}'''
PROMPT = PromptTemplate(
input_variables=["input", "table_info", "dialect"],
template=_DEFAULT_TEMPLATE
)
path = "/var/lib/postgresql/data/llama-2-7b.Q2_K.gguf"
callbacks = [StreamingStdOutCallbackHandler()]
llm = GPT4All(model = path,
callbacks=callbacks,
n_threads=8,
max_tokens=81920,
verbose=True
)
set_verbose(True)
db_chain = SQLDatabaseChain.from_llm(llm = llm,
db = my_db,
prompt = PROMPT,
use_query_checker=True,
verbose = True
)
question = 'Count the rows on table Access'
answer = db_chain(question)
print(answer)```
but I am getting the following error:
```ERROR: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "```"
LINE 1: ```sql
^
[SQL: ```sql
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (
SELECT * FROM (]
```
### Suggestion:
_No response_ | Recursive query when connecting to postgres db | https://api.github.com/repos/langchain-ai/langchain/issues/14022/comments | 1 | 2023-11-29T10:55:01Z | 2024-03-13T19:55:54Z | https://github.com/langchain-ai/langchain/issues/14022 | 2,016,322,236 | 14,022 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Hi, I'm looking for some implementation that's utilizing a ConversationChain and giving it access to Internet. I want to integrate duckduckgo or bing-api or serpapi into my ConversationChain.
Would appreciate any help! Thanks
### Suggestion:
_No response_ | Unable to Integrate ConversationChain with Tools like duckduckgo or serp-api | https://api.github.com/repos/langchain-ai/langchain/issues/14021/comments | 3 | 2023-11-29T10:47:49Z | 2024-03-13T19:57:49Z | https://github.com/langchain-ai/langchain/issues/14021 | 2,016,308,490 | 14,021 |
[
"langchain-ai",
"langchain"
] | ### System Info
IPython : 8.15.0
ipykernel : 6.25.0
ipywidgets : 8.0.4
jupyter_client : 7.4.9
jupyter_core : 5.5.0
jupyter_server : 1.23.4
jupyterlab : 3.5.3
nbclient : 0.8.0
nbconvert : 7.10.0
nbformat : 5.9.2
notebook : 6.5.4
qtconsole : 5.4.2
traitlets : 5.7.1
Python 3.11.6
Langchain '0.0.340'
### Who can help?
_No response_
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [X] Async
### Reproduction
TypeError: object Document can't be used in 'await' expression
translated_document = await qa_translator.atransform_documents(documents)
from official documentation notebook :
https://github.com/langchain-ai/langchain/blob/1cd9d5f3328e144cbe5d6ef52a22029d4fdf0cce/docs/docs/integrations/document_transformers/doctran_translate_document.ipynb
### Expected behavior
The problem might be arise due to specific python version or asyncio . | Doctran translate documents | https://api.github.com/repos/langchain-ai/langchain/issues/14020/comments | 2 | 2023-11-29T10:46:04Z | 2024-03-16T16:07:25Z | https://github.com/langchain-ai/langchain/issues/14020 | 2,016,305,395 | 14,020 |
[
"langchain-ai",
"langchain"
] | ### Feature request
It would interesting to have the option tu run a OpenAIAssistantRunnable that has access to custom tools and OpenAI build in tools like code_intrepreter, vision and retrieval.
### Motivation
It would increase the developers capabilty of creating even more powerful agents.
### Your contribution
n/a | Ability to use custom tools and openai build in functions on OpenAIAssistantRunnable | https://api.github.com/repos/langchain-ai/langchain/issues/14019/comments | 1 | 2023-11-29T10:41:57Z | 2024-03-13T20:03:43Z | https://github.com/langchain-ai/langchain/issues/14019 | 2,016,297,886 | 14,019 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I use the below code to load data and splitted it and embedded it and finally pushing it into vector store. during that process,
I'm getting **openai.NotFoundError: Error code: 404 - {'error': {'code': '404', 'message': 'Resource not found'}}**. After this method failed, I also tried with AzurecosmosDBVectorsearch vector store it also failed and returned the same error. Kindly help on this.
```
from langchain.embeddings.azure_openai import AzureOpenAIEmbeddings
from langchain.vectorstores.azure_cosmos_db import AzureCosmosDBVectorSearch
from langchain.vectorstores.chroma import Chroma
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.document_loaders import PyPDFLoader
# Load PDF
loaders = [
PyPDFLoader("ai.pdf")
]
docs = []
for loader in loaders:
docs.extend(loader.load())
# Define the Text Splitter
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1500,
chunk_overlap=150
)
# Create a split of the document using the text splitter
res_splits = text_splitter.split_documents(docs)
embedding = AzureOpenAIEmbeddings(
openai_api_version="1699-02-30",
openai_api_key="xxxxxxxxxxxxxxxxxxxxxxxxx",
# model_name="gpt-35-turbo",
azure_endpoint="https://ggggggggggggggggggggggg.openai.azure.com/")
persist_directory = 'docs/chroma/'
# Create the vector store
vectordb = Chroma.from_documents(
documents=res_splits,
embedding=embedding,
persist_directory=persist_directory
)
print(vectordb._collection.count())
```
### Suggestion:
_No response_ | Issue: openai.NotFoundError: Error code: 404 - {'error': {'code': '404', 'message': 'Resource not found'}} | https://api.github.com/repos/langchain-ai/langchain/issues/14018/comments | 8 | 2023-11-29T10:18:06Z | 2024-06-08T16:07:41Z | https://github.com/langchain-ai/langchain/issues/14018 | 2,016,254,745 | 14,018 |
[
"langchain-ai",
"langchain"
] | ### System Info
Python 3.10.10 langchain@0.0.342
langchain-core@ 0.0.7
### Who can help?
_No response_
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
md_file = docs[0].page_content
headers_to_split_on = [
("###", "Section"),
]
markdown_splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on)
md_header_splits = markdown_splitter.split_text(md_file)
chunk_size = 500
chunk_overlap = 0
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size, chunk_overlap=chunk_overlap
)
all_splits = text_splitter.split_documents(md_header_splits)
vectorstore = Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings())
metadata_field_info = [
AttributeInfo(
name="Section",
description="Part of the document that the text comes from",
type="string or list[string]",
),
]
document_content_description = "Major sections of the document"
# Define self query retriever
llm = OpenAI(temperature=0)
retriever = SelfQueryRetriever.from_llm(
llm, vectorstore, document_content_description, metadata_field_info, verbose=True
)
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
qa_chain = RetrievalQA.from_chain_type(llm, retriever=retriever)
qa_chain.run("衰老有哪些因素?")
### Expected behavior
how can I fix the problem | when I run the demo from the cookbook,I get error Error code: 404 - {'error': {'message': 'The model `text-davinci-003` does not exist1', 'type': 'invalid_request_error', 'param': None, 'code': 'model_not_found'}} | https://api.github.com/repos/langchain-ai/langchain/issues/14017/comments | 1 | 2023-11-29T08:45:42Z | 2024-03-13T20:00:32Z | https://github.com/langchain-ai/langchain/issues/14017 | 2,016,092,448 | 14,017 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
When I call Llam2-70b-chat model using conversation chain, I got very short response from the model. But if I use LLMChain to call the model, it can give me a long response. So, is there any thing cut off or limit the response length in conversation chain? The model parameter about max_new_tokens I set as 4096, so I don't think that is caused by the model.
<img width="1589" alt="截屏2023-11-29 15 47 33" src="https://github.com/langchain-ai/langchain/assets/27841780/34eb62c5-ce1f-4296-9ff8-6298c0c031d6">
### Suggestion:
_No response_ | Issue: how to increase the conversation chain response length? | https://api.github.com/repos/langchain-ai/langchain/issues/14015/comments | 1 | 2023-11-29T07:49:03Z | 2024-03-13T20:04:32Z | https://github.com/langchain-ai/langchain/issues/14015 | 2,016,008,120 | 14,015 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Hi,
I am using Langchain and LlamaCpp to load my models.
I have set "`mirostat`" and "`repitition_penalty`" in my model params and recently I am getting the following UserWarning:
```
UserWarning: WARNING! repetition_penalty is not default parameter.
repetition_penalty was transferred to model_kwargs.
Please confirm that repetition_penalty is what you intended.
```
and
```
UserWarning: WARNING! mirostat is not default parameter.
mirostat was transferred to model_kwargs.
Please confirm that mirostat is what you intended.
```
Here is my code:
```
import box
import yaml
from langchain.llms import LlamaCpp
from langchain.callbacks.manager import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
def build_llm(model_path):
callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
n_gpu_layers = 1 # Metal set to 1 is enough.
n_batch = 512 # Should be between 1 and n_ctx, consider the amount of RAM of your Apple Silicon Chip.
if model_path == "/Users/mweissenba001/Documents/llama2/llama.cpp/models/7B/ggml-model-q4_0.bin":
context_size = 4000
if model_path == "/Users/mweissenba001/Documents/rag_example/Modelle/llama-2-13b-german-assistant-v2.Q5_K_M.gguf":
context_size = 4000
else:
context_size = 7000
llm = LlamaCpp(
max_tokens =cfg.MAX_TOKENS,
model_path=model_path,
temperature=cfg.TEMPERATURE,
f16_kv=True,
n_ctx=context_size, # 8k aber mann muss Platz lassen für Instruction, History etc.
n_gpu_layers=n_gpu_layers,
n_batch=n_batch,
callback_manager=callback_manager,
verbose=True, # Verbose is required to pass to the callback manager
top_p=0.75,
top_k=40,
repetition_penalty=1.1,
mirostat = 2,
)
return llm
llm = build_llm(model_path)
```
My current Langchain Version is:
`langchain-0.0.339`
Upgrading to `langchain-0.0.341` didn't help.
So what do I have to do to prevent the warnings? Where in model_kwargs to I have to set mirostat and repitition_penalty?
### Suggestion:
_No response_ | UserWarning: WARNING! repetition_penalty is not default parameter. | https://api.github.com/repos/langchain-ai/langchain/issues/14014/comments | 1 | 2023-11-29T07:43:04Z | 2024-03-13T20:03:38Z | https://github.com/langchain-ai/langchain/issues/14014 | 2,016,000,077 | 14,014 |
[
"langchain-ai",
"langchain"
] | ### Feature request
[Rephrase and Respond: Let Large Language Models Ask Better Questions for Themselves](https://arxiv.org/abs/2311.04205)
",,,RaR is complementary to CoT and can be combined with CoT to achieve even better performance,,,"
- interesting prompt technique.
Could be implemented with LangChain.
### Motivation
to make LangChain more powerful?
### Your contribution
I can help with documentation | `Rephrase and Respond` | https://api.github.com/repos/langchain-ai/langchain/issues/14003/comments | 1 | 2023-11-29T03:12:45Z | 2024-03-13T20:00:34Z | https://github.com/langchain-ai/langchain/issues/14003 | 2,015,715,132 | 14,003 |
[
"langchain-ai",
"langchain"
] | ### Issue with current documentation:
Streamlit tutorial suggests
```
from langchain.memory import ConversationBufferMemory
from langchain.memory.chat_message_histories import StreamlitChatMessageHistory
# Optionally, specify your own session_state key for storing messages
msgs = StreamlitChatMessageHistory(key="special_app_key")
memory = ConversationBufferMemory(memory_key="history", chat_memory=msgs)
if len(msgs.messages) == 0:
msgs.add_ai_message("How can I help you?")
```
but in version 0.340, definition of ConversationBufferMemory only includes parameter memory_key but not chat_history.
I have noticed my model outputs being less accurate for the same script when streamlit is incorporated and I suspect this is the issue.
### Idea or request for content:
Please clarify how to best implement Streamlit with chat history. | DOC: streamlit memory parameters - memory_key and chat_history | https://api.github.com/repos/langchain-ai/langchain/issues/13995/comments | 2 | 2023-11-29T00:14:13Z | 2024-04-23T16:55:13Z | https://github.com/langchain-ai/langchain/issues/13995 | 2,015,551,448 | 13,995 |
[
"langchain-ai",
"langchain"
] | ### System Info
Code
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True, return_sql=False, use_query_checker=True, prompt=prompt_template)
db_chain.run("What are some recently added dockets and their title?")
Verbose
> Entering new SQLDatabaseChain chain...
What are some recently added dockets and their title?
SQLQuery:SELECT id, title, modifyDate FROM docket ORDER BY modifyDate DESC LIMIT 5;
SQLResult: [('CMS-2023-0184', 'CY 2024 Inpatient Hospital Deductible and Hospital and Extended Care Services Coinsurance Amounts. CMS-8083-N', datetime.datetime(2023, 11, 1, 15, 34, 1)), ('CMS-2023-0183', '(CMS-10143) State Data for the Medicare Modernization Act (MMA)', datetime.datetime(2023, 11, 1, 10, 34, 24)), ('CMS-2023-0181', 'CHIP State Plan Eligibility (CMS-10398 #17)', datetime.datetime(2023, 11, 1, 10, 25, 35)), ('CMS-2023-0182', '(CMS-10434 #77) Medicaid and Continuous Eligibility for Children', datetime.datetime(2023, 11, 1, 10, 24, 56)), ('CMS-2023-0180', 'Virtual Groups for Merit Based Incentive Payment System (MIPS) (CMS-10652)', datetime.datetime(2023, 10, 31, 13, 8, 24))]
Answer:SELECT id, title, modifyDate FROM docket ORDER BY modifyDate DESC LIMIT 5;
> Finished chain.
Output:
'SELECT id, title, modifyDate FROM docket ORDER BY modifyDate DESC LIMIT 5;'
The chain is not returning the SQLResult in the chat format even though the query is executed correctly.
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [X] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
prompt_suffix = """
If asked for recent dockets, give 5 most recent ones.
Make sure the table name is in the database.
Table name: docket,
Use only these columns when selecting: id, title, modifyDate
"""
prompt_template = PromptTemplate.from_template(prompt_suffix)
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True, return_sql=False, use_query_checker=True, prompt=prompt_template)
db_chain.run("What are some recently added dockets and their title?")
### Expected behavior
Example output:
The recently added dockets with their dates are:\n\n* CMS-2023-0181 - CY 2024 Inpatient Hospital Deductible and Hospital and Extended Care Services Coinsurance Amounts (November 1st, 2023' | SQLDatabaseChain returning Question and SQL Query instead of answer | https://api.github.com/repos/langchain-ai/langchain/issues/13994/comments | 4 | 2023-11-28T23:56:36Z | 2024-06-24T12:26:33Z | https://github.com/langchain-ai/langchain/issues/13994 | 2,015,530,321 | 13,994 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Hi there,
Before I was using local pickle files as the source of storage of my PDFs and chat history. And now I am moving into next step where I want to using Pinecone as my vector database to store these. I have made couple changes and they are not working and giving my error message. Especially for the part where I check if the embeddings are already stored in Pinecone and only create new embeddings for new files.
Here is my code:
## Imports
import streamlit as st
import os
from apikey import apikey
import pickle
from PyPDF2 import PdfReader
# Streamlit - user interface
from streamlit_extras.add_vertical_space import add_vertical_space
# Langchain
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.llms import OpenAI
from langchain.chains.question_answering import load_qa_chain
from langchain.callbacks import get_openai_callback
from langchain.chat_models.openai import ChatOpenAI
from langchain.schema import (SystemMessage, HumanMessage, AIMessage)
# Pinecone
from langchain.vectorstores import Pinecone
import pinecone
os.environ['OPENAI_API_KEY'] = apikey
## User Interface
# Side Bar
with st.sidebar:
st.title('🚀 Zi-GPT Version 2.0')
st.markdown('''
## About
This app is an LLM-powered chatbot built using:
- [Streamlit](https://streamlit.io/)
- [LangChain](https://python.langchain.com/)
- [OpenAI](https://platform.openai.com/docs/models) LLM model
''')
add_vertical_space(5)
st.write('Made with ❤️ by Zi')
# Main Page
def main():
st.header("Zi's PDF Helper: Chat with PDF")
# upload a PDF file
pdf = st.file_uploader("Please upload your PDF here", type='pdf')
# st.write(pdf)
# read PDF
if pdf is not None:
pdf_reader = PdfReader(pdf)
# split document into chunks
# also can use text split: good for PDFs that do not contains charts and visuals
sections = []
for page in pdf_reader.pages:
# Split the page text by paragraphs (assuming two newlines indicate a new paragraph)
page_sections = page.extract_text().split('\n\n')
sections.extend(page_sections)
chunks = sections
# st.write(chunks)
## embeddings
# Set up Pinecone
pinecone.init(api_key='d8d78cba-fbf1-42c6-a761-9e89a5ed24eb', environment='gcp-starter')
index_name = 'langchainresearch'
if index_name not in pinecone.list_indexes():
pinecone.create_index(index_name, dimension=1536, metric="cosine") # Adjust the dimension as per your embeddings
index = pinecone.Index(index_name)
file_name = pdf.name[:-4]
# Check if embeddings are already stored in Pinecone
if index.exists(id=file_name):
# Fetch embeddings from Pinecone
VectorStore = index.fetch(ids=[file_name])[file_name]
st.write('Embeddings Loaded from Pinecone')
else:
# Compute embeddings
embeddings = OpenAIEmbeddings(model="text-embedding-ada-002")
VectorStore = FAISS.from_texts(chunks, embedding=embeddings)
# Store embeddings in Pinecone
vectors = VectorStore.get_all_vectors()
index.upsert(vectors={(file_name, vectors)})
st.write('Embeddings Computation Completed and Stored in Pinecone')
# Create chat history
# Pinecone Setup for Chat History
chat_history_index_name = 'chat_history'
if chat_history_index_name not in pinecone.list_indexes():
pinecone.create_index(chat_history_index_name, dimension=1) # Dimension is 1 as we're not storing vectors here
chat_history_index = pinecone.Index(chat_history_index_name)
# Create or Load Chat History from Pinecone
if pdf:
# Check if chat history exists in Pinecone
if chat_history_index.exists(id=pdf.name):
# Fetch chat history from Pinecone
chat_history = chat_history_index.fetch(ids=[pdf.name])[pdf.name]
st.write('Chat History Loaded from Pinecone')
else:
# Initialize empty chat history
chat_history = []
# Initialize chat_history in session_state if not present
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# Check if 'prompt' is in session state
if 'last_input' not in st.session_state:
st.session_state.last_input = ''
# User Input
current_prompt = st.session_state.get('user_input', '')
prompt_placeholder = st.empty()
prompt = prompt_placeholder.text_area("Ask questions about your PDF:", value=current_prompt, placeholder="Send a message", key="user_input")
submit_button = st.button("Submit")
if submit_button and prompt:
# Update the last input in session state
st.session_state.last_input = prompt
docs = VectorStore.similarity_search(query=prompt, k=3)
#llm = OpenAI(temperature=0.9, model_name='gpt-3.5-turbo')
chat = ChatOpenAI(model='gpt-4', temperature=0.7, max_tokens=3000)
message = [
SystemMessage(content="You are a helpful assistant"),
HumanMessage(content=prompt)
]
chain = load_qa_chain(llm=chat, chain_type="stuff")
with get_openai_callback() as cb:
response = chain.run(input_documents=docs, question=message)
print(cb)
# st.write(response)
# st.write(docs)
# Process the response using AIMessage schema
# ai_message = AIMessage(content="AI message content")
# ai_message.content = response.generations[0].message.content
# Add to chat history
chat_entry = {
"user_message": prompt,
"bot_response": response
}
# Save chat history
# Generate a unique ID for the chat entry, e.g., using a timestamp or a UUID
chat_entry_id = generate_unique_id()
pinecone_upsert(chat_history_index, {chat_entry_id: chat_entry})
# Clear the input after processing
prompt_placeholder.text_area("Ask questions about your PDF:", value='', placeholder="Send a message", key="pdf_prompt")
# Display the entire chat
chat_history = pinecone_query(chat_history_index, query_params)
chat_content = ""
for entry in chat_history:
user_msg = entry["user_message"]
bot_resp = entry["bot_response"]
chat_content += f"<div style='background-color: #222222; color: white; padding: 10px;'>**You:** {user_msg}</div>"
chat_content += f"<div style='background-color: #333333; color: white; padding: 10px;'>**Zi GPT:** {bot_resp}</div>"
st.markdown(chat_content, unsafe_allow_html=True)
if __name__ == '__main__':
main()
### Suggestion:
_No response_ | Issue: Introduce Pinecone into my PDF reader LLM | https://api.github.com/repos/langchain-ai/langchain/issues/13987/comments | 2 | 2023-11-28T21:48:49Z | 2024-01-24T14:59:06Z | https://github.com/langchain-ai/langchain/issues/13987 | 2,015,378,058 | 13,987 |
[
"langchain-ai",
"langchain"
] | I was working with a sqlite DB that I created for a large dataset (~150k rows).
Code snippets:
`db = SQLDatabase.from_uri("sqlite:///MLdata.sqlite")`
`SQLITE_PROMPT_TEXT = '''You are a SQLite expert. Given an input question, first create a
syntactically correct SQLite query to run, then look at the results of the query and return
the answer to the input question.
Unless the user specifies in the question a specific number of examples to obtain, query for
at most {top_k} results using the LIMIT clause as per SQLite. You can order the results to
return the most informative data in the database.
Never query for all columns from a table. You must query only the columns that are needed to
answer the question. Wrap each column name in double quotes (") to denote them as delimited
identifiers.
Pay attention to use only the column names you can see in the tables below. Be careful to not
query for columns that do not exist. Also, pay attention to which column is in which table.
Use the following format:
Question: Question here
SQLQuery: SQL Query to run
SQLResult: Result of the SQLQuery
Answer: Final answer here
Only use the following tables:
{table_info}
Question: {input}'''`
`SQLITE_PROMPT = PromptTemplate(input_variables=['input', 'table_info', 'top_k'], template=SQLITE_PROMPT_TEXT)
sql_chain = SQLDatabaseChain(llm=local_llm, database=db, prompt=SQLITE_PROMPT, return_direct=False, return_intermediate_steps=False, verbose=False)
res=sql_chain("How many rows is in this db?")`
Response: 'There are 142321 rows in the input_table of this db.'
Second query
`res=sql_chain("Count rows with 'Abdominal pain', VAX_TYPE='COVID19', SEX= 'F' and HOSPITAL= 'Y' is in the input_table of this db")`
Response: 'There are 115 rows in the input_table where Abdominal pain is present, VAX_TYPE is COVID19, Sex is Female, and Hospital is Yes.'
Third query I was trying to find the patient ID only instead of the count. But I am not able to get the patient ID.
`res=sql_chain("What is the VAERS_ID with 'Abdominal pain', VAX_TYPE='COVID19', SEX= 'F' and HOSPITAL= 'Y' in this db. ")`
But the output generated is same as my second query.
Seems like the counting is working fine but nothing more.
Can anyone help me in displaying table like output from sqlDbchain via langchain and llama2? | Using langchain and LLaMA2 to QA with a large SQL DB | https://api.github.com/repos/langchain-ai/langchain/issues/13977/comments | 2 | 2023-11-28T18:11:46Z | 2024-03-13T19:55:37Z | https://github.com/langchain-ai/langchain/issues/13977 | 2,015,022,272 | 13,977 |
[
"langchain-ai",
"langchain"
] | ### Feature request
NVIDIA TensorRT is an open-source SDK for high-performance deep learning inference, includes a deep learning inference optimizer and runtime that delivers low latency and high throughput for inference applications. I propose that a connector be added to langchain allowing users to use TensorRT with minimal configuration.
### Motivation
There are several implementations of this connector floating around the internet. Lots of folks seem to want this. Rather than have everyone need to add that connector manually it seems to make sense to natively include it in Langchain.
### Your contribution
I am happy to open the PR for this and will do so shortly. | Nvidia TensorRT LLM Connector | https://api.github.com/repos/langchain-ai/langchain/issues/13975/comments | 4 | 2023-11-28T16:24:31Z | 2024-03-27T16:07:47Z | https://github.com/langchain-ai/langchain/issues/13975 | 2,014,825,307 | 13,975 |
[
"langchain-ai",
"langchain"
] | ### Feature request
Currently, the extraction chain only supports the extraction of an Array of object.
For example
```python
from typing import Optional
from langchain.chains import create_extraction_chain_pydantic
from langchain.pydantic_v1 import BaseModel
# Pydantic data class
class Properties(BaseModel):
person_name: str
person_height: int
person_hair_color: str
dog_breed: Optional[str]
dog_name: Optional[str]
# Extraction
chain = create_extraction_chain_pydantic(pydantic_schema=Properties, llm=llm)
# Run
inp = """Alex is 5 feet tall. Claudia is 1 feet taller Alex and jumps higher than him. Claudia is a brunette and Alex is blonde."""
chain.run(inp)
# Results in
#
# [Properties(person_name='Alex', person_height=5, person_hair_color='blonde', dog_breed=None, dog_name=None),
# Properties(person_name='Claudia', person_height=6, person_hair_color='brunette', dog_breed=None, dog_name=None)]
#
````
There is currently no option available to just get one `Properties` object.
It would be nice if you could define at the beginning if you are interested in one object or an array of objects
For example
```` python
chain = create_extraction_chain_pydantic(pydantic_schema=List[Properties], llm=llm) -> Array of Properties
chain = create_extraction_chain_pydantic(pydantic_schema=Properties] llm=llm) -> Just one Propertie
`````
### Motivation
It would just make life easier when you knew that you were only dealing with one object.
It might also improve the response and prevent wrong or incomplete responses.
### Your contribution
I would create and submit a PR that contains this feature. | Singel object extraction | https://api.github.com/repos/langchain-ai/langchain/issues/13971/comments | 2 | 2023-11-28T14:29:08Z | 2024-03-08T16:40:14Z | https://github.com/langchain-ai/langchain/issues/13971 | 2,014,572,602 | 13,971 |
[
"langchain-ai",
"langchain"
] | ### System Info
hi!
im getting this error 👍
`AttributeError Traceback (most recent call last)
File <command-3819272873890469>, line 7
1 # gpt-3.5-turbo-0613
2 # gpt-3.5-turbo-1106
3 # gpt-4
4 # gpt-4-1106-preview
5 llm_model = "gpt-3.5-turbo-1106"
----> 7 llm = ChatOpenAI(
8 temperature=0,
9 model=llm_model
10 )
File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/langchain/load/serializable.py:97, in Serializable.__init__(self, **kwargs)
96 def __init__(self, **kwargs: Any) -> None:
---> 97 super().__init__(**kwargs)
98 self._lc_kwargs = kwargs
File /databricks/python/lib/python3.10/site-packages/pydantic/main.py:339, in pydantic.main.BaseModel.__init__()
File /databricks/python/lib/python3.10/site-packages/pydantic/main.py:1102, in pydantic.main.validate_model()
File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/langchain/chat_models/openai.py:291, in ChatOpenAI.validate_environment(cls, values)
284 values["openai_proxy"] = get_from_dict_or_env(
285 values,
286 "openai_proxy",
287 "OPENAI_PROXY",
288 default="",
289 )
290 try:
--> 291 import openai
293 except ImportError:
294 raise ImportError(
295 "Could not import openai python package. "
296 "Please install it with `pip install openai`."
297 )
File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/openai/__init__.py:11
9 from ._types import NoneType, Transport, ProxiesTypes
10 from ._utils import file_from_path
---> 11 from ._client import (
12 Client,
13 OpenAI,
14 Stream,
15 Timeout,
16 Transport,
17 AsyncClient,
18 AsyncOpenAI,
19 AsyncStream,
20 RequestOptions,
21 )
22 from ._version import __title__, __version__
23 from ._exceptions import (
24 APIError,
25 OpenAIError,
(...)
37 APIResponseValidationError,
38 )
File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/openai/_client.py:12
8 from typing_extensions import override
10 import httpx
---> 12 from . import resources, _exceptions
13 from ._qs import Querystring
14 from ._types import (
15 NOT_GIVEN,
16 Omit,
(...)
21 RequestOptions,
22 )
File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/openai/resources/__init__.py:6
4 from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse
5 from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse
----> 6 from .edits import Edits, AsyncEdits, EditsWithRawResponse, AsyncEditsWithRawResponse
7 from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse
8 from .images import (
9 Images,
10 AsyncImages,
11 ImagesWithRawResponse,
12 AsyncImagesWithRawResponse,
13 )
File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/openai/resources/edits.py:24
19 from .._client import OpenAI, AsyncOpenAI
21 __all__ = ["Edits", "AsyncEdits"]
---> 24 class Edits(SyncAPIResource):
25 with_raw_response: EditsWithRawResponse
27 def __init__(self, client: OpenAI) -> None:
File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/openai/resources/edits.py:31, in Edits()
28 super().__init__(client)
29 self.with_raw_response = EditsWithRawResponse(self)
---> 31 @typing_extensions.deprecated(
32 "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n"
33 )
34 def create(
35 self,
36 *,
37 instruction: str,
38 model: Union[str, Literal["text-davinci-edit-001", "code-davinci-edit-001"]],
39 input: Optional[str] | NotGiven = NOT_GIVEN,
40 n: Optional[int] | NotGiven = NOT_GIVEN,
41 temperature: Optional[float] | NotGiven = NOT_GIVEN,
42 top_p: Optional[float] | NotGiven = NOT_GIVEN,
43 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
44 # The extra values given here take precedence over values defined on the client or passed to this method.
45 extra_headers: Headers | None = None,
46 extra_query: Query | None = None,
47 extra_body: Body | None = None,
48 timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
49 ) -> Edit:
50 """
51 Creates a new edit for the provided input, instruction, and parameters.
52
(...)
81 timeout: Override the client-level default timeout for this request, in seconds
82 """
83 return self._post(
84 "/edits",
85 body=maybe_transform(
(...)
99 cast_to=Edit,
100 )
AttributeError: module 'typing_extensions' has no attribute 'deprecated'`
im using ChatOpenAI with the follwing libs:

and python version is
Python 3.10.12
until some days these worked great. and i didnt touch the code.
so, whats happening here?
thanks
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [X] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
llm_model = "gpt-4-1106-preview"
llm = ChatOpenAI(
temperature=0,
model=llm_model
)
-- using databricks, with langchain and openai
### Expected behavior
just an ok and chatopenai working | AttributeError: module 'typing_extensions' has no attribute 'deprecated' when using ChatOpenAI | https://api.github.com/repos/langchain-ai/langchain/issues/13970/comments | 1 | 2023-11-28T14:15:08Z | 2024-03-13T20:01:42Z | https://github.com/langchain-ai/langchain/issues/13970 | 2,014,540,587 | 13,970 |
[
"langchain-ai",
"langchain"
] | ### System Info
Hi, i'm obtaining this error trace when performing a basic `create_extraction_chain` example.I'm using CTransformers (llama2 type), more specifically, this model here: https://huggingface.co/clibrain/Llama-2-13b-ft-instruct-es-gguf
Python version: 3.11
Environment:
```
accelerate 0.24.1
aiofiles 22.1.0
aiohttp 3.9.0
aiosignal 1.3.1
aiosqlite 0.19.0
alembic 1.9.4
anyio 3.7.1
appnope 0.1.3
argilla 1.19.0
argon2-cffi 23.1.0
argon2-cffi-bindings 21.2.0
arrow 1.3.0
asttokens 2.4.1
async-lru 2.0.4
attrs 23.1.0
Babel 2.13.1
backoff 1.11.1
bcrypt 4.0.1
beautifulsoup4 4.12.2
bleach 6.1.0
Brotli 1.1.0
brotli-asgi 1.2.0
certifi 2023.11.17
cffi 1.16.0
charset-normalizer 3.3.2
click 8.1.7
coloredlogs 15.0.1
comm 0.2.0
commonmark 0.9.1
cryptography 41.0.5
ctransformers 0.2.27
dataclasses-json 0.6.3
datasets 2.15.0
debugpy 1.8.0
decorator 5.1.1
defusedxml 0.7.1
Deprecated 1.2.14
dill 0.3.7
diskcache 5.6.3
ecdsa 0.18.0
elastic-transport 8.10.0
elasticsearch8 8.7.0
executing 2.0.1
fastapi 0.104.1
fastjsonschema 2.19.0
filelock 3.13.1
fqdn 1.5.1
frozenlist 1.4.0
fsspec 2023.10.0
greenlet 3.0.1
h11 0.14.0
httpcore 0.16.3
httptools 0.6.1
httpx 0.23.3
huggingface-hub 0.19.4
humanfriendly 10.0
idna 3.4
ipykernel 6.27.0
ipython 8.17.2
isoduration 20.11.0
jedi 0.19.1
Jinja2 3.1.2
joblib 1.3.2
json5 0.9.14
jsonpatch 1.33
jsonpointer 2.4
jsonschema 4.20.0
jsonschema-specifications 2023.11.1
jupyter_client 8.6.0
jupyter_core 5.5.0
jupyter-events 0.9.0
jupyter-lsp 2.2.0
jupyter_server 2.11.0
jupyter_server_terminals 0.4.4
jupyterlab 4.0.9
jupyterlab-pygments 0.2.2
jupyterlab_server 2.25.2
langchain 0.0.341
langchain-core 0.0.6
langsmith 0.0.67
llama_cpp_python 0.2.20
Mako 1.3.0
markdown-it-py 3.0.0
MarkupSafe 2.1.3
marshmallow 3.20.1
matplotlib-inline 0.1.6
mdurl 0.1.2
mistune 3.0.2
monotonic 1.6
mpmath 1.3.0
multidict 6.0.4
multiprocess 0.70.15
mypy-extensions 1.0.0
nbclient 0.9.0
nbconvert 7.11.0
nbformat 5.9.2
nest-asyncio 1.5.8
networkx 3.2.1
nltk 3.8.1
notebook_shim 0.2.3
numpy 1.23.5
opensearch-py 2.0.1
optimum 1.14.1
overrides 7.4.0
packaging 23.2
pandas 1.5.3
pandocfilters 1.5.0
parso 0.8.3
passlib 1.7.4
pexpect 4.8.0
Pillow 10.1.0
pip 23.3.1
platformdirs 4.0.0
prometheus-client 0.19.0
prompt-toolkit 3.0.41
protobuf 4.25.1
psutil 5.9.6
ptyprocess 0.7.0
pure-eval 0.2.2
py-cpuinfo 9.0.0
pyarrow 14.0.1
pyarrow-hotfix 0.6
pyasn1 0.5.1
pycparser 2.21
pydantic 1.10.13
Pygments 2.17.2
python-dateutil 2.8.2
python-dotenv 1.0.0
python-jose 3.3.0
python-json-logger 2.0.7
python-multipart 0.0.6
pytz 2023.3.post1
PyYAML 6.0.1
pyzmq 25.1.1
referencing 0.31.0
regex 2023.10.3
requests 2.31.0
rfc3339-validator 0.1.4
rfc3986 1.5.0
rfc3986-validator 0.1.1
rich 13.0.1
rpds-py 0.13.1
rsa 4.9
safetensors 0.4.0
scikit-learn 1.3.2
scipy 1.11.4
segment-analytics-python 2.2.0
Send2Trash 1.8.2
sentence-transformers 2.2.2
sentencepiece 0.1.99
setuptools 68.2.2
six 1.16.0
smart-open 6.4.0
sniffio 1.3.0
soupsieve 2.5
SQLAlchemy 2.0.23
stack-data 0.6.3
starlette 0.27.0
sympy 1.12
tenacity 8.2.3
terminado 0.18.0
threadpoolctl 3.2.0
tinycss2 1.2.1
tokenizers 0.15.0
torch 2.1.1
torchvision 0.16.1
tornado 6.3.3
tqdm 4.66.1
traitlets 5.13.0
transformers 4.35.2
typer 0.9.0
types-python-dateutil 2.8.19.14
typing_extensions 4.8.0
typing-inspect 0.9.0
uri-template 1.3.0
urllib3 1.26.18
uvicorn 0.20.0
uvloop 0.19.0
watchfiles 0.21.0
wcwidth 0.2.12
webcolors 1.13
webencodings 0.5.1
websocket-client 1.6.4
websockets 12.0
wrapt 1.14.1
xxhash 3.4.1
yarl 1.9.3
```
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [X] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Hi, i'm obtaining this error trace when performing a basic `create_extraction_chain` example.I'm using CTransformers (llama2 type), more specifically, this model here: https://huggingface.co/clibrain/Llama-2-13b-ft-instruct-es-gguf
```
OutputParserException Traceback (most recent call last)
Cell In[9], line 17
12 chain = create_extraction_chain(schema, llm)
14 inp = """Alex is 5 feet tall. Claudia is 1 feet taller Alex and jumps higher than him. Claudia is a brunette and Alex is blonde.
15 Willow is a German Shepherd that likes to play with other dogs and can always be found playing with Milo, a border collie that lives close by."""
---> 17 chain.run(inp)
File ~/Desktop/green-jobs/genv/lib/python3.11/site-packages/langchain/chains/base.py:507, in Chain.run(self, callbacks, tags, metadata, *args, **kwargs)
505 if len(args) != 1:
506 raise ValueError("`run` supports only one positional argument.")
--> 507 return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[
508 _output_key
509 ]
511 if kwargs and not args:
512 return self(kwargs, callbacks=callbacks, tags=tags, metadata=metadata)[
513 _output_key
514 ]
File ~/Desktop/green-jobs/genv/lib/python3.11/site-packages/langchain/chains/base.py:312, in Chain.__call__(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)
310 except BaseException as e:
311 run_manager.on_chain_error(e)
--> 312 raise e
313 run_manager.on_chain_end(outputs)
314 final_outputs: Dict[str, Any] = self.prep_outputs(
315 inputs, outputs, return_only_outputs
316 )
File ~/Desktop/green-jobs/genv/lib/python3.11/site-packages/langchain/chains/base.py:306, in Chain.__call__(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)
299 run_manager = callback_manager.on_chain_start(
300 dumpd(self),
301 inputs,
302 name=run_name,
303 )
304 try:
305 outputs = (
--> 306 self._call(inputs, run_manager=run_manager)
307 if new_arg_supported
308 else self._call(inputs)
309 )
310 except BaseException as e:
311 run_manager.on_chain_error(e)
File ~/Desktop/green-jobs/genv/lib/python3.11/site-packages/langchain/chains/llm.py:104, 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 ~/Desktop/green-jobs/genv/lib/python3.11/site-packages/langchain/chains/llm.py:258, in LLMChain.create_outputs(self, llm_result)
256 def create_outputs(self, llm_result: LLMResult) -> List[Dict[str, Any]]:
257 """Create outputs from response."""
--> 258 result = [
259 # Get the text of the top generated string.
260 {
261 self.output_key: self.output_parser.parse_result(generation),
262 "full_generation": generation,
263 }
264 for generation in llm_result.generations
265 ]
266 if self.return_final_only:
267 result = [{self.output_key: r[self.output_key]} for r in result]
File ~/Desktop/green-jobs/genv/lib/python3.11/site-packages/langchain/chains/llm.py:261, in <listcomp>(.0)
256 def create_outputs(self, llm_result: LLMResult) -> List[Dict[str, Any]]:
257 """Create outputs from response."""
258 result = [
259 # Get the text of the top generated string.
260 {
--> 261 self.output_key: self.output_parser.parse_result(generation),
262 "full_generation": generation,
263 }
264 for generation in llm_result.generations
265 ]
266 if self.return_final_only:
267 result = [{self.output_key: r[self.output_key]} for r in result]
File ~/Desktop/green-jobs/genv/lib/python3.11/site-packages/langchain/output_parsers/openai_functions.py:130, in JsonKeyOutputFunctionsParser.parse_result(self, result, partial)
129 def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:
--> 130 res = super().parse_result(result, partial=partial)
131 if partial and res is None:
132 return None
File ~/Desktop/green-jobs/genv/lib/python3.11/site-packages/langchain/output_parsers/openai_functions.py:68, in JsonOutputFunctionsParser.parse_result(self, result, partial)
66 generation = result[0]
67 if not isinstance(generation, ChatGeneration):
---> 68 raise OutputParserException(
69 "This output parser can only be used with a chat generation."
70 )
71 message = generation.message
72 try:
OutputParserException: This output parser can only be used with a chat generation.
```
Im using the following example:
```
schema = {
"properties": {
"person_name": {"type": "string"},
"person_height": {"type": "integer"},
"person_hair_color": {"type": "string"},
"dog_name": {"type": "string"},
"dog_breed": {"type": "string"},
},
"required": [],
}
chain = create_extraction_chain(schema, llm)
inp = """Alex is 5 feet tall. Claudia is 1 feet taller Alex and jumps higher than him. Claudia is a brunette and Alex is blonde.
Willow is a German Shepherd that likes to play with other dogs and can always be found playing with Milo, a border collie that lives close by."""
chain.run(inp)
```
### Expected behavior
I expect not to get an error when executing the code | OutputParserException in extraction use case | https://api.github.com/repos/langchain-ai/langchain/issues/13969/comments | 3 | 2023-11-28T14:13:25Z | 2024-03-08T16:47:51Z | https://github.com/langchain-ai/langchain/issues/13969 | 2,014,537,056 | 13,969 |
[
"langchain-ai",
"langchain"
] | ### System Info
**python:** 3.11.6
**langchain:** 0.0.335
**openai:** 0.28.1
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [X] Agents / Agent Executors
- [X] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
I tried to create custom tools for Agent type ZERO_SHOT_REACT_DESCRIPTION but after executing the first chain, it keeps getting error Caused by NewConnectionError on the next chain. The tools work fine because I tested them with Agent type OPENAI.FUNTIONS
My first tool
```
def get_thing(u: str) -> str:
c, l = get_thing_ori(u, True)
r = c + '\n' + l
return r
class GetThingCheckInput(BaseModel):
u: str = Field(..., description='thing to get')
def get_thing_tool():
GetThingTool = StructuredTool.from_function(
name="get_thing",
description="Useful to get thing",
func=get_thing,
args_schema=GetThingCheckInput
)
return GetThingTool
```
My second tool
```
def get_S(t: str, l=str, c=str) -> str:
u_s, d_s = get_so()
result = ''
for u, d in zip(u_s, d_s):
result += f'U: {u}\nD: {d}\n\n'
return result
def parsing_get_S(string: str):
t, l, c = string.split(', ')
return (get_S(t, l, c))
class ParsingGetSCheckInput(BaseModel):
string: str = Field(..., description='A string contain a data in format: "T, L, C"')
def get_parsing_get_S_tool():
ParsingGetSTool = StructuredTool.from_function(
name = 'parsing_get_S',
description="Useful to get S. Input is a comma-seperated list contain data in format: 'T, L, C'",
func=parsing_get_S,
args_schema=ParsingGetSCheckInput
)
return ParsingGetSTool
```
This is my main
```
if __name__ == '__main__':
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0, max_retries=5, timeout=100)
GetThingTool = get_thing_tool()
ParsingGetSTool = get_parsing_get_S_tool()
tools = [GetThingTool, ParsingGetSTool]
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
```
I try to add both `os.environ["LANGCHAIN_TRACING"] = "true"` and `os.environ["LANGCHAIN_TRACING"] = "true"` but it not working.
Full error is:
```
ERROR:root:download error: 'https://www.dailymail.co.uk/tvshowbiz/article-12792715/Leonardo-DiCaprio-low-key-glamorous-girlfriend-Vittoria-Ceretti-family-London.html' HTTPConnectionPool(host="'https", port=80): Max retries exceeded with url: //[www.dailymail.co.uk/tvshowbiz/article-12792715/Leonardo-DiCaprio-low-key-glamorous-girlfriend-Vittoria-Ceretti-family-London.html](https://file+.vscode-resource.vscode-cdn.net/d%3A/Python%20Project/www.dailymail.co.uk/tvshowbiz/article-12792715/Leonardo-DiCaprio-low-key-glamorous-girlfriend-Vittoria-Ceretti-family-London.html)' (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000018BEA481B90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
```
### Expected behavior
As I use Agent type OPENAI.FUNTIONS, it completely returns a full answer, so that means there is nothing wrong with the tools, i guess. It should work for agent type ZERO_SHOT_REACT_DESCRIPTION. The reason I use zero shot is because the thinking part works better in different languages than agent-type OPENAI.FUNTIONS. | Caused by NewConnectionError when using ZERO_SHOT_REACT_DESCRIPTION | https://api.github.com/repos/langchain-ai/langchain/issues/13968/comments | 2 | 2023-11-28T13:57:21Z | 2023-11-30T11:03:08Z | https://github.com/langchain-ai/langchain/issues/13968 | 2,014,504,640 | 13,968 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
Hello Team,
We are finding a way to pass the context, previous question and answer to **create_pandas_dataframe_agent**. Can u please help me understand how i can pass the context(previous question and answer) to the **create_pandas_dataframe_agent**. it will be helpful if you have any such example implementation
Thanks,
Akash
### Suggestion:
_No response_ | Issue: Passing context(previous question and answer) to the create_pandas_dataframe_agent function. | https://api.github.com/repos/langchain-ai/langchain/issues/13967/comments | 16 | 2023-11-28T13:30:17Z | 2024-03-18T16:06:56Z | https://github.com/langchain-ai/langchain/issues/13967 | 2,014,447,411 | 13,967 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
**Summary:**
The FAISS similarity search in LangChain is encountering difficulties when processing alpha-numeric queries that involve numeric integers. While the search performs well for queries like "What are resolutions to problems related to SAF," it exhibits suboptimal behavior when processing queries such as "Give me complete details of L2-resolution against ORA-14300," which involve alpha-numeric combinations.
Note that we have already successfully embedded and indexed the above documents that includes alpha numeric key as well
such as "ORA-14300".
**Expected Behavior:**
The FAISS similarity search should accurately and effectively retrieve relevant information for alpha-numeric queries, providing precise results even when numeric integers are included in the query.
**Current Behavior:**
The search is not functioning correctly when processing alpha-numeric queries with numeric integers. It fails to accurately identify and retrieve relevant documents, leading to a suboptimal user experience.


**Steps to Reproduce:**
Index CSV data containing both text and numerical values, and subsequently execute a query that includes an alphanumeric question.
**Additional Information:**
Environment: Langchain version (0.0.284)
**Impact:**
This issue affects the accuracy and reliability of the FAISS similarity search, particularly when handling alpha-numeric queries that include numeric integers. Users relying on LangChain for information retrieval may experience challenges when seeking relevant documents related to such queries.
**Priority:**
High
Are FAISS and Redis similarity searches capable of providing such high similarity search over the index? If not, please guide me on where I should turn to achieve better and more accurate results
Thank you for your attention to this matter. Feel free to request additional information if needed.
### Suggestion:
_No response_ | Why does FAISS similarity search not fetch data with respect to alphanumeric keys like ORA-14300? | https://api.github.com/repos/langchain-ai/langchain/issues/13964/comments | 1 | 2023-11-28T12:50:29Z | 2024-03-13T20:03:49Z | https://github.com/langchain-ai/langchain/issues/13964 | 2,014,369,520 | 13,964 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I create my vector db using the following code:
```
db = Chroma.from_documents(
chunked_documents,
embeddings,
persist_directory=db_path + '/' + db_type,
client_settings=chroma_settings,)
```
`chunked_documents` is a list of elements of type Document.
I have added metadata which is a simple numerical id: `{'id': 1}`
```
embeddings = HuggingFaceInstructEmbeddings(
model_name=args.embedding_model,
model_kwargs={"device": args.device},
)
```
```
CHROMA_SETTINGS = Settings(
anonymized_telemetry=False,
is_persistent=True,
)
```
What happens is that I run `db.similarity_search(query, k=3)` and for part of the answers, the metadata dict is empty. Has anyone encountered such an issue?
Just to point out, when I create the db using the `from_texts()` method where I add raw texts and metadata separately I do not encounter the issue and when running `db.similarity_search()` the returned answer, contains the respective metadata.
### Suggestion:
_No response_ | Issue: Chroma.from_documents does not save metadata properly | https://api.github.com/repos/langchain-ai/langchain/issues/13963/comments | 5 | 2023-11-28T12:16:56Z | 2024-05-02T16:04:54Z | https://github.com/langchain-ai/langchain/issues/13963 | 2,014,310,258 | 13,963 |
[
"langchain-ai",
"langchain"
] | ### System Info
I am using the SelfQueryRetriever class to make questions about a set of documents. It seems that there is an issue with the use of the `enable_limit` argument
Versions:
Langchain Version: 0.0.340
openai 1.3.5
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [X] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [X] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
enable_limit = False:
```python
retriever = SelfQueryRetriever.from_llm(
llm,
vectorstore,
document_content_description,
metadata_field_info,
enable_limit=False
)
query = "I want indentify thousand repairs with xxxx"
result = retriever.invoke(query)
len(result)
#Result: 4
```
If change enable_limit = True:
```python
retriever = SelfQueryRetriever.from_llm(
llm,
vectorstore,
document_content_description,
metadata_field_info,
enable_limit=True
)
query = "I want indentify thousand repairs with xxxx"
result = retriever.invoke(query)
len(result)
#Result: 1000
```
If enable_limit=True and change in query for "All":
```python
retriever = SelfQueryRetriever.from_llm(
llm,
vectorstore,
document_content_description,
metadata_field_info,
enable_limit=True
)
query = "I want indentify All repairs with xxxx"
result = retriever.invoke(query)
len(result)
#Result: 4
```
### Expected behavior
The expected behaviour with "enable_limit = False" was to show more than 1000 documents.
As there is no defined limit, all documents were expected as a result. | Enable Limit False in Self Query Retriever doesn't have the expected behavior | https://api.github.com/repos/langchain-ai/langchain/issues/13961/comments | 1 | 2023-11-28T11:50:02Z | 2024-03-13T20:01:17Z | https://github.com/langchain-ai/langchain/issues/13961 | 2,014,263,985 | 13,961 |
[
"langchain-ai",
"langchain"
] | ### System Info
Current LangChain master commit:
https://github.com/langchain-ai/langchain/commits/391f200
### Who can help?
@hwchase17 @baskaryan
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Just run
```
from langchain.chat_models import BedrockChat
```
Stacktrace:
```
tests/e2e-tests/test_compatibility_matrix.py:10: in <module>
from langchain.chat_models import ChatOpenAI, AzureChatOpenAI, ChatVertexAI, BedrockChat
/tmp/venv/lib/python3.11/site-packages/langchain/chat_models/__init__.py:20: in <module>
from langchain.chat_models.anthropic import ChatAnthropic
/tmp/venv/lib/python3.11/site-packages/langchain/chat_models/anthropic.py:18: in <module>
from langchain.chat_models.base import (
/tmp/venv/lib/python3.11/site-packages/langchain/chat_models/base.py:1: in <module>
from langchain_core.language_models.chat_models import (
E ImportError: cannot import name 'agenerate_from_stream' from 'langchain_core.language_models.chat_models' (/tmp/venv/lib/python3.11/site-packages/langchain_core/language_models/chat_models.py)
```
### Expected behavior
To being able to import the required modules | ImportError: cannot import name 'agenerate_from_stream' from 'langchain_core.language_models.chat_models' | https://api.github.com/repos/langchain-ai/langchain/issues/13958/comments | 5 | 2023-11-28T09:40:11Z | 2023-11-29T13:33:23Z | https://github.com/langchain-ai/langchain/issues/13958 | 2,014,030,020 | 13,958 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I'm currently working on a project and have encountered an issue with the deletion functionality for Confluence
Spaces. I've implemented a function delete_embeddings that is supposed to delete embeddings based on the Confluence space key, but it doesn't seem to be working as expected.
Here's the relevant code snippet:
def delete_embeddings(file_path, persist_directory):
chroma_db = chromadb.PersistentClient(path=persist_directory)
collection = chroma_db.get_or_create_collection(name="langchain")
ids = collection.get(where={"source": file_path})['ids']
collection.delete(where={"source": file_path},ids=ids)
# chroma_db.delete_collection(name="langchain")
print("delete successfully")
And I'm calling this function as follows:
delete_embeddings(names, persist_directory)
I want to delete embeddings of Confluence Spaces when user request deletion confluence space.
### Suggestion:
_No response_ | Issue: Question about Deletion of Embeddings for Confluence Spaces | https://api.github.com/repos/langchain-ai/langchain/issues/13956/comments | 5 | 2023-11-28T08:26:59Z | 2024-03-13T19:58:26Z | https://github.com/langchain-ai/langchain/issues/13956 | 2,013,904,967 | 13,956 |
[
"langchain-ai",
"langchain"
] | ### Feature request
PGVector in Langchain does not support advance metadata filtering such as "OR" clause.
For now, there is no way to perform filters such as:
```
{
"$or": [
{"uploaded_by": {"$eq": "USER1"}},
{"org": {"$eq": "ORG"}},
]
}
```
### Motivation
Our team is unable to use langchain with PGVector due to its lack of support for "OR" filter.
Having advanced metadata filtering like that in Pinecone/Qdrant would really help
https://docs.pinecone.io/docs/metadata-filtering
### Your contribution
For now, I see existing PR: https://github.com/langchain-ai/langchain/pull/12977
This could possibly solve the issue. | Advance metadata filtering for PGVector | https://api.github.com/repos/langchain-ai/langchain/issues/13955/comments | 4 | 2023-11-28T08:15:46Z | 2024-07-04T16:07:13Z | https://github.com/langchain-ai/langchain/issues/13955 | 2,013,887,941 | 13,955 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
I'm currently working on a project and have encountered an issue with the deletion functionality for Confluence Spaces. I've implemented a function `delete_embeddings` that is supposed to delete embeddings based on the Confluence space key, but it doesn't seem to be working as expected.
Here's the relevant code snippet:
```python
def delete_embeddings(file_path, persist_directory):
chroma_db = chromadb.PersistentClient(path=persist_directory)
collection = chroma_db.get_or_create_collection(name="langchain")
ids = collection.get(where={"source": file_path})['ids']
collection.delete(where={"source": file_path},ids=ids)
# chroma_db.delete_collection(name="langchain")
print("delete successfully")
And I'm calling this function as follows:
delete_embeddings(names, persist_directory)
### Suggestion:
_No response_ | Issue: Question about Deletion Functionality for Confluence Spaces | https://api.github.com/repos/langchain-ai/langchain/issues/13954/comments | 2 | 2023-11-28T06:57:30Z | 2024-03-13T20:01:58Z | https://github.com/langchain-ai/langchain/issues/13954 | 2,013,781,829 | 13,954 |
[
"langchain-ai",
"langchain"
] | ### Issue with current documentation:
I was hoping to use the Dropbox document loader for a large number of pdf and some docx documents, however I am not sure whether this loader supports these file types. I followed the instructions on https://python.langchain.com/docs/integrations/document_loaders/dropbox and installed the "unstructured[all-docs]" package but I keep getting the message that the loader skips these files.
> xxx.docx could not be decoded as text. Skipping.
> yyy.pdf could not be decoded as text. Skipping.
Does this loader only support .txt files? Is there an alternative? I see the Unstructured loader only works for individual files, is that the best alternative?
Many thanks!
### Idea or request for content:
File formats the loader supports needs to be clarified
unstructured package was given as a prerequisite for pdf files but I was getting missing package/method errors until I installed the "unstructured[all-docs]" package and still not able to load pdf files | DOC: Dropbox document loader functionality | https://api.github.com/repos/langchain-ai/langchain/issues/13952/comments | 7 | 2023-11-28T06:18:48Z | 2023-12-03T22:19:38Z | https://github.com/langchain-ai/langchain/issues/13952 | 2,013,737,662 | 13,952 |
[
"langchain-ai",
"langchain"
] | ### System Info
To train data in Pinecone, I used the function.
_pinecone = Pinecone.from_documents(docs, self.embeddings, index_name=self.index_name)
all the parameters have values always:


But, this error occurs often like this:

@hwchase17 , I am looking forward to fixing this issue asap. Thank you.
### Who can help?
_No response_
### Information
- [ ] The official example notebooks/scripts
- [X] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [X] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
class PineConeIndexer:
def __init__(self):
self.embeddings = OpenAIEmbeddings()
# initialize pinecone
pinecone.init(
api_key=os.environ.get('PINECONE_API_KEY'),
environment=os.environ.get('PINECONE_ENV')
)
self.index_name = os.environ.get('PINECONE_INDEX_NAME')
def upsert_index_from_task(self, task):
try:
# get doc
....
_pinecone = Pinecone.from_documents(docs, self.embeddings, index_name=self.index_name)
return {"success": True, "error": None}
except Exception as e:
return {"success": False, "error": str(e)}
### Expected behavior
sometimes, this error occurs:
PineconeProtocolError
Failed to connect; did you specify the correct index name?
ProtocolError
('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))
| PineconeProtocolError: Failed to connect; did you specify the correct index name? | https://api.github.com/repos/langchain-ai/langchain/issues/13951/comments | 3 | 2023-11-28T05:49:35Z | 2024-06-08T16:07:35Z | https://github.com/langchain-ai/langchain/issues/13951 | 2,013,694,385 | 13,951 |
[
"langchain-ai",
"langchain"
] | ### Issue with current documentation:
this is intput token (import pandas as pd
import json
from IPython.display import Markdown, display
from langchain.agents import create_csv_agent
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI
import os
os.environ["OPENAI_API_KEY"] = ""
# Load the dataset
df = pd.read_csv('Loan Collections - Sheet1.csv')
# Function to convert date and time columns to float
def convert_date_time_columns_to_float(df):
for column in df.select_dtypes(include=['object']).columns:
# Check if the column name contains 'date' or 'time'
if 'date' in column.lower() or 'time' in column.lower():
try:
# Convert the column to datetime
df[column] = pd.to_datetime(df[column], errors='coerce')
# Convert datetime to numerical representation (e.g., days since a reference date)
reference_date = pd.to_datetime('1900-01-01')
df[column] = (df[column] - reference_date).dt.total_seconds() / (24 * 60 * 60)
except ValueError:
# Handle errors during conversion
print(f"Error converting column '{column}' to float.")
# Convert 'date' and 'time' columns to float
convert_date_time_columns_to_float(df)
# Extract unique values for each column
unique_values_per_column = {}
for column in df.select_dtypes(include=['object']).columns:
unique_values_per_column[column] = df[column].unique().tolist()
# Convert the dictionary to JSON
json_data_train = json.dumps(unique_values_per_column, indent=4)
testData_fname = "Sample Retail Stores Data.csv"
# Load the dataset
df2 = pd.read_csv(testData_fname)
convert_date_time_columns_to_float(df2)
# Extract unique values for each column
unique_values_per_column = {}
for column in df2.select_dtypes(include=['object']).columns:
unique_values_per_column[column] = df2[column].unique().tolist()
# Convert the dictionary to JSON
json_data_test = json.dumps(unique_values_per_column, indent=4)
# Define user's question
user_question = "Percentage share of State by Value?"
# Define the prompt template
prompt_template = f'''If the dataset has the following columns: {json_data_train}'''+''' Understand user questions with different column names and convert them to a JSON format.
Question might not even mentioned column name at all, it would probably mention value of the column. so it has to figure it out columnn name based on that value.
Example1:
User Question1: top zone in the year 2019 with Loan Amt between 10k and 20k and tenure > 12 excluding Texas region?
{
"start_date": "01-01-2019",
"end_date": "31-12-2019",
"time_stamp_col": "Due Date",
"agg_columns": [],
"trend": "null",
"to_start_date": "null",
"to_end_date": "null",
"growth": "null",
"variables_grpby": ["Zone"],
"filters": {},
"not_in": {"Region": ["Texas"]},
"num_filter": {
"gt": [
["Loan Tenure", 12],
["Loan Amount", 10000]
],
"lt": [
["Loan Amount", 20000]
]
},
"percent": "false",
"top": "1",
"bottom": "null"
}
Note the following in the above example
- The word "top" in the User Question made the "top" key have the value as "1". If "highest" is mentioned in the User Question, even then "top" would have the value as "1". If "top" is not mentioned or not implied in the User Question, then it takes on the value "null". Similarly for "bottom" key in the System Response.
- The word "zone" in the User Question refers to a column "Zone" in the dataset and since it is a non-numeric column and we have to group by that column, the system response has it as one of the values of the list of the key "variables_grpby"
- The key "start_date" and "end_date" Since it is mentioned 2019 in the User Question as the timeframe, the "start_date" assumes the beginning of the year 2019 and "end_date" assumes the end of the year 2019. If no date related words are mentioned in the question, "start_date" would be "null" and "end_date" would be "null".
- The key "time_stamp_col" in the System Response should mention the relevant time related column name from the dataset according to the question if the question mentions a time related word.
- The key "agg_columns" in the System Response is a list of columns to be aggregated which should mention the numeric column names on which the question wants us to aggregate on.
- The key "trend" in the System Response, "trend" is set to "null" since the user question doesn't imply any trend analysis . If the question were about trends over time, this key would contain information about the trend, such as "upward," "downward," or "null" if no trend is specified.
- The key "filters" An empty dictionary in this case, as there are no explicit filters mentioned in the user question. If the user asked to filter data based on certain conditions (e.g. excluding a specific region), this key would contain the relevant filters.
- The key "to_start_date" and "to_end_date" Both set to "null" in this example because the user question specifies a single timeframe (2019). If the question mentioned a range (e.g. "from January 2019 to March 2019"), these keys would capture the specified range.
- The key "growth" Set to "null" in this example as there is no mention of growth in the user question. If the user inquired about growth or change over time, this key would provide information about the type of growth (e.g."monthly","yearly"," "absolute") or be set to "null" if not applicable.
- The key "not_in" Contains information about exclusion criteria based on the user's question. In this example, it excludes the "Texas" region. If the user question doesn't involve exclusions, this key would be an empty dictionary.
- The key "num_filter" Specifies numerical filters based on conditions in the user question. In this example, it filters loans with a tenure greater than 12 and loan amounts between 10k and 20k. If the user question doesn't involve numerical filters, this key would be an empty dictionary.
- The key "percent" Set to "false" in this example as there is no mention of percentage in the user question. If the user inquired about percentages, this key would contain information about the use of percentages in the response.
Similarly, below are more examples of user questions and their corresponding expected System Responses.
Example 2:
User Question: What is the Highest Loan Amount and Loan Outstanding by RM Name James in January 2020
{
"start_date": "01-01-2020",
"end_date": "31-01-2020",
"time_stamp_col": "Due Date",
"agg_columns": ["Loan Amount", "Loan Outstanding"],
"trend": "null",
"to_start_date": "null",
"to_end_date": "null",
"growth": "null",
"variables_grpby": [],
"filters": {"RM Name": ["James"]},
"not_in": {},
"num_filter": {},
"percent": "false",
"top": "1",
"bottom": "null"
}
Example 3:
User Question: Which RM Name with respect to Region has the Highest Interest Outstanding and Principal Outstanding in the year 2019
{
"start_date": "01-01-2019",
"end_date": "31-12-2019",
"time_stamp_col": "Due Date",
"agg_columns": ["Interest Outstanding", "Principal Outstanding"],
"trend": "null",
"to_start_date": "null",
"to_end_date": "null",
"growth": "null",
"variables_grpby": ["RM Name", "Region"],
"filters": {},
"not_in": {},
"num_filter": {},
"percent": "false",
"top": "1",
"bottom": "null"
}
Example 4:
User Question: Which Branch in North Carolina with respect to Cibil Score Bucket has the Highest Cibil Score in 2019
{
"start_date": "01-01-2019",
"end_date": "31-12-2019",
"time_stamp_col": "Due Date",
"agg_columns": ["Cibil Score", "DPD Bucket"],
"trend": "null",
"to_start_date": "null",
"to_end_date": "null",
"growth": "null",
"variables_grpby": ["Branch"],
"filters": {"Region": ["North Carolina"]},
"not_in": {},
"num_filter": {},
"percent": "false",
"top": "1",
"bottom": "null"
}
''
Example 5:
User Question: With respect to Zone, Region, Branch, RM Name what is the Highest Loan Amount, Loan Tenure, Loan Outstanding, EMI Pending, Principal Outstanding
{
"start_date": "null",
"end_date": "null",
"time_stamp_col": "null",
"agg_columns": ["Loan Amount", "Loan Tenure", "Loan Outstanding", "EMI Pending", "Principal Outstanding"],
"trend": "null",
"to_start_date": "null",
"to_end_date": "null",
"growth": "null",
"variables_grpby": ["Zone", "Region", "Branch", "RM Name"],
"filters": {},
"not_in": {},
"num_filter": {},
"percent": "false",
"top": "1",
"bottom": "null"
}
Example 6:
User Question: Top 2 zones by Housing Loan in the year 2019
{
"start_date": "01-01-2019",
"end_date": "31-12-2019",
"time_stamp_col": "Due Date",
"agg_columns": ["Housing Loan"],
"trend": "null",
"to_start_date": "null",
"to_end_date": "null",
"growth": "null",
"variables_grpby": ["Zone"],
"filters": {"Product": ["Home Loan"]},
"not_in": {},
"num_filter": {},
"percent": "false",
"top": "2",
"bottom": "null"
}
'''+ f'''Our test dataset has the following columns: {json_data_test}
User Question (to be converted): {user_question}'''
# Load the agent
agent = create_csv_agent(OpenAI(temperature=0), testData_fname, verbose=True)
gpt4_agent = create_csv_agent(ChatOpenAI(temperature=0, model_name="gpt-4-1106-preview"), testData_fname)
# Use the formatted question as the input to your agent
response = gpt4_agent.run(prompt_template)
# Print the response
print(user_question)
print(response)) and this is output token ( Percentage share of State by Value?
{
"start_date": "null",
"end_date": "null",
"time_stamp_col": "null",
"agg_columns": ["Value"],
"trend": "null",
"to_start_date": "null",
"to_end_date": "null",
"growth": "null",
"variables_grpby": ["State"],
"filters": {},
"not_in": {},
"num_filter": {},
"percent": "true",
"top": "null",
"bottom": "null"
})
### Idea or request for content:
_No response_ | can you tell me how to calculate what will be cost for this input tokens in prompt and output tokens in prompt | https://api.github.com/repos/langchain-ai/langchain/issues/13947/comments | 1 | 2023-11-28T04:42:02Z | 2024-03-13T20:00:27Z | https://github.com/langchain-ai/langchain/issues/13947 | 2,013,606,586 | 13,947 |
[
"langchain-ai",
"langchain"
] | ### System Info
machine: mackbook pro Sonoma 14.1.1
package:
python = "3.10.13"
openai = "^0.28.1"
pandas = "^2.1.1"
ipython = "^8.16.0"
langchain = "^0.0.306"
python-dotenv = "^1.0.0"
seaborn = "^0.13.0"
tqdm = "^4.66.1"
torch = "^2.1.0"
transformers = "^4.35.2"
accelerate = "^0.24.1"
sentencepiece = "^0.1.99"
openllm = "^0.4.27"
### Who can help?
_No response_
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
follow the instruction https://python.langchain.com/docs/integrations/llms/openllm
1)openllm start dolly-v2
2)
from langchain.llms import OpenLLM
server_url = "http://localhost:3000" # Replace with remote host if you are running on a remote server
llm = OpenLLM(server_url=server_url)
llm("what is the meaning of life")
error:
line 229 /langchain/llms/openllm.py 220
AtrributionError: "HttpClient" object has not attribute 'configuration'
### Expected behavior
return a response from LLM | 'HTTPClient' object has no attribute 'configuration' | https://api.github.com/repos/langchain-ai/langchain/issues/13943/comments | 3 | 2023-11-28T03:28:12Z | 2024-03-13T20:01:59Z | https://github.com/langchain-ai/langchain/issues/13943 | 2,013,546,758 | 13,943 |
[
"langchain-ai",
"langchain"
] | ### System Info
langchain 0.0.340
### Who can help?
@hwchase17 @agola11
### Information
- [ ] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [X] LLMs/Chat Models
- [X] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
After openai v1 sdk the previous method openai.proxy = {xxx} is no longer supported. But langchain is still using it.
It seems openai v1 sdk only support to set proxy on client level. see this issue on open ai sdk repo https://github.com/openai/openai-python/issues/825#issuecomment-1826047567
### Expected behavior
Should implement the way openai sdk required to set proxy | To support open v1 SDK proxy setting | https://api.github.com/repos/langchain-ai/langchain/issues/13939/comments | 1 | 2023-11-28T02:12:10Z | 2024-03-13T20:00:20Z | https://github.com/langchain-ai/langchain/issues/13939 | 2,013,460,359 | 13,939 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
It seems like that the agent can only take one variable "input".
I would like to create an agent with a custom prompt template that takes multiple variables whenever a user types something. like agent_executor.invoke({"input": "what is my name", "example":example, "user_profile":user_profile})
the custom prompt template looks like """
user input: {input}
example: {example}
user_profile : {user_profile}
### Suggestion:
_No response_ | Issue: create agent takes multiple variables | https://api.github.com/repos/langchain-ai/langchain/issues/13937/comments | 2 | 2023-11-28T01:27:57Z | 2024-03-13T20:00:24Z | https://github.com/langchain-ai/langchain/issues/13937 | 2,013,425,511 | 13,937 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
trying building devcontainer following steps in doc ~/langchain/.devcontainer/README.md, but stuck at step10/11
<img width="876" alt="Screen Shot 2023-11-27 at 7 56 30 PM" src="https://github.com/langchain-ai/langchain/assets/97558871/3b8c803c-bdce-410d-8b7a-19fb0d1bc692">
### Suggestion:
_No response_ | devcontainer fail to built | https://api.github.com/repos/langchain-ai/langchain/issues/13936/comments | 3 | 2023-11-28T00:57:23Z | 2023-11-29T04:10:15Z | https://github.com/langchain-ai/langchain/issues/13936 | 2,013,395,749 | 13,936 |
[
"langchain-ai",
"langchain"
] | ### Issue you'd like to raise.
When utilizing the create_sql_agent module by LangChain to interact with a SQL database and generate SQL queries from natural language, I've encountered an issue with the responses. Currently, when I execute queries, the SQL Agent responds with placeholder information, citing security reasons for omitting the actual data. However, for my use case, it is crucial to receive the real information retrieved from the SQL database tables.
Also, it limits the information as well even with `top_k=50`. The database return 50 records but in the output it only shows 10-12 with the following output: Please note that this is a partial list. There are more ...
langchain == 0.0.313
langchain-experimental == 0.0.32
```
dbmssql = SQLDatabase.from_uri(
connection_url,
include_tables=[
"table_1",
"table_2",
"table_3",
"table_4",
],
view_support=False
)
chat_llm = ChatOpenAI(
model="gpt-4",
temperature=0,
verbose=True,
openai_api_key=openai_api_key,
request_timeout=600
)
def create_mssql_db_agent(dbmssql):
few_shot_docs = [
Document(page_content=question, metadata={
"sql_query": few_shots[question]})
for question in few_shots.keys()
]
vector_db = FAISS.from_documents(few_shot_docs, embeddings)
retriever = vector_db.as_retriever()
tool_description = """
This tool will help you understand similar examples to adapt them to the user question.
Input to this tool should be the user question.
"""
retriever_tool = create_retriever_tool(
retriever, name="sql_get_similar_examples", description=tool_description
)
custom_tool_list = [retriever_tool]
custom_suffix = """
I should first get the similar examples I know.
If the examples are enough to construct the query, I can build it.
Otherwise, I can then look at the tables in the database to see what I can query.
Then I should query the schema of the most relevant tables
"""
agent = create_sql_agent(
agent_executor_kwargs={"return_intermediate_steps": True},
llm=chat_llm,
toolkit=SQLDatabaseToolkit(db=dbmssql, llm=chat_llm),
verbose=True,
agent_type=AgentType.OPENAI_FUNCTIONS,
extra_tools=custom_tool_list,
suffix=custom_suffix,
top_k=50,
# return_intermediate_steps=True
)
return agent
```
### Suggestion:
_No response_ | Issue: create_sql_agent omits and limits actual information retrieved from SQL tables | https://api.github.com/repos/langchain-ai/langchain/issues/13931/comments | 4 | 2023-11-27T22:16:47Z | 2024-04-06T01:22:57Z | https://github.com/langchain-ai/langchain/issues/13931 | 2,013,215,135 | 13,931 |
[
"langchain-ai",
"langchain"
] | ### Feature request
Allow intercepting agents' final answers and reporting any feedback on the final answers to the agents without ending the agent execution chain.
This will enable users to, for example, run validations on the final answer (e.g. whether the answer contains some keywords) or agent's state (whether agent has used a particular tool) and report issues to the agent so that it can fix the problems before ending the chain.
### Motivation
Today, we don't have a way to run an analysis on final answers and report problems (if any) to the agents so that they can fix the problems without losing the thoughts and observations of the current chain (if there's a way to achieve that today, please feel free to point me to it and close this issue). This feature will allow self-correction of final answers, further enhancing the capabilities of agents.
Some use cases I have in mind include
1. Validate the final answer to ensure that it conforms to some instructions, e.g. by making an LLM call.
2. Make sure the agent has used a set of tools to come up with the answer.
3. Apply some rules on the answer to determine whether answer is correct or not, e.g. whether the answer contains certain keywords.
### Your contribution
I'm not able to contribute currently, however, I might be able to pick this up in coming weeks if it seems useful to others as well. | Allow intercepting agents' final answers and reporting feedback to them | https://api.github.com/repos/langchain-ai/langchain/issues/13929/comments | 5 | 2023-11-27T18:23:38Z | 2024-03-17T16:06:36Z | https://github.com/langchain-ai/langchain/issues/13929 | 2,012,847,820 | 13,929 |
[
"langchain-ai",
"langchain"
] | Hi everyone,
I'm trying to do something and I haven´t found enough information on the internet to make it work properly with Langchain. Here it is:
I want to develop a QA chat using pdfs as knowledge source, using as relevant documents the ones corresponding to a certain pdf that the user will choose with a select box. To achieve that:
1. I've built a Azure Search vector store in which all the embeddings of different documents are stored.
Each document's metadata looks something like this:
{
"@odata.context": "https://blublu.search.windows.net/indexes('embeddings')/$metadata#docs(*)",
"@search.nextPageParameters": {
"search": "*",
"top": null,
"skip": 50
},
"value": [
{
"@search.score": 1,
"id": "doc_embeddings_7102233d903cd1ac7475a60c373a716b57bf1586",
"title": "https://blahblah.blob.core.windows.net/documents/converted/100.pdf.txt",
"content": " Officer | Immediate line manager | Region/Division head or VP of the corresponding vertical | KFSL HR | | CEO | \n|Assistant Manager | | \n|Manager | CEO.\nv",
"content_vector": [
-0.0014578825,
-0.0058897766],
"tag": "",
"metadata": "{\"source\": \"[https://ask}"
},...}
3.With all this I'm using a ConversationalRetrievalChain to retrieve info from the vector store and using an llm to answer questions entered via prompt:
class FilteredRetriever:
def __init__(self, retriever, filter_prefix):
self.retriever = retriever
self.filter_prefix = filter_prefix
def retrieve(self, *args, **kwargs):
results = self.retriever.retrieve(*args, **kwargs)
return [doc for doc in results if doc['value']['title'].startswith(self.filter_prefix)]
source='https://blahblah.blob.core.windows.net/documents/converted/100.pdf.txt'
filtered_retriever = FilteredRetriever(self.vector_store.as_retriever(), source)
chain = ConversationalRetrievalChain(
retriever=filtered_retriever,
question_generator=question_generator,
combine_docs_chain=doc_chain,
return_source_documents=True,
# top_k_docs_for_context= self.k
)
But this is raising: instance of BaseRetriever expected (type=type_error.arbitrary_type; expected_arbitrary_type=BaseRetriever)
### Suggestion:
Have already referred [Filtering retrieval with ConversationalRetrievalChain](https://github.com/langchain-ai/langchain/issues/7474#top)
#7474 | Filtering Issue with ConversationRetrievalChain | https://api.github.com/repos/langchain-ai/langchain/issues/13924/comments | 2 | 2023-11-27T17:19:53Z | 2024-03-13T20:02:28Z | https://github.com/langchain-ai/langchain/issues/13924 | 2,012,745,465 | 13,924 |
[
"langchain-ai",
"langchain"
] | - | - | https://api.github.com/repos/langchain-ai/langchain/issues/13923/comments | 1 | 2023-11-27T17:04:38Z | 2023-11-28T05:59:31Z | https://github.com/langchain-ai/langchain/issues/13923 | 2,012,721,002 | 13,923 |
[
"langchain-ai",
"langchain"
] | @dosu-bot
I have a project where I need to extract product details from product links online. What is the best url loader for this use case?
Also, for the previous links that I already appended to a csv file called "Lalal". How can I create embeddings only for the new URL link that I will extract so that I dont have to embed the entire document every single time.
Please write the code for me in python. | Link to URL to load product details | https://api.github.com/repos/langchain-ai/langchain/issues/13920/comments | 6 | 2023-11-27T16:38:20Z | 2024-03-13T19:59:35Z | https://github.com/langchain-ai/langchain/issues/13920 | 2,012,673,073 | 13,920 |
[
"langchain-ai",
"langchain"
] | ### System Info
Langchain all versions
### Who can help?
@hwchase17 @izzymsft
### Information
- [X] The official example notebooks/scripts
- [ ] My own modified scripts
### Related Components
- [ ] LLMs/Chat Models
- [ ] Embedding Models
- [ ] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [X] Vector Stores / Retrievers
- [ ] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async
### Reproduction
Instantiate a new AzureCosmosDBVectorSearch with embeddings key different than vectorContent, and then you get this error
`Similarity index was not found for a vector similarity search query.`
This is because embeddings key is parametrised correctly
https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/vectorstores/azure_cosmos_db.py#L75
https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/vectorstores/azure_cosmos_db.py#L92
, but not used on index creation
https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/vectorstores/azure_cosmos_db.py#L224
### Expected behavior
The embedding_key param should be used to create the index properly | AzureCosmosDBVectorSearch index creation fixes document key | https://api.github.com/repos/langchain-ai/langchain/issues/13918/comments | 2 | 2023-11-27T16:11:15Z | 2024-03-13T20:01:29Z | https://github.com/langchain-ai/langchain/issues/13918 | 2,012,621,829 | 13,918 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.