delayedkarma/langchain-issues huggingface dataset:
feat: Implement `stream` interface
Labels: name: lgtm, name: auto:enhancement, name: area: models, name: size:L

<!-- Thank you for contributing to LangChain!

Please title your PR "<package>: <description>", where <package> is whichever of langchain, community, core, experimental, etc. is being modified.

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,
  - **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` from the root of the package you've modified to check this locally.

See contribution guidelines for more information on how to write/run tests, lint, etc: https://python.langchain.com/docs/contributing/

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. It lives in `docs/docs/integrations` directory.

If no one reviews your PR within a few days, please @-mention one of @baskaryan, @eyurtsev, @hwchase17.
 -->

Major changes:

- Rename `wasm_chat.py` to `llama_edge.py`
- Rename the `WasmChatService` class to `ChatService`
- Implement the `stream` interface for `ChatService`
- Add `test_chat_wasm_service_streaming` in the integration test
- Update `llama_edge.ipynb`
docs: Correct a typo on Quickstart page
Labels: name: auto:documentation, name: size:XS

The ChatOpenAI class does not have a parameter called **openai_api_key**.  Instead, it should be renamed to **api_key** only.

<!-- Thank you for contributing to LangChain!

Please title your PR "<package>: <description>", where <package> is whichever of langchain, community, core, experimental, etc. is being modified.

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,
  - **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` from the root of the package you've modified to check this locally.

See contribution guidelines for more information on how to write/run tests, lint, etc: https://python.langchain.com/docs/contributing/

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. It lives in `docs/docs/integrations` directory.

If no one reviews your PR within a few days, please @-mention one of @baskaryan, @eyurtsev, @hwchase17.
 -->
No function called
Labels: name: area: models

### Checked other resources

- [X] I added a very descriptive title to this issue.
- [X] I searched the LangChain documentation with the integrated search.
- [X] I used the GitHub search to find a similar question and didn't find it.

### Example Code

from langchain.chat_models import ChatOpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnableMap
from langchain.schema.messages import HumanMessage, SystemMessage
from langchain.vectorstores import DocArrayInMemorySearch
from langchain.utils.openai_functions import convert_pydantic_to_openai_function
from typing import List
from pydantic import BaseModel, Field

class PopulationSearch(BaseModel):
    """Get the population size based on the given city"""
    city: str = Field(description="city")


population_function = convert_pydantic_to_openai_function(PopulationSearch)
model = ChatOpenAI(
    temperature=0,
    model_name="gpt4-turbo"
)
response = model.invoke("What is the population of Wuhan?", functions=[population_function])
print(response.additional_kwargs)

### Description

The result is {}. Why is it empty value?
The screenshots are as follows:
![image](https://github.com/langchain-ai/langchain/assets/8477759/97d66ed6-4cbb-4664-8231-d5e5990ca0db)


### System Info

Python version is 3.11
LangChain version is 0.0.343

### 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
ConfluenceLoader.load giving AttributeError: 'str' object has no attribute 'get' while reading all documents from space
Labels: name: area: doc loader, name: auto:bug

### Checked other resources

- [X] I added a very descriptive title to this issue.
- [X] I searched the LangChain documentation with the integrated search.
- [X] I used the GitHub search to find a similar question and didn't find it.

### Example Code

from langchain.document_loaders import ConfluenceLoader

loader = ConfluenceLoader(
    url="<my confluence link>", username="<my user name>", 
    api_key="<my token>"
)
documents = loader.load(space_key="<my space>", include_attachments=True, limit=1, max_pages=1)

### Description

I am trying to load all confluence pages using ConflueceLoader. I expect to get all the pages but instead I get the AttributeError: 'str' object has no attribute 'get'

### System Info

python version 3.10.2
langchain version 0.0.345

### 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
Index Creation
Labels: name: auto:improvement

### Feature request

I noticed that the MongoDBChatMessageHistory class object is attempting to create an index during connection, causing each request to take longer than usual. Index Creation is one time process, So no need create index everytime. By default, index creation is enabled. To address this, add an additional parameter, index_creation. If index_creation is set to False, this step should be ignored. 

Current Code:
```
def __init__(
        self,
        connection_string: str,
        session_id: str,
        database_name: str = DEFAULT_DBNAME,
        collection_name: str = DEFAULT_COLLECTION_NAME,
    ):
        from pymongo import MongoClient, errors

        self.connection_string = connection_string
        self.session_id = session_id
        self.database_name = database_name
        self.collection_name = collection_name

        try:
            self.client: MongoClient = MongoClient(connection_string)
        except errors.ConnectionFailure as error:
            logger.error(error)

        self.db = self.client[database_name]
        self.collection = self.db[collection_name]
        self.collection.create_index("SessionId")
```

Proposed modification:
```
def __init__(
        self,
        connection_string: str,
        session_id: str,
        database_name: str = DEFAULT_DBNAME,
        collection_name: str = DEFAULT_COLLECTION_NAME,
        index_creation:bool =True #New argument 
    ):
        from pymongo import MongoClient, errors

        self.connection_string = connection_string
        self.session_id = session_id
        self.database_name = database_name
        self.collection_name = collection_name

        try:
            self.client: MongoClient = MongoClient(connection_string)
        except errors.ConnectionFailure as error:
            logger.error(error)

        self.db = self.client[database_name]
        self.collection = self.db[collection_name]
        if index_creation: #Conditional Index Creation
            self.collection.create_index("SessionId")
```

### Motivation

Developer can do custom modification, But if you make this feature that feature comes package.

### Your contribution

yes, can do this
Proposed modification:
```
def __init__(
        self,
        connection_string: str,
        session_id: str,
        database_name: str = DEFAULT_DBNAME,
        collection_name: str = DEFAULT_COLLECTION_NAME,
        index_creation:bool =True #New argument 
    ):
        from pymongo import MongoClient, errors

        self.connection_string = connection_string
        self.session_id = session_id
        self.database_name = database_name
        self.collection_name = collection_name

        try:
            self.client: MongoClient = MongoClient(connection_string)
        except errors.ConnectionFailure as error:
            logger.error(error)

        self.db = self.client[database_name]
        self.collection = self.db[collection_name]
        if index_creation: #Conditional Index Creation
            self.collection.create_index("SessionId")
```
How can I store chat history in a database and retrieve results using cosine similarity when querying the database?"
Labels: name: area: embeddings, name: auto:documentation

### Issue with current documentation:

import os
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationTokenBufferMemory
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores.qdrant import Qdrant
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, MessagesPlaceholder, \
    HumanMessagePromptTemplate
from qdrant_client import QdrantClient

os.environ['OPENAI_API_KEY'] = "mykey"
client = QdrantClient(host="192.168.0.313", port=6333)
COLLECTION_NAME = "embed"
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
vectorstore = Qdrant.from_documents(
    client=client,
    collection_name=COLLECTION_NAME,
    embeddings=embeddings,
    search_params={"metric_type": "cosine"},
)

prompt = ChatPromptTemplate(
    messages=[
        SystemMessagePromptTemplate.from_template(
            "you are robot."
        ),
        MessagesPlaceholder(variable_name="chat_history"),
        HumanMessagePromptTemplate.from_template("{question}"),
    ]
)


llm_name = "gpt-3.5-turbo"
llm = ChatOpenAI(model_name=llm_name, temperature=0)
memory_token_limit = 100
retriever = vectorstore.as_retriever()
memory = ConversationTokenBufferMemory(
    llm=llm,
    prompt=prompt,
    max_token_limit=int(memory_token_limit),
    memory_key="chat_history",
    return_messages=True,
)

qa = ConversationalRetrievalChain.from_llm(
    llm=llm,
    retriever=retriever,
    memory=memory,
    verbose=True,
)

chat_history = []
while True:
    memory.load_memory_variables({})
    question = input('ask：')
    result = qa.run({'question': question, 'chat_history': chat_history})
    print(result)
    chat_history.append([f'User: {question}', f'Ai: {result}'])
    print(chat_history)
    st_history = ' '.join(map(str, chat_history))
    res = embeddings.embed_query(st_history)

    print(f'ok: {res[:4]}...')
    if question.lower() == 'bye':
        break


### Idea or request for content:

embeddings
cosine
PR community:Removing knn beta content in mongodb atlas vectorstore
Labels: name: lgtm, name: area: vector store, name: auto:improvement, name: size:S

<!-- Thank you for contributing to LangChain!

Please title your PR "<package>: <description>", where <package> is whichever of langchain, community, core, experimental, etc. is being modified.

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,
  - **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` from the root of the package you've modified to check this locally.

See contribution guidelines for more information on how to write/run tests, lint, etc: https://python.langchain.com/docs/contributing/

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. It lives in `docs/docs/integrations` directory.

If no one reviews your PR within a few days, please @-mention one of @baskaryan, @eyurtsev, @hwchase17.
 -->
community: deprecate ErnieBotChat and ErnieEmbeddings classes
Labels: name: lgtm, name: area: embeddings, name: auto:improvement, name: auto:nit, name: size:L

  - **Description:** add deprecated warning for ErnieBotChat and ErnieEmbeddings. 
    - These two classes **lack maintenance** and do not use the sdk provided by qianfan, which means hard to implement some key feature like streaming. 
    - The alternative `langchain_community.chat_models.QianfanChatEndpoint` and `langchain_community.embeddings.QianfanEmbeddingsEndpoint` can completely replace these two classes, only need to change configuration items.
  - **Issue:** None,
  - **Dependencies:** None,
  - **Twitter handle:** None
AttributeError: 'str' object has no attribute 'log'
Labels: name: area: agent, name: auto:bug

I am creating a tool using _run and _arun versions for my FastAPI code to use the tool in AgentExecutor. When I test my agent, I am running into this AttributeError which I am unable to resolve even with a debugger. Am I missing anything here? 


from fastapi import Request
from langchain.tools import tool, BaseTool
from pydantic import BaseModel, Field
from typing import Type, Optional
from langchain.callbacks.manager import (
    AsyncCallbackManagerForToolRun,
    CallbackManagerForToolRun,
)

from settings import app_settings as settings
from ai.tools import run_chain
import httpx


class PlaceHolderSchema(BaseModel):
    dummy: Optional[str] 

async def run_chain_tool(request: Request) :          
    
    class ChainTool(BaseTool):
        name = "run_chain"
        description = "This tool takes a user question as input and returns the answer using the Cube JSON extraction and Cube API response."        
        args_schema: Type[PlaceHolderSchema] = PlaceHolderSchema
        def _run(self,    
            question: str,        
            run_manager: Optional[CallbackManagerForToolRun] = None, 
            dummy: Optional[str] = None,         
            ) -> str:
            """
            This function "synchronously" runs the tool.

            Args:
                question (str): User question about the Cube data model.
            Returns:
                answer (str): Answer to the user question by running a chain of steps such as generation of Cube JSON, calling Cube API, and generating final answer.
            """
            raise NotImplementedError("run_chain tool does not support synchronous execution")

        async def _arun(self,
            question: str,                  
            run_manager: Optional[AsyncCallbackManagerForToolRun] = None,         
            dummy: Optional[str] = None,   
        ) -> str:
            """
            This function "asynchronously" runs the tool.

            Args:
                question (str): User question about the Cube data model.
            Returns:
                answer (str): Answer to the user question by running a chain of steps such as generation of Cube JSON, calling Cube API, and generating final answer.
            """
            try:                      
                answer = await run_chain(question, request)
                print(answer)
                return answer  

            except Exception as e: print(f"Error: {e}")                     
            
    return ChainTool()
Google Trend utility makes assumptions on keys from response
Labels: name: auto:bug

### Checked other resources

- [X] I added a very descriptive title to this issue.
- [X] I searched the LangChain documentation with the integrated search.
- [X] I used the GitHub search to find a similar question and didn't find it.

### Example Code

The following code:
```
import os
from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper

os.environ['SERPAPI_API_KEY'] = ''

tool = GoogleTrendsAPIWrapper()
tool.run("Something that will yield an error like totally")
```
will yield this:
```
Traceback (most recent call last):
  File "/home/ubuntu/Work/luc/langchain-google-trends-issue-1/langchain_google_trends_issue_1/main.py", line 9, in <module>
    tool.run("Something that will yield an error like totally")
  File "/home/ubuntu/Work/luc/langchain-google-trends-issue-1/.venv/lib/python3.10/site-packages/langchain_community/utilities/google_trends.py", line 68, in run
    total_results = client.get_dict()["interest_over_time"]["timeline_data"]
KeyError: 'interest_over_time'
```

### Description

* I'm trying to use the Google Trends tool with some AI agent. 
* Now the (not so smart) agent ran a query with Google Trend that did NOT return what its implementation expected.
* I would expect the implementation to follow a more foolproof logic.


### System Info

# pyproject.toml
python = "^3.10"
langchain = "0.0.354"
pytest = "^7.4.4"
google-search-results = "^2.4.2"

### 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
SelfQueryRetriever with Pinecone Automatically Converts String Metadata into DateTime
Labels: name: area: vector store, name: auto:bug, name: integration: pinecone

### Checked other resources

- [X] I added a very descriptive title to this issue.
- [X] I searched the LangChain documentation with the integrated search.
- [X] I used the GitHub search to find a similar question and didn't find it.

### Example Code

Metadata
```python
doc.metadata["date_year_short"] = date_obj.strftime("%y") # 23
doc.metadata["date_year_long"] = date_obj.strftime("%Y")  # 2023
doc.metadata["date_month"] = date_obj.strftime("%-m") # 12
doc.metadata["date_month_name"] = calendar.month_name[date_obj.month] # December
doc.metadata["date_day"] = date_obj.strftime("%-d") # 31
doc.metadata["date_uploaded"] = calendar.month_name[date_obj.month] + " " + date_obj.strftime("%Y") # January 2023
```

Self-Query Retriever + Pinecone DB Instatiation
```python
llm = ChatOpenAI(temperature=0)
vectorstore = Pinecone.from_existing_index(index_name="test", embedding=get_embedding_function())

retriever = SelfQueryRetriever.from_llm(
    llm,
    vectorstore,
    "Information about when the document was created and where it was grabbed from.",
    metadata_field_info,
)


# bancworks_docs[1359]
retriever.vectorstore.similarity_search_with_score(question)
```



### Description

Should be able to see my metadata instantiated in string form the way I created them instead of being converted to date time.

For example, my date_month_name field is "Feburary 2023". It should not be converted to 2/1/2000.

### System Info

Docker image container, Python v3.11, Langchain v0.1.0

### 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
core: make BaseTool._parse_input return all parameters
Labels: name: area: agent, name: auto:bug, name: size:XS

## Why

the `tool` decorator is convenient to specify parameter infomations, but the default values are not parsed by default:

```
from langchain.agents import tool
from langchain.pydantic_v1 import Field

@tool
def text2images(
    prompt: str,
    n: int = Field(1, description="image count"),
):
    '''generate images'''
    ...

text2images("draw a house") 

# will fail because BaseTool._parse_input returns {"prompt": "draw a house"}, then the tool is called with parameters {"prompt": "draw a house", "n": FieldInfo(...)}.
# it should return {"prompt": "draw a house", "n": 1}

```
embedding router with conversation history 
Labels: name: area: memory, name: auto:question

### Checked other resources

- [X] I added a very descriptive title to this issue.
- [X] I searched the LangChain documentation with the integrated search.
- [X] I used the GitHub search to find a similar question and didn't find it.

### Example Code

I wrote the code for categorization of prompt.

```python
def prompt_router(input, embeddings, prompt_templates, prompt_embeddings):
    query_embedding = embeddings.embed_query(input["query"])
    similarity = cosine_similarity([query_embedding], prompt_embeddings)[0]
    most_similar = prompt_templates[similarity.argmax()]
    print(most_similar)
    return PromptTemplate.from_template(most_similar)
    
    
def main_categorizer(message):
    global memory, entry
    formatted_history = memory.get_history_as_string()
    
    case1_template = """Description of what case1 does

    Chat History:
    {chat_history}

    Here is a question:
    {query}"""

    case2_template = """Description of what case2 does

    Chat History:
    {chat_history}

    Here is a question:
    {query}"""

    case3_template = """Description of what case3 does

    Chat History:
    {chat_history}

    Here is a question:
    {query}"""

    case4_template = """Description of what case4 does

    Chat History:
    {chat_history}

    Here is a question:
    {query}"""


    prompt_templates = [case1_template, case2_template, case3_template, case4_template]
    prompt_embeddings = embeddings.embed_documents(prompt_templates)

    chain = (
        {"query": RunnablePassthrough()}
        | RunnableLambda(prompt_router)
        | llm
        | StrOutputParser()
    )
```

### Description

Based on the document in https://python.langchain.com/docs/expression_language/cookbook/embedding_router,
I've tried to implement embedding router.
What I would like to do is, adding conversation history to the case prompts so that they can use historical conversation as well to consider which category the user prompt is.

In here, I have no idea where to put {chat_history} value just like the query being inserted with ```"query": RunnablePassthrough()```


### System Info

langchian==0.0.352

### Related Components

- [X] LLMs/Chat Models
- [ ] Embedding Models
- [X] Prompts / Prompt Templates / Prompt Selectors
- [ ] Output Parsers
- [ ] Document Loaders
- [ ] Vector Stores / Retrievers
- [X] Memory
- [ ] Agents / Agent Executors
- [ ] Tools / Toolkits
- [X] Chains
- [ ] Callbacks/Tracing
- [ ] Async