delayedkarma/langchain-issues huggingface dataset:
Issue: I am using GPT-4 with SQLDatabaseChain it shows ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine error
Labels: name: area: memory, name: auto:bug, name: area: models

### Issue you'd like to raise.

I am working with SQLDatabaseChain in Django framework everytime  I execute the code it shows below error.
 File "C:\Users\ehsuser\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

Below is my code

user='root'       
database= 'real_estate_chatbot_new'
password=''
host= 'localhost'
port= '3306'
table_name1='app_projects'
table_name2='app_projectimages'

db_uri=f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}"

#input_db = SQLDatabase.from_uri('sqlite:///ashridhar.db')
input_db = SQLDatabase.from_uri(db_uri,include_tables=[table_name1,table_name2])
db_chain = SQLDatabaseChain.from_llm(llm, input_db, verbose=True)

prompt = """
        - You're a real estate chatbot for Buy home that is going to answer to a potential lead so keep your messages dynamic and enthusiastic making the interactions lively and enjoyable!.
        - Answer the question from database only if you don't find answer from database return a friendly message.
        - don't use word like 'database' in answer.
        - If it is not relevant to the database return connvencing and gratitude message.
        - If it is realted to price return it in words suppose the price is 7000000 then return 70 lakhs."""

tools = [
    Tool(
        name="Real_Estate_Chatbot",
        func=db_chain.run,
        #description="Answer the question from database only if you don't find answer from database return a friendly message., You're a real estate sales agent that is going to answer to a potential lead so keep your messages dynamic and enthusiastic making the interactions lively and enjoyable!.",
        description=prompt
    ),
]



agent_kwargs = {
    "extra_prompt_messages": [MessagesPlaceholder(variable_name="memory")],
}
memory = ConversationBufferWindowMemory(memory_key="memory",k=4,return_messages=True)

agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.OPENAI_FUNCTIONS,
    verbose=True,
    agent_kwargs=agent_kwargs,
    memory=memory,
)

response = agent.run(message)
return response


### Suggestion:

_No response_
Plain models are not calling callbacks when cached
Labels: name: auto:bug, name: area: models

### System Info

```
pip freeze | grep langchain
langchain==0.0.268
langchainplus-sdk==0.0.17
```

### Who can help?

@hwchase17 @agola11 

### 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
- [X] Callbacks/Tracing
- [ ] Async

### Reproduction

```py
from typing import Any, Dict, List

import langchain
from langchain.cache import SQLiteCache
from langchain.callbacks.base import BaseCallbackHandler
from langchain.chat_models import ChatVertexAI
from langchain.llms import VertexAI
from langchain.schema import HumanMessage

langchain.llm_cache = SQLiteCache(database_path="langchain-llm-cache.db")


class CallbackHandler(BaseCallbackHandler):
    run_inline = True

    def __init__(self, logger=None):
        self.messages = []

    def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str], run_id, parent_run_id, **kwargs: Any) -> Any:
        self.messages.append(run_id)


callback = CallbackHandler()
bison_text_llm = VertexAI(model_name="text-bison@001", temperature=0.0, max_output_tokens=500, callbacks=[callback])
bison_chat_llm = ChatVertexAI(model_name="chat-bison@001", temperature=0.0, max_output_tokens=500, callbacks=[callback])

bison_chat_llm([HumanMessage(content="Hello, how are you?")])
assert len(callback.messages) == 1
bison_chat_llm([HumanMessage(content="Hello, how are you?")])
assert len(callback.messages) == 2

bison_text_llm("Hello, how are you?")
assert len(callback.messages) == 3
bison_text_llm("Hello, how are you?")
assert len(callback.messages) == 4
```

### Expected behavior

It's unclear to me whether callbacks should be called when call is cached, but we can see that chat and plain text models implement different behaviour.

Ideally, callbacks would be called, with a flag saying that call is cached.
feat(streaming_aiter.py): add support for multiple LLM runs in a AsyncIteratorCallbackHandler
Labels: name: auto:improvement, name: area: models

<!-- Thank you for contributing to LangChain!

Replace this entire comment with:
  - Description: a description of the change, 
  - Issue: the issue # it fixes (if applicable),
  - Dependencies: any dependencies required for this change,
  - Tag maintainer: for a quicker response, tag the relevant maintainer (see below),
  - Twitter handle: we announce bigger features on Twitter. If your PR gets announced and you'd like a mention, we'll gladly shout you out!

Please make sure your PR is passing linting and testing before submitting. Run `make format`, `make lint` and `make test` to check this locally.

See contribution guidelines for more information on how to write/run tests, lint, etc: 
https://github.com/hwchase17/langchain/blob/master/.github/CONTRIBUTING.md

If you're adding a new integration, please include:
  1. a test for the integration, preferably unit tests that do not rely on network access,
  2. an example notebook showing its use. These live is docs/extras directory.

If no one reviews your PR within a few days, please @-mention one of @baskaryan, @eyurtsev, @hwchase17, @rlancemartin.
 -->

- Description: When I want to integrate LangChain into my Poe-API Project, which aims to provide multiple OpenAI functions for users, I write code based on https://github.com/langchain-ai/langchain-template-poe-fastapi/blob/main/langchain_template_poe_fastapi/handler.py
  ```py
  class EchoBot(PoeBot):
    async def get_response(self, query):
        callback_handler = AsyncIteratorCallbackHandler()

        mode = ChatOpenAI(
            temperature=0,
            model="gpt-3.5-turbo",
            streaming=True,
            callbacks=[callback_handler],
        )

        memory = convert_poe_messages(query.query)

        agent = initialize_agent(
            tools,
            llm=mode,
            agent=AgentType.OPENAI_FUNCTIONS,
            verbose=True,
            agent_kwargs={
                "extra_prompt_messages": [MessagesPlaceholder(variable_name="memory")],
            },
            memory=memory,
        )

        logging.info(query.query)

        last_message = query.query[-1].content
        run = asyncio.create_task(agent.arun(last_message))

        # Yield the tokens as they come in
        async for token in callback_handler.aiter():
            yield self.text_event(token)
        # Await the chain run
        await run
  ```
  However, I have noticed that it is not functioning properly. Example of each run process: `__init__ -> aiter -> on_llm_start -> on_llm_end -> on_llm_start ->on_llm_end`, `aiter` will end at the first `on_llm_end`. 
  The purpose of this PR is to ensure that `aiter` does not terminate at the first occurrence of `on_llm_end` when `LLMResult` has no any output message.

- Issue: https://github.com/langchain-ai/langchain/issues/9374

- Dependencies: None
Regression in structured_chat agent's Output parser
Labels: name: area: agent, name: auto:bug

### System Info

This regression affects Langchain >=0.0.262. This regression was introduced with #8965.

If an agent's output to input to a tool (e.g. to generate an `AgentAction`) contains either backticks (such as to represent a code block with ```), or embedded JSON (such as a structured JSON string in the `action_input` key), then the output parsing will fail.

### 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
- [ ] Vector Stores / Retrievers
- [ ] Memory
- [X] Agents / Agent Executors
- [X] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async

### Reproduction

Steps to reproduce the behavior:

1. Generate an agent that outputs a markdown formatted code block with a language.

To input to this tool, an `AgentAction` step will be made, that might look like:

```
```json
{
  "action": "Code generator tool",
  "action_input": "Generate code to optimize ```python\nprint("hello world")```
}
```

(Can't show closing backticks above due to formatting issues, but assume there's closing backticks in the above code block)

2. An error will occur, as a result of being unable to parse the actions.

Using 
`pattern = re.compile(r"```(?:json)?\n(.*)```", re.DOTALL)` works slightly better for both embedded JSON and backticks, but will result in unexpected behavior if there are multiple actions in a response

### Expected behavior

Should be able to parse a response with backticks or JSON inside the `action_input` key
All prompts translated to russian
Labels: name: auto:improvement, name: area: models

<!-- Thank you for contributing to LangChain!

Replace this entire comment with:
  - Description: a description of the change, 
  - Issue: the issue # it fixes (if applicable),
  - Dependencies: any dependencies required for this change,
  - Tag maintainer: for a quicker response, tag the relevant maintainer (see below),
  - Twitter handle: we announce bigger features on Twitter. If your PR gets announced and you'd like a mention, we'll gladly shout you out!

Please make sure your PR is passing linting and testing before submitting. Run `make format`, `make lint` and `make test` to check this locally.

See contribution guidelines for more information on how to write/run tests, lint, etc: 
https://github.com/hwchase17/langchain/blob/master/.github/CONTRIBUTING.md

If you're adding a new integration, please include:
  1. a test for the integration, preferably unit tests that do not rely on network access,
  2. an example notebook showing its use. These live is docs/extras directory.

If no one reviews your PR within a few days, please @-mention one of @baskaryan, @eyurtsev, @hwchase17, @rlancemartin.
 -->
All prompts translation
Labels: name: auto:improvement, name: area: models

<!-- Thank you for contributing to LangChain!

Replace this entire comment with:
  - Description: a description of the change, 
  - Issue: the issue # it fixes (if applicable),
  - Dependencies: any dependencies required for this change,
  - Tag maintainer: for a quicker response, tag the relevant maintainer (see below),
  - Twitter handle: we announce bigger features on Twitter. If your PR gets announced and you'd like a mention, we'll gladly shout you out!

Please make sure your PR is passing linting and testing before submitting. Run `make format`, `make lint` and `make test` to check this locally.

See contribution guidelines for more information on how to write/run tests, lint, etc: 
https://github.com/hwchase17/langchain/blob/master/.github/CONTRIBUTING.md

If you're adding a new integration, please include:
  1. a test for the integration, preferably unit tests that do not rely on network access,
  2. an example notebook showing its use. These live is docs/extras directory.

If no one reviews your PR within a few days, please @-mention one of @baskaryan, @eyurtsev, @hwchase17, @rlancemartin.
 -->
AttributeError: 'RecursiveCharacterTextSplitter' object has no attribute 'split_documents'
Labels: name: area: doc loader, name: area: vector store, name: auto:bug

### System Info

LangChain 0.0.74
Python 3.10
Windows 10

### 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

from langchain.document_loaders import UnstructuredExcelLoader
from langchain.indexes import VectorstoreIndexCreator
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI


loader = UnstructuredExcelLoader("N:\Python\Data.xlsx", mode="elements")
index = VectorstoreIndexCreator().from_loaders([loader])

Gives the following:
Traceback (most recent call last):

  Cell In[33], line 1
    index = VectorstoreIndexCreator().from_loaders([loader])

  File C:\Program Files\Anaconda3\lib\site-packages\langchain\indexes\vectorstore.py:73 in from_loaders

  File C:\Program Files\Anaconda3\lib\site-packages\langchain\indexes\vectorstore.py:77 in from_documents

AttributeError: 'RecursiveCharacterTextSplitter' object has no attribute 'split_documents'

### Expected behavior

Hi, 

When using the VectorstoreIndexCreator, I get an error:
AttributeError: 'RecursiveCharacterTextSplitter' object has no attribute 'split_documents'

In this case, it is when I want to upload an excel file, but I get the same when trying to upload a .txt  get the same error when I try to upload .txt files (with TextLoader).

Many thanks for your help!
Add AINetwork blockchain toolkit integration
Labels: name: area: agent, name: auto:enhancement

# Description
This PR introduces a new toolkit for interacting with the AINetwork blockchain. The toolkit provides a set of tools for performing various operations on the AINetwork blockchain, such as transferring AIN, reading and writing values to the blockchain database, managing apps, setting rules and owners. 

# Dependencies
[ain-py](https://github.com/ainblockchain/ain-py) >= 1.0.2

# Misc
The example notebook (langchain/docs/extras/integrations/toolkits/ainetwork.ipynb) is in the PR
Chatbot responses are deterorating on using langchain compared to open AI completion 
Labels: name: area: memory, name: auto:bug, name: auto:question, name: area: models

### Issue you'd like to raise.

Hi, 
Iam using langchain version 0.0.187. 
Here are the steps that I have followed to get chat response uisng langchain
```
   def initlize_llm_chain_prompt(self):
        print("initilizing llm chain prompt")
        llm_model=AzureOpenAI(deployment_name=self.AZURE_OPENAI_CHATGPT_DEPLOYMENT,model_name=os.environ.get("AZURE_OPENAI_CHATGPT_MODEL"),
                                temperature=0,
                                        max_tokens=1000)
        llm_chat_prompt = PromptTemplate(input_variables=["question"], template=self.prompt_template)
        question_generator = LLMChain(llm=llm_model, prompt=llm_chat_prompt)
        doc_chain=load_qa_chain(llm_model, chain_type="stuff")
        memory = ConversationBufferWindowMemory(memory_key="chat_history",return_messages=True,k=4)  # remember last 4 conversations

        self.llm_chain_prompt=ConversationalRetrievalChain(retriever=self.elastic_vector_search.as_retriever(search_kwargs={"k": 5}),
                                                        memory=memory,question_generator=question_generator,combine_docs_chain=doc_chain,verbose=True,get_chat_history=self.get_chat_history_custom)

```
**_Here is how Iam calling chat_**

 `result=self.llm_chain({"question": user_query}, )`
Here is the Prompt template format
```
prompt_template = """
System
Answer ONLY  with the facts listed in the Referenced documents. 
If there isn't enough information in the Sources , say you don't know. 
Do not strictly generate answers if its not available in the  Source and even though if you know the answer for it.





UserQuery:
{question}



Chatbot:
 """
```

In get_chat_history_custom() Iam just appending the conversation history data
  ```
 def get_chat_history_custom(self,inputs):
        res = []
        if(len(inputs)>0):
            inp_len=len(inputs)       
            for i in range(0,inp_len,2):
                human_content = inputs[i].content
                ai_content=inputs[i+1].content.split('Question')[0]
                res.append(f"Human:{human_content}\AIMessage:{ai_content}")
            buf="\n".join(res)
            return buf
        else:
            return ""
```

What I have observed is Iam not getting good responses even though Iam providing the relavent data as the source to the chat. Iam getiing good and expected answers if I use open AI completion call. Can I please knoww, If any of the above steps is wrong? and Do you recommond any other version langchain? 

### Suggestion:

Chatbot responses are not getting as expected in langchain on compared to the responses of open AI completion
Request for using custom fine tuned models
Labels: name: area: agent, name: auto:improvement, name: area: models

### Feature request

Issue you'd like to raise.
langchain==0.0.162

Hi, I am using a fine tuned model that generates user prompts to SQL queries, instead of the default model provided by langchain. The reason for doing this is because langchain does not know about all the data from the database unless you provide context to it but there is a lot of data hence why it can create incorrect SQL queries also it is unable to form complex queries for similar reasons even after you give it context.

So my question is based upon the output I am getting below. Is there a way to keep the initial question I asked the same throughout like in the action input, instead of "SOME_BRANCH_NAME" I want the entire sentence to go through to the SQLDatabaseChain like the user initially asked which is "what is the summary of last 3 issues reported by SOME_BRANCH_NAME". Basically since the Action Input is different from what the user asked, it is generating the wrong SQL query since what it should be doing is this, "SELECT summary FROM sla_tat_summary WHERE organization like '%SOME_BRANCH_NAME%' ORDER BY ReportedDate DESC LIMIT 3;" instead of what is shown below. I could just use the SQLDatabaseChain on its own which does get the exact query I want since I was able to make sure only the prompt the user gave went through, but the agent is needed since I am using it for things other than SQL generation.

user prompt: what is the summary of last 3 issues reported by SOME_BRANCH_NAME

Entering new AgentExecutor chain...
I need to find out what the last 3 issues reported by SOME_BRANCH_NAME were.
Action: TPS Issue Tracker Database
Action Input: SOME_BRANCH_NAME

Entering new SQLDatabaseChain chain...
SOME_BRANCH_NAME:
SELECT organization, COUNT() FROM sla_tat_summary WHERE severity = 'Level 2 - Critical' GROUP BY organization ORDER BY COUNT() DESC LIMIT 1

In summary I want to have an option to keep my user prompt unchanged throughout the flow from the agent to the to SQLdatabasechain

### Motivation

I need a way for langchain to be able to use fine-tuned models for multi-class classification and have a way to not use hard-coded stopping points rather have it as a parameter for a developer to select. 

### Your contribution

my custom langchain package would only integrate well with my own use case hence why I am not submitting a PR. Also even though I am using langchain==0.0.162. But the issue would be similar in the latest langchain version
Issue: Proxy not successfully used
Labels: name: area: agent, name: auto:bug, name: area: models

### Issue you'd like to raise.

This is my code, I'm not sure if it's correct:
`from langchain.llms import ChatGLM
from langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType, tool
from datetime import date

@tool
def time(text: str) -> str:
    """返回今天的日期，用于回答用户关于今天日期的问题。
    输入应该始终为空字符串，此函数将始终返回今天的日期。
    任何日期计算都应在此函数外部进行。"""
    return str(date.today())


endpoint_url = "http://0.0.0.0:8000"

llm = ChatGLM(
    endpoint_url=endpoint_url,
    max_token=80000,
    # history=[["我有一些问题！","我可以回答你的任何问题，请向我提问！"]],
    top_p=0.9,
    model_kwargs={"sample_model_args": False},
)

tools = load_tools([], llm=llm)
agent = initialize_agent(
    tools + [time], 
    llm, 
    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    handle_parsing_errors=True,
    verbose=True
)

try:
    result = agent.run("今天是几号？")
    print(result)
except Exception as e: 
    print("外部访问异常：", e)`

However, the answer after running is not accurate：
`(chatglm_env) root@autodl-container-b25f1193e8-0ae83321:~/autodl-tmp# python t_n.py


> Entering new AgentExecutor chain...
Could not parse LLM output: 今天是2023年2月18日。
Observation: Invalid or incomplete response
Thought:Could not parse LLM output: Today is February 18th, 2023.
Observation: Invalid or incomplete response
Thought:Final Answer: 今天是2023年2月18日。

> Finished chain.
今天是2023年2月18日。`

Please help me



### Suggestion:

_No response_
AttributeError: 'super' object has no attribute 'parse_obj' when using OpenAPISpec.from_file
Labels: name: auto:bug, name: area: models

### System Info

Langchain version 0.0.268


### 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
- [X] Tools / Toolkits
- [ ] Chains
- [ ] Callbacks/Tracing
- [ ] Async

### Reproduction

1. Load in .yaml file containing the OpenAPI specification.
2. Call the OpenAPISpec with   ` open_api_spec = OpenAPISpec.from_file(file_path)`

Error shows that in _openapi.py_ line 202 ,`return super().parse_obj(obj)` no longer inherits the super method from Pydantic's BaseModel parse_obj.  

### Expected behavior

The OpenAPISpec should be delivered so that it can be passed on to `NLAToolkit.from_llm_and_spec`.