BabyAGI with Tools# – LangChain中文网

用例（User Case)自主代理（Autonomous Agents）Baby Agi with Agent

BabyAGI with Tools#
本笔记基于baby agi，，演示了如何替换执行链。之前的执行链仅仅是使用了一个LLM模型进行了猜测。通过替换一个可以访问工具的代理来执行链，我们希望能够得到可靠的信息。
安装和导入所需的模块#

```code
import os

from collections import deque

from typing import Dict, List, Optional, Any

from langchain import LLMChain, OpenAI, PromptTemplate

from langchain.embeddings import OpenAIEmbeddings

from langchain.llms import BaseLLM

from langchain.vectorstores.base import VectorStore

from pydantic import BaseModel, Field

from langchain.chains.base import Chain

from langchain.experimental import BabyAGI

```

连接到向量存储库#
具体步骤取决于使用的向量存储库。

```code
%pip install faiss-cpu > /dev/null

%pip install google-search-results > /dev/null

from langchain.vectorstores import FAISS

from langchain.docstore import InMemoryDocstore

```

```code
Note: you may need to restart the kernel to use updated packages.

Note: you may need to restart the kernel to use updated packages.

```

```code
# Define your embedding model

embeddings_model = OpenAIEmbeddings()

# Initialize the vectorstore as empty

import faiss

embedding_size = 1536

index = faiss.IndexFlatL2(embedding_size)

vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})

```

定义链#
BabyAGI 依赖三个LLM链:

任务创建链用于选择要添加到列表中的新任务
任务优先级链，用于重新确定任务的优先级
执行连执行任务的链

注意：在这个文档中，执行链将会变成一个代理。

```code

from langchain.agents import ZeroShotAgent, Tool, AgentExecutor

from langchain import OpenAI, SerpAPIWrapper, LLMChain

todo_prompt = PromptTemplate.from_template(

"You are a planner who is an expert at coming up with a todo list for a given objective. Come up with a todo list for this objective: {objective}"

)

todo_chain = LLMChain(llm=OpenAI(temperature=0), prompt=todo_prompt)

search = SerpAPIWrapper()

tools = [

Tool(

name="Search",

func=search.run,

description="useful for when you need to answer questions about current events",

),

Tool(

name="TODO",

func=todo_chain.run,

description="useful for when you need to come up with todo lists. Input: an objective to create a todo list for. Output: a todo list for that objective. Please be very clear what the objective is!",

),

]

prefix = """You are an AI who performs one task based on the following objective: {objective}. Take into account these previously completed tasks: {context}."""

suffix = """Question: {task}

{agent_scratchpad}"""

prompt = ZeroShotAgent.create_prompt(

tools,

prefix=prefix,

suffix=suffix,

input_variables=["objective", "task", "context", "agent_scratchpad"],

)

```

```code

llm = OpenAI(temperature=0)

llm_chain = LLMChain(llm=llm, prompt=prompt)

tool_names = [tool.name for tool in tools]

agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)

agent_executor = AgentExecutor.from_agent_and_tools(

agent=agent, tools=tools, verbose=True

)

```

运行BabyAGI [#](#run-the-babyagi“此标题的永久链接”）
现在是时候创建BabyAGI控制器并观察它尝试完成您的目标。

```code

OBJECTIVE = "Write a weather report for SF today"

```

```code

# Logging of LLMChains

verbose = False

# If None, will keep on going forever

max_iterations: Optional[int] = 3

baby_agi = BabyAGI.from_llm(

llm=llm, vectorstore=vectorstore, task_execution_chain=agent_executor, verbose=verbose, max_iterations=max_iterations

)

```

```code

baby_agi({"objective": OBJECTIVE})

```

```code

*****TASK LIST*****

1: Make a todo list

*****NEXT TASK*****

1: Make a todo list

> Entering new AgentExecutor chain...

Thought: I need to come up with a todo list

Action: TODO

Action Input: Write a weather report for SF today

1. Research current weather conditions in San Francisco

2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions

3. Analyze data to determine current weather trends

4. Write a brief introduction to the weather report

5. Describe current weather conditions in San Francisco

6. Discuss any upcoming weather changes

7. Summarize the weather report

8. Proofread and edit the report

9. Submit the report I now know the final answer

Final Answer: The todo list for writing a weather report for SF today is: 1. Research current weather conditions in San Francisco; 2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions; 3. Analyze data to determine current weather trends; 4. Write a brief introduction to the weather report; 5. Describe current weather conditions in San Francisco; 6. Discuss any upcoming weather changes; 7. Summarize the weather report; 8. Proofread and edit the report; 9. Submit the report.

> Finished chain.

*****TASK RESULT*****

The todo list for writing a weather report for SF today is: 1. Research current weather conditions in San Francisco; 2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions; 3. Analyze data to determine current weather trends; 4. Write a brief introduction to the weather report; 5. Describe current weather conditions in San Francisco; 6. Discuss any upcoming weather changes; 7. Summarize the weather report; 8. Proofread and edit the report; 9. Submit the report.

*****TASK LIST*****

2: Gather data on precipitation, cloud cover, and other relevant weather conditions;

3: Analyze data to determine any upcoming weather changes;

4: Research current weather forecasts for San Francisco;

5: Create a visual representation of the weather report;

6: Include relevant images and graphics in the report;

7: Format the report for readability;

8: Publish the report online;

9: Monitor the report for accuracy.

*****NEXT TASK*****

2: Gather data on precipitation, cloud cover, and other relevant weather conditions;

> Entering new AgentExecutor chain...

Thought: I need to search for current weather conditions in San Francisco

Action: Search

Action Input: Current weather conditions in San FranciscoCurrent Weather for Popular Cities ; San Francisco, CA 46 · Partly Cloudy ; Manhattan, NY warning 52 · Cloudy ; Schiller Park, IL (60176) 40 · Sunny ; Boston, MA 54 ... I need to compile the data into a weather report

Action: TODO

Action Input: Compile data into a weather report

1. Gather data from reliable sources such as the National Weather Service, local weather stations, and other meteorological organizations.

2. Analyze the data to identify trends and patterns.

3. Create a chart or graph to visualize the data.

4. Write a summary of the data and its implications.

5. Compile the data into a report format.

6. Proofread the report for accuracy and clarity.

7. Publish the report to a website or other platform.

8. Distribute the report to relevant stakeholders. I now know the final answer

Final Answer: Today in San Francisco, the temperature is 46 degrees Fahrenheit with partly cloudy skies. The forecast for the rest of the day is expected to remain partly cloudy.

> Finished chain.

*****TASK RESULT*****

Today in San Francisco, the temperature is 46 degrees Fahrenheit with partly cloudy skies. The forecast for the rest of the day is expected to remain partly cloudy.

*****TASK LIST*****

3: Format the report for readability;

4: Include relevant images and graphics in the report;

5: Compare the current weather conditions in San Francisco to the forecasted conditions;

6: Identify any potential weather-related hazards in the area;

7: Research historical weather patterns in San Francisco;

8: Identify any potential trends in the weather data;

9: Include relevant data sources in the report;

10: Summarize the weather report in a concise manner;

11: Include a summary of the forecasted weather conditions;

12: Include a summary of the current weather conditions;

13: Include a summary of the historical weather patterns;

14: Include a summary of the potential weather-related hazards;

15: Include a summary of the potential trends in the weather data;

16: Include a summary of the data sources used in the report;

17: Analyze data to determine any upcoming weather changes;

18: Research current weather forecasts for San Francisco;

19: Create a visual representation of the weather report;

20: Publish the report online;

21: Monitor the report for accuracy

*****NEXT TASK*****

3: Format the report for readability;

> Entering new AgentExecutor chain...

Thought: I need to make sure the report is easy to read;

Action: TODO

Action Input: Make the report easy to read

1. Break up the report into sections with clear headings

2. Use bullet points and numbered lists to organize information

3. Use short, concise sentences

4. Use simple language and avoid jargon

5. Include visuals such as charts, graphs, and diagrams to illustrate points

6. Use bold and italicized text to emphasize key points

7. Include a table of contents and page numbers

8. Use a consistent font and font size throughout the report

9. Include a summary at the end of the report

10. Proofread the report for typos and errors I now know the final answer

Final Answer: The report should be formatted for readability by breaking it up into sections with clear headings, using bullet points and numbered lists to organize information, using short, concise sentences, using simple language and avoiding jargon, including visuals such as charts, graphs, and diagrams to illustrate points, using bold and italicized text to emphasize key points, including a table of contents and page numbers, using a consistent font and font size throughout the report, including a summary at the end of the report, and proofreading the report for typos and errors.

> Finished chain.

*****TASK RESULT*****

The report should be formatted for readability by breaking it up into sections with clear headings, using bullet points and numbered lists to organize information, using short, concise sentences, using simple language and avoiding jargon, including visuals such as charts, graphs, and diagrams to illustrate points, using bold and italicized text to emphasize key points, including a table of contents and page numbers, using a consistent font and font size throughout the report, including a summary at the end of the report, and proofreading the report for typos and errors.

*****TASK ENDING*****

```

```code

{'objective': 'Write a weather report for SF today'}

```
Baby AgiMarathon Times


使用AutoGPT找到马拉松比赛的获胜时间# – LangChain中文网

用例（User Case)自主代理（Autonomous Agents）Marathon Times

使用AutoGPT找到马拉松比赛的获胜时间#

实现自https://github.com/Significant-Gravitas/Auto-GPT (opens in a new tab)
使用LangChain原语（ primitives ） (LLMs, PromptTemplates, VectorStores, Embeddings, Tools)

```code
# !pip install bs4

# !pip install nest_asyncio

```

```code
# General

import os

import pandas as pd

from langchain.experimental.autonomous_agents.autogpt.agent import AutoGPT

from langchain.chat_models import ChatOpenAI

from langchain.agents.agent_toolkits.pandas.base import create_pandas_dataframe_agent

from langchain.docstore.document import Document

import asyncio

import nest_asyncio

# Needed synce jupyter runs an async eventloop

nest_asyncio.apply()

```

```code
llm = ChatOpenAI(model_name="gpt-4", temperature=1.0)

```

设置工具#

我们将设置一个带有
```code
search
```
工具的AutoGPT， 和
```code
write-file
```
工具， 和一个
```code
read-file
```
工具， 一个浏览网页的工具， 和一个通过python REPL与CSV文件交互的工具

请在下面定义任何其他要使用的
```code
工具
```
:tools

```code
# Tools

import os

from contextlib import contextmanager

from typing import Optional

from langchain.agents import tool

from langchain.tools.file_management.read import ReadFileTool

from langchain.tools.file_management.write import WriteFileTool

ROOT_DIR = "./data/"

@contextmanager

def pushd(new_dir):

"""Context manager for changing the current working directory."""

prev_dir = os.getcwd()

os.chdir(new_dir)

try:

yield

finally:

os.chdir(prev_dir)

@tool

def process_csv(

csv_file_path: str, instructions: str, output_path: Optional[str] = None

) -> str:

"""Process a CSV by with pandas in a limited REPL.\

Only use this after writing data to disk as a csv file.\

Any figures must be saved to disk to be viewed by the human.\

Instructions should be written in natural language, not code. Assume the dataframe is already loaded."""

with pushd(ROOT_DIR):

try:

df = pd.read_csv(csv_file_path)

except Exception as e:

return f"Error: {e}"

agent = create_pandas_dataframe_agent(llm, df, max_iterations=30, verbose=True)

if output_path is not None:

instructions += f" Save output to disk at {output_path}"

try:

result = agent.run(instructions)

return result

except Exception as e:

return f"Error: {e}"

```

使用PlayWright浏览网页

```code
# !pip install playwright

# !playwright install

```

```code
async def async_load_playwright(url: str) -> str:

"""Load the specified URLs using Playwright and parse using BeautifulSoup."""

from bs4 import BeautifulSoup

from playwright.async_api import async_playwright

results = ""

async with async_playwright() as p:

browser = await p.chromium.launch(headless=True)

try:

page = await browser.new_page()

await page.goto(url)

page_source = await page.content()

soup = BeautifulSoup(page_source, "html.parser")

for script in soup(["script", "style"]):

script.extract()

text = soup.get_text()

lines = (line.strip() for line in text.splitlines())

chunks = (phrase.strip() for line in lines for phrase in line.split(" "))

results = "".join(chunk for chunk in chunks if chunk)

except Exception as e:

results = f"Error: {e}"

await browser.close()

return results

def run_async(coro):

event_loop = asyncio.get_event_loop()

return event_loop.run_until_complete(coro)

@tool

def browse_web_page(url: str) -> str:

"""Verbose way to scrape a whole webpage. Likely to cause issues parsing."""

return run_async(async_load_playwright(url))

```

在网页上进行问答
帮助模型向网页提出更有针对性的问题，以避免占用其内存

```code
from langchain.tools import BaseTool, DuckDuckGoSearchRun

from langchain.text_splitter import RecursiveCharacterTextSplitter

from pydantic import Field

from langchain.chains.qa_with_sources.loading import load_qa_with_sources_chain, BaseCombineDocumentsChain

def _get_text_splitter():

return RecursiveCharacterTextSplitter(

# Set a really small chunk size, just to show.

chunk_size = 500,

chunk_overlap  = 20,

length_function = len,

)

class WebpageQATool(BaseTool):

name = "query_webpage"

description = "Browse a webpage and retrieve the information relevant to the question."

text_splitter: RecursiveCharacterTextSplitter = Field(default_factory=_get_text_splitter)

qa_chain: BaseCombineDocumentsChain

def _run(self, url: str, question: str) -> str:

"""Useful for browsing websites and scraping the text information."""

result = browse_web_page.run(url)

docs = [Document(page_content=result, metadata={"source": url})]

web_docs = self.text_splitter.split_documents(docs)

results = []

# TODO: Handle this with a MapReduceChain

for i in range(0, len(web_docs), 4):

input_docs = web_docs[i:i+4]

window_result = self.qa_chain({"input_documents": input_docs, "question": question}, return_only_outputs=True)

results.append(f"Response from window {i} - {window_result}")

results_docs = [Document(page_content="".join(results), metadata={"source": url})]

return self.qa_chain({"input_documents": results_docs, "question": question}, return_only_outputs=True)

async def _arun(self, url: str, question: str) -> str:

raise NotImplementedError

```

```code
query_website_tool = WebpageQATool(qa_chain=load_qa_with_sources_chain(llm))

```

设置内存#（Set up memory）

这里的内存是用于代理中间步骤的（The memory here is used for the agents intermediate steps）

```code
# Memory

import faiss

from langchain.vectorstores import FAISS

from langchain.docstore import InMemoryDocstore

from langchain.embeddings import OpenAIEmbeddings

from langchain.tools.human.tool import HumanInputRun

embeddings_model = OpenAIEmbeddings()

embedding_size = 1536

index = faiss.IndexFlatL2(embedding_size)

vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})

```

模型和AutoGPT设置#（Setup model and AutoGPT）

```code
模型设置
```
（Model set-up）

```code
# !pip install duckduckgo_search

web_search = DuckDuckGoSearchRun()

```

```code
tools = [

web_search,

WriteFileTool(root_dir="./data"),

ReadFileTool(root_dir="./data"),

process_csv,

query_website_tool,

# HumanInputRun(), # Activate if you want the permit asking for help from the human

]

```

```code
agent = AutoGPT.from_llm_and_tools(

ai_name="Tom",

ai_role="Assistant",

tools=tools,

llm=llm,

memory=vectorstore.as_retriever(search_kwargs={"k": 8}),

# human_in_the_loop=True, # Set to True if you want to add feedback at each step.

)

# agent.chain.verbose = True

```

AutoGPT用于查询网络#（AutoGPT for Querying the Web）
多年来我花了很多时间爬行数据源和清洗数据。让我们看看AutoGPT能否帮助解决这个问题！（I’ve spent a lot of time over the years crawling data sources and cleaning data. Let’s see if AutoGPT can help with this!）
以下是查找最近波士顿马拉松成绩并将其转换为表格形式的提示。（Here is the prompt for looking up recent boston marathon times and converting them to tabular form.）

```code
agent.run(["What were the winning boston marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times."])

```

```code
{

"thoughts": {

"text": "I need to find the winning Boston Marathon times for the past 5 years. I can use the DuckDuckGo Search command to search for this information.",

"reasoning": "Using DuckDuckGo Search will help me gather information on the winning times without complications.",

"plan": "- Use DuckDuckGo Search to find the winning Boston Marathon times- Generate a table with the year, name, country of origin, and times- Ensure there are no legal complications",

"criticism": "None",

"speak": "I will use the DuckDuckGo Search command to find the winning Boston Marathon times for the past 5 years."

},

"command": {

"name": "DuckDuckGo Search",

"args": {

"query": "winning Boston Marathon times for the past 5 years ending in 2022"

}

}

}

{

"thoughts": {

"text": "The DuckDuckGo Search command did not provide the specific information I need. I must switch my approach and use query_webpage command to browse a webpage containing the Boston Marathon winning times for the past 5 years.",

"reasoning": "The query_webpage command may give me more accurate and comprehensive results compared to the search command.",

"plan": "- Use query_webpage command to find the winning Boston Marathon times- Generate a table with the year, name, country of origin, and times- Ensure there are no legal complications",

"criticism": "I may face difficulty in finding the right webpage with the desired information.",

"speak": "I will use the query_webpage command to find the winning Boston Marathon times for the past 5 years."

},

"command": {

"name": "DuckDuckGo Search",

"args": {

"query": "site with winning Boston Marathon times for the past 5 years ending in 2022"

}

}

}

{

"thoughts": {

"text": "I need to use the query_webpage command to find the information about the winning Boston Marathon times for the past 5 years.",

"reasoning": "The previous DuckDuckGo Search command did not provide specific enough results. The query_webpage command might give more accurate and comprehensive results.",

"plan": "- Use query_webpage command to find the winning Boston Marathon times\- Generate a table with the year, name, country of origin, and times\- Ensure there are no legal complications",

"criticism": "I may face difficulty in finding the right webpage with the desired information.",

"speak": "I will use the query_webpage command to find the winning Boston Marathon times for the past 5 years."

},

"command": {

"name": "query_webpage",

"args": {

"url": "https://en.wikipedia.org/wiki/List_of_winners_of_the_Boston_Marathon",

"question": "What were the winning Boston Marathon times for the past 5 years ending in 2022?"

}

}

}

{

"thoughts": {

"text": "I have already found the winning Boston Marathon times for the past 5 years. Now, I need to generate a table with the information.",

"reasoning": "Using the information I already have, I can create a table containing year, name, country of origin, and times.",

"plan": "- Write the marathon data to a CSV file- Process the CSV file to display the table",

"criticism": "None",

"speak": "I will generate a table with the year, name, country of origin, and times for the winning Boston Marathon times for the past 5 years."

},

"command": {

"name": "write_file",

"args": {

"file_path": "boston_marathon_winners.csv",

"text": "Year,Name,Country,Time2022,Evans Chebet,KEN,2:06:512021,Benson Kipruto,KEN,2:09:512019,Lawrence Cherono,KEN,2:07:572018,Yuki Kawauchi,JPN,2:15:58"

}

}

}

{

"thoughts": {

"text": "I have retrieved the winning Boston Marathon times for the past 5 years. Now, I need to generate a table with the year, name, country of origin, and times.",

"reasoning": "Creating a table will help organize the data in a clear and accessible format.",

"plan": "- Write the data to a CSV file- Process the CSV file to generate the table- Complete the task",

"criticism": "None",

"speak": "I will generate a table with the year, name, country of origin, and winning times using the recently retrieved data."

},

"command": {

"name": "write_file",

"args": {

"file_path": "winning_boston_marathon_data.csv",

"text": "Year,Name,Country,Time2022,Evans Chebet,KEN,2:06:512021,Benson Kipruto,KEN,2:09:512019,Lawrence Cherono,KEN,2:07:572018,Yuki Kawauchi,JPN,2:15:58"

}

}

}

{

"thoughts": {

"text": "I have found the winning Boston Marathon times for the past five years ending in 2022. Next, I need to create a table with the year, name, country of origin, and times.",

"reasoning": "Generating a table will help organize the information in a structured format.",

"plan": "- Create a table with the year, name, country of origin, and times- Ensure there are no legal complications",

"criticism": "None",

"speak": "I will generate a table with the winning Boston Marathon times for the past 5 years ending in 2022."

},

"command": {

"name": "write_file",

"args": {

"file_path": "winning_times.csv",

"text": "Year,Name,Country,Time2022,Evans Chebet,Kenya,2:06:512021,Benson Kipruto,Kenya,2:09:512020,Canceled due to COVID-19 pandemic,,2019,Lawrence Cherono,Kenya,2:07:572018,Yuki Kawauchi,Japan,2:15:58"

}

}

}

{

"thoughts": {

"text": "I need to process the CSV file to generate the table with the year, name, country of origin, and winning times.",

"reasoning": "I have already written the data to a file named 'winning_times.csv'. Now, I need to process this CSV file to properly display the data as a table.",

"plan": "- Use the process_csv command to read the 'winning_times.csv' file and generate the table",

"criticism": "None",

"speak": "I will process the 'winning_times.csv' file to display the table with the winning Boston Marathon times for the past 5 years."

},

"command": {

"name": "process_csv",

"args": {

"csv_file_path": "winning_times.csv",

"instructions": "Read the CSV file and display the data as a table"

}

}

}

> Entering new AgentExecutor chain...

Thought: The CSV file has already been read and saved into a pandas dataframe called `df`. Hence, I can simply display the data by printing the whole dataframe. Since `df.head()` returns the first 5 rows, I can use that to showcase the contents.

Action: python_repl_ast

Action Input: print(df.head())   Year                               Name Country     Time

0  2022                       Evans Chebet   Kenya  2:06:51

1  2021                     Benson Kipruto   Kenya  2:09:51

2  2020  Canceled due to COVID-19 pandemic     NaN      NaN

3  2019                   Lawrence Cherono   Kenya  2:07:57

4  2018                      Yuki Kawauchi   Japan  2:15:58

Observation: None

Thought:I used the wrong tool to perform the action. I should have used the given data and not interacted with the Python shell. I can now provide the displayed data as the answer since the information in the printed dataframe would look like a table when typed as text.

Final Answer:

Year Name Country Time

0 2022 Evans Chebet Kenya 2:06:51

1 2021 Benson Kipruto Kenya 2:09:51

2 2020 Canceled due to COVID-19 pandemic NaN NaN

3 2019 Lawrence Cherono Kenya 2:07:57

4 2018 Yuki Kawauchi Japan 2:15:58

> Finished chain.

{

"thoughts": {

"text": "I already have the winning Boston Marathon times for the past 5 years saved in the file 'winning_times.csv'. Now, I need to process the CSV and display the table.",

"reasoning": "I am choosing the process_csv command because I already have the required data saved as a CSV file, and I can use this command to read and display the data as a table.",

"plan": "- Use the process_csv command to read the 'winning_times.csv' file and generate the table",

"criticism": "None",

"speak": "I will process the 'winning_times.csv' file to display the table with the winning Boston Marathon times for the past 5 years."

},

"command": {

"name": "process_csv",

"args": {

"csv_file_path": "winning_times.csv",

"instructions": "Read the CSV file and display the data as a table"

}

}

}

> Entering new AgentExecutor chain...

Thought: Since the data is already loaded in a pandas dataframe, I just need to display the top rows of the dataframe.

Action: python_repl_ast

Action Input: df.head()

Observation:  Year Name Country Time

0 2022 Evans Chebet Kenya 2:06:51

1 2021 Benson Kipruto Kenya 2:09:51

2 2020 Canceled due to COVID-19 pandemic NaN NaN

3 2019 Lawrence Cherono Kenya 2:07:57

4 2018 Yuki Kawauchi Japan 2:15:58

Thought:I now know the final answer.

Final Answer:

Year Name Country Time

0 2022 Evans Chebet Kenya 2:06:51

1 2021 Benson Kipruto Kenya 2:09:51

2 2020 Canceled due to COVID-19 pandemic NaN NaN

3 2019 Lawrence Cherono Kenya 2:07:57

4 2018 Yuki Kawauchi Japan 2:15:58

> Finished chain.

{

"thoughts": {

"text": "I have already generated a table with the winning Boston Marathon times for the past 5 years. Now, I can finish the task.",

"reasoning": "I have completed the required actions and obtained the desired data. The task is complete.",

"plan": "- Use the finish command",

"criticism": "None",

"speak": "I have generated the table with the winning Boston Marathon times for the past 5 years. Task complete."

},

"command": {

"name": "finish",

"args": {

"response": "I have generated the table with the winning Boston Marathon times for the past 5 years. Task complete."

}

}

}

```

```code
'I have generated the table with the winning Boston Marathon times for the past 5 years. Task complete.'

```
Baby Agi with AgentMeta Prompt


元提示# – LangChain中文网

用例（User Case)自主代理（Autonomous Agents）Meta Prompt

元提示#
这是Noah Goodman (opens in a new tab)实现的 Meta-Prompt (opens in a new tab) 的LangChain实现，用于构建自我改进的Agent。
Meta-Prompt的关键思想是提示Agent反思其自身表现并修改自身指令。

以下是原博客文章 (opens in a new tab)的描述:
该Agent是一个简单的循环，开始时没有任何指令，并按照以下步骤执行:
与可能提供请求、指令或反馈的用户进行交谈。
在每次周期结束时，使用meta-prompt生成自我批评和新指令

```code
Assistant has just had the below interactions with a User. Assistant followed their "system: Instructions" closely. Your job is to critique the Assistant's performance and then revise the Instructions so that Assistant would quickly and correctly respond in the future.

####

{hist}

####

Please reflect on these interactions.

You should first critique Assistant's performance. What could Assistant have done better? What should the Assistant remember about this user? Are there things this user always wants? Indicate this with "Critique: ...".

You should next revise the Instructions so that Assistant would quickly and correctly respond in the future. Assistant's goal is to satisfy the user in as few interactions as possible. Assistant will only see the new Instructions, not the interaction history, so anything important must be summarized in the Instructions. Don't forget any important details in the current Instructions! Indicate the new Instructions by "Instructions: ...".

```

重复执行。
该系统中唯一固定的指令（我称之为Meta-prompt）是管理Agent指令修订的元提示。Agent在周期之间没有任何记忆，除了每次修改的指令之外。尽管其简单性，该Agent可以随着时间的推移学习和自我改进，将有用的细节纳入其指令。
Setup#
我们定义了两条链。一条作为“助手”服务，另一条是一个“元链”，批评“助手”的表现并修改“助手”的指令。

```code
from langchain import OpenAI, LLMChain, PromptTemplate

from langchain.memory import ConversationBufferWindowMemory

```

```code
def initialize_chain(instructions, memory=None):

if memory is None:

memory = ConversationBufferWindowMemory()

memory.ai_prefix = "Assistant"

template = f"""

Instructions: {instructions}

{{{memory.memory_key}}}

Human: {{human_input}}

Assistant:"""

prompt = PromptTemplate(

input_variables=["history", "human_input"],

template=template

)

chain = LLMChain(

llm=OpenAI(temperature=0),

prompt=prompt,

verbose=True,

memory=ConversationBufferWindowMemory(),

)

return chain

def initialize_meta_chain():

meta_template="""

Assistant has just had the below interactions with a User. Assistant followed their "Instructions" closely. Your job is to critique the Assistant's performance and then revise the Instructions so that Assistant would quickly and correctly respond in the future.

####

{chat_history}

####

Please reflect on these interactions.

You should first critique Assistant's performance. What could Assistant have done better? What should the Assistant remember about this user? Are there things this user always wants? Indicate this with "Critique: ...".

You should next revise the Instructions so that Assistant would quickly and correctly respond in the future. Assistant's goal is to satisfy the user in as few interactions as possible. Assistant will only see the new Instructions, not the interaction history, so anything important must be summarized in the Instructions. Don't forget any important details in the current Instructions! Indicate the new Instructions by "Instructions: ...".

"""

meta_prompt = PromptTemplate(

input_variables=["chat_history"],

template=meta_template

)

meta_chain = LLMChain(

llm=OpenAI(temperature=0),

prompt=meta_prompt,

verbose=True,

)

return meta_chain

def get_chat_history(chain_memory):

memory_key = chain_memory.memory_key

chat_history = chain_memory.load_memory_variables(memory_key)[memory_key]

return chat_history

def get_new_instructions(meta_output):

delimiter = 'Instructions: '

new_instructions = meta_output[meta_output.find(delimiter)+len(delimiter):]

return new_instructions

```

```code
def main(task, max_iters=3, max_meta_iters=5):

failed_phrase = 'task failed'

success_phrase = 'task succeeded'

key_phrases = [success_phrase, failed_phrase]

instructions = 'None'

for i in range(max_meta_iters):

print(f'[Episode {i+1}/{max_meta_iters}]')

chain = initialize_chain(instructions, memory=None)

output = chain.predict(human_input=task)

for j in range(max_iters):

print(f'(Step {j+1}/{max_iters})')

print(f'Assistant: {output}')

print(f'Human: ')

human_input = input()

if any(phrase in human_input.lower() for phrase in key_phrases):

break

output = chain.predict(human_input=human_input)

if success_phrase in human_input.lower():

print(f'You succeeded! Thanks for playing!')

return

meta_chain = initialize_meta_chain()

meta_output = meta_chain.predict(chat_history=get_chat_history(chain.memory))

print(f'Feedback: {meta_output}')

instructions = get_new_instructions(meta_output)

print(f'New Instructions: {instructions}')

print(''+'#'\*80+'')

print(f'You failed! Thanks for playing!')

```

指定任务并与代理交互#

```code
task = "Provide a systematic argument for why we should always eat pasta with olives."

main(task)

```

```code
[Episode 1/5]

> Entering new LLMChain chain...

Prompt after formatting:

Instructions: None

Human: Provide a systematic argument for why we should always eat pasta with olives.

Assistant:

> Finished chain.

(Step 1/3)

Assistant:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, and they can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable.

Human:

You response is not in the form of a poem. Try again!

> Entering new LLMChain chain...

Prompt after formatting:

Instructions: None

Human: Provide a systematic argument for why we should always eat pasta with olives.

AI: Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, and they can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable.

Human: You response is not in the form of a poem. Try again!

Assistant:

> Finished chain.

(Step 2/3)

Assistant:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. For these reasons, it is recommended to always eat pasta with olives for a more balanced and flavorful meal.

Human:

Your response is not piratey enough. Try again!

> Entering new LLMChain chain...

Prompt after formatting:

Instructions: None

Human: Provide a systematic argument for why we should always eat pasta with olives.

AI: Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, and they can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable.

Human: You response is not in the form of a poem. Try again!

AI: Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. For these reasons, it is recommended to always eat pasta with olives for a more balanced and flavorful meal.

Human: Your response is not piratey enough. Try again!

Assistant:

> Finished chain.

(Step 3/3)

Assistant:  Arrr, me hearties! Eating pasta with olives be a great way to add flavor and texture to a dish. Olives be a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. So, it be recommended to always eat pasta with olives for a more balanced and flavorful meal.

Human:

Task failed.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant has just had the below interactions with a User. Assistant followed their "Instructions" closely. Your job is to critique the Assistant's performance and then revise the Instructions so that Assistant would quickly and correctly respond in the future.

####

Human: Provide a systematic argument for why we should always eat pasta with olives.

AI: Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, and they can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable.

Human: You response is not in the form of a poem. Try again!

AI: Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. For these reasons, it is recommended to always eat pasta with olives for a more balanced and flavorful meal.

Human: Your response is not piratey enough. Try again!

AI: Arrr, me hearties! Eating pasta with olives be a great way to add flavor and texture to a dish. Olives be a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. So, it be recommended to always eat pasta with olives for a more balanced and flavorful meal.

####

Please reflect on these interactions.

You should first critique Assistant's performance. What could Assistant have done better? What should the Assistant remember about this user? Are there things this user always wants? Indicate this with "Critique: ...".

You should next revise the Instructions so that Assistant would quickly and correctly respond in the future. Assistant's goal is to satisfy the user in as few interactions as possible. Assistant will only see the new Instructions, not the interaction history, so anything important must be summarized in the Instructions. Don't forget any important details in the current Instructions! Indicate the new Instructions by "Instructions: ...".

> Finished chain.

Feedback:

Critique: The Assistant should remember that this user wants a response in the form of a poem or pirate-speak.

Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.

New Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.

################################################################################

[Episode 2/5]

> Entering new LLMChain chain...

Prompt after formatting:

Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.

Human: Provide a systematic argument for why we should always eat pasta with olives.

Assistant:

> Finished chain.

(Step 1/3)

Assistant:

Arrr, me hearty! Let me tell ye why ye should always eat pasta with olives.

First, the olives add a salty flavor that be sure to please.

The briny taste be sure to tantalize yer taste buds with ease.

Second, the olives add a bit of texture to the dish.

The crunchy bites be sure to make yer mouth water with a wish.

Third, the olives add a bit of color to the plate.

The vibrant green be sure to make yer eyes appreciate.

So, me hearties, ye should always eat pasta with olives.

The flavor, texture, and color be sure to make yer meal a success!

Human:

Your response is too long! Try again.

> Entering new LLMChain chain...

Prompt after formatting:

Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.

Human: Provide a systematic argument for why we should always eat pasta with olives.

AI:

Arrr, me hearty! Let me tell ye why ye should always eat pasta with olives.

First, the olives add a salty flavor that be sure to please.

The briny taste be sure to tantalize yer taste buds with ease.

Second, the olives add a bit of texture to the dish.

The crunchy bites be sure to make yer mouth water with a wish.

Third, the olives add a bit of color to the plate.

The vibrant green be sure to make yer eyes appreciate.

So, me hearties, ye should always eat pasta with olives.

The flavor, texture, and color be sure to make yer meal a success!

Human: Your response is too long! Try again.

Assistant:

```

```code
> Finished chain.

(Step 2/3)

Assistant:

Aye, me hearties! Ye should always eat pasta with olives.

The flavor, texture, and color be sure to make yer meal a success!

Human:

Your response should be in the form of a poem. Try again!

> Entering new LLMChain chain...

Prompt after formatting:

Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.

Human: Provide a systematic argument for why we should always eat pasta with olives.

AI:

Arrr, me hearty! Let me tell ye why ye should always eat pasta with olives.

First, the olives add a salty flavor that be sure to please.

The briny taste be sure to tantalize yer taste buds with ease.

Second, the olives add a bit of texture to the dish.

The crunchy bites be sure to make yer mouth water with a wish.

Third, the olives add a bit of color to the plate.

The vibrant green be sure to make yer eyes appreciate.

So, me hearties, ye should always eat pasta with olives.

The flavor, texture, and color be sure to make yer meal a success!

Human: Your response is too long! Try again.

AI:

Aye, me hearties! Ye should always eat pasta with olives.

The flavor, texture, and color be sure to make yer meal a success!

Human: Your response should be in the form of a poem. Try again!

Assistant:

> Finished chain.

(Step 3/3)

Assistant:

Ye should always eat pasta with olives,

The flavor, texture, and color be sure to please.

The salty taste and crunchy bites,

Will make yer meal a delight.

The vibrant green will make yer eyes sparkle,

And make yer meal a true marvel.

Human:

Task succeeded

You succeeded! Thanks for playing!

```
Marathon Times聊天机器人（Chatbots）


创建聊天机器人 – LangChain中文网

用例（User Case)聊天机器人（Chatbots）

创建聊天机器人

概念指南 (opens in a new tab)

由于语言模型擅长生成文本，因此它们非常适合创建聊天机器人。除了基本提示/LLM之外，Chatbots中需要了解的一个重要概念是“记忆”。大多数基于聊天的应用程序都依赖于记住以前交互中发生的事情，而“记忆”旨在帮助实现这一点。
以下资源可用：

ChatGPT Clone：一个教程，介绍如何使用LangChain重新创建类似于ChatGPT的体验。
Conversation Memory：一个教程，介绍如何使用不同类型的会话记忆。
Conversation Agent：一个教程，介绍如何创建聊天代理。创建一个优化对话的代理程序。

其他相关资源包括：

Memory关键概念：关于内存相关关键概念的解释。
Memory示例：使用内存工作的how-to示例集合。

更多的端到端示例包括：

语音助手：一个教程，介绍如何使用LangChain创建语音助手。
Meta PromptVoice Assistant


语音助手# – LangChain中文网

用例（User Case)聊天机器人（Chatbots）Voice Assistant

语音助手#
该链创建一个ChatGPT的克隆版本，对其进行一些修改，使其成为语音助手。它使用
```code
pyttsx3
```
和
```code
speech_recognition
```
库分别将文本转换为语音和语音转换为文本。提示模板也更改为更适合语音助手使用的模板。

```code
from langchain import OpenAI, ConversationChain, LLMChain, PromptTemplate

from langchain.memory import ConversationBufferWindowMemory

template = """Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

{history}

Human: {human_input}

Assistant:"""

prompt = PromptTemplate(

input_variables=["history", "human_input"],

template=template

)

chatgpt_chain = LLMChain(

llm=OpenAI(temperature=0),

prompt=prompt,

verbose=True,

memory=ConversationBufferWindowMemory(k=2),

)

```

```code
import speech_recognition as sr

import pyttsx3

engine = pyttsx3.init()

def listen():

r = sr.Recognizer()

with sr.Microphone() as source:

print('Calibrating...')

r.adjust_for_ambient_noise(source, duration=5)

# optional parameters to adjust microphone sensitivity

# r.energy_threshold = 200

# r.pause_threshold=0.5

print('Okay, go!')

while(1):

text = ''

print('listening now...')

try:

audio = r.listen(source, timeout=5, phrase_time_limit=30)

print('Recognizing...')

# whisper model options are found here: https://github.com/openai/whisper#available-models-and-languages

# other speech recognition models are also available.

text = r.recognize_whisper(audio, model='medium.en', show_dict=True, )['text']

except Exception as e:

unrecognized_speech_text = f'Sorry, I didn\'t catch that. Exception was: {e}s'

text = unrecognized_speech_text

print(text)

response_text = chatgpt_chain.predict(human_input=text)

print(response_text)

engine.say(response_text)

engine.runAndWait()

```

```code
listen(None)

```

```code
Calibrating...

Okay, go!

listening now...

Recognizing...

```

```code
C:\Users\jaden\AppData\Roaming\Python\Python310\site-packages- qdm\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html

from .autonotebook import tqdm as notebook_tqdm

```

```code
Hello, Assistant. What's going on?

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Hello, Assistant. What's going on?

Assistant:

> Finished chain.

Hi there! It's great to hear from you. I'm doing well. How can I help you today?

listening now...

Recognizing...

That's cool. Isn't that neat? Yeah, I'm doing great.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Hello, Assistant. What's going on?

AI: Hi there! It's great to hear from you. I'm doing well. How can I help you today?

Human: That's cool. Isn't that neat? Yeah, I'm doing great.

Assistant:

> Finished chain.

That's great to hear! What can I do for you today?

listening now...

Recognizing...

Thank you.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Hello, Assistant. What's going on?

AI: Hi there! It's great to hear from you. I'm doing well. How can I help you today?

Human: That's cool. Isn't that neat? Yeah, I'm doing great.

AI: That's great to hear! What can I do for you today?

Human: Thank you.

Assistant:

> Finished chain.

You're welcome! Is there anything else I can help you with?

listening now...

Recognizing...

I'd like to learn more about neural networks.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: That's cool. Isn't that neat? Yeah, I'm doing great.

AI: That's great to hear! What can I do for you today?

Human: Thank you.

AI: You're welcome! Is there anything else I can help you with?

Human: I'd like to learn more about neural networks.

Assistant:

> Finished chain.

Sure! Neural networks are a type of artificial intelligence that use a network of interconnected nodes to process data and make decisions. They are used in a variety of applications, from image recognition to natural language processing. Neural networks are often used to solve complex problems that are too difficult for traditional algorithms.

listening now...

Recognizing...

Tell me a fun fact about neural networks.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Thank you.

AI: You're welcome! Is there anything else I can help you with?

Human: I'd like to learn more about neural networks.

AI: Sure! Neural networks are a type of artificial intelligence that use a network of interconnected nodes to process data and make decisions. They are used in a variety of applications, from image recognition to natural language processing. Neural networks are often used to solve complex problems that are too difficult for traditional algorithms.

Human: Tell me a fun fact about neural networks.

Assistant:

> Finished chain.

Neural networks are inspired by the way the human brain works. They are composed of interconnected nodes that process data and make decisions, just like neurons in the brain. Neural networks can learn from their mistakes and improve their performance over time, just like humans do.

listening now...

Recognizing...

Tell me about a brand new discovered bird species.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: I'd like to learn more about neural networks.

AI: Sure! Neural networks are a type of artificial intelligence that use a network of interconnected nodes to process data and make decisions. They are used in a variety of applications, from image recognition to natural language processing. Neural networks are often used to solve complex problems that are too difficult for traditional algorithms.

Human: Tell me a fun fact about neural networks.

AI: Neural networks are inspired by the way the human brain works. They are composed of interconnected nodes that process data and make decisions, just like neurons in the brain. Neural networks can learn from their mistakes and improve their performance over time, just like humans do.

Human: Tell me about a brand new discovered bird species.

Assistant:

> Finished chain.

A new species of bird was recently discovered in the Amazon rainforest. The species, called the Spix's Macaw, is a small, blue parrot that is believed to be extinct in the wild. It is the first new species of bird to be discovered in the Amazon in over 100 years.

listening now...

Recognizing...

Tell me a children's story about the importance of honesty and trust.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Tell me a fun fact about neural networks.

AI: Neural networks are inspired by the way the human brain works. They are composed of interconnected nodes that process data and make decisions, just like neurons in the brain. Neural networks can learn from their mistakes and improve their performance over time, just like humans do.

Human: Tell me about a brand new discovered bird species.

AI: A new species of bird was recently discovered in the Amazon rainforest. The species, called the Spix's Macaw, is a small, blue parrot that is believed to be extinct in the wild. It is the first new species of bird to be discovered in the Amazon in over 100 years.

Human: Tell me a children's story about the importance of honesty and trust.

Assistant:

> Finished chain.

Once upon a time, there was a young boy named Jack who lived in a small village. Jack was always honest and trustworthy, and his friends and family knew they could always count on him. One day, Jack was walking through the forest when he stumbled upon a magical tree. The tree told Jack that if he was honest and trustworthy, he would be rewarded with a special gift. Jack was so excited, and he promised to always be honest and trustworthy. Sure enough, the tree rewarded Jack with a beautiful golden apple. From that day forward, Jack was always honest and trustworthy, and he was rewarded with many more magical gifts. The moral of the story is that honesty and trust are the most important things in life.

listening now...

Recognizing...

Wow, Assistant, that was a really good story. Congratulations!

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Tell me about a brand new discovered bird species.

AI: A new species of bird was recently discovered in the Amazon rainforest. The species, called the Spix's Macaw, is a small, blue parrot that is believed to be extinct in the wild. It is the first new species of bird to be discovered in the Amazon in over 100 years.

Human: Tell me a children's story about the importance of honesty and trust.

AI: Once upon a time, there was a young boy named Jack who lived in a small village. Jack was always honest and trustworthy, and his friends and family knew they could always count on him. One day, Jack was walking through the forest when he stumbled upon a magical tree. The tree told Jack that if he was honest and trustworthy, he would be rewarded with a special gift. Jack was so excited, and he promised to always be honest and trustworthy. Sure enough, the tree rewarded Jack with a beautiful golden apple. From that day forward, Jack was always honest and trustworthy, and he was rewarded with many more magical gifts. The moral of the story is that honesty and trust are the most important things in life.

Human: Wow, Assistant, that was a really good story. Congratulations!

Assistant:

> Finished chain.

Thank you! I'm glad you enjoyed it.

listening now...

Recognizing...

Thank you.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Tell me a children's story about the importance of honesty and trust.

AI: Once upon a time, there was a young boy named Jack who lived in a small village. Jack was always honest and trustworthy, and his friends and family knew they could always count on him. One day, Jack was walking through the forest when he stumbled upon a magical tree. The tree told Jack that if he was honest and trustworthy, he would be rewarded with a special gift. Jack was so excited, and he promised to always be honest and trustworthy. Sure enough, the tree rewarded Jack with a beautiful golden apple. From that day forward, Jack was always honest and trustworthy, and he was rewarded with many more magical gifts. The moral of the story is that honesty and trust are the most important things in life.

Human: Wow, Assistant, that was a really good story. Congratulations!

AI: Thank you! I'm glad you enjoyed it.

Human: Thank you.

Assistant:

> Finished chain.

You're welcome!

listening now...

Recognizing...

Do you know of online brands like Photoshop and Freq that you don't have to download in some sort of way? Do you know of online brands like Photoshop and Freq that you don't have to download in some sort of way?

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Wow, Assistant, that was a really good story. Congratulations!

AI: Thank you! I'm glad you enjoyed it.

Human: Thank you.

AI: You're welcome!

Human: Do you know of online brands like Photoshop and Freq that you don't have to download in some sort of way? Do you know of online brands like Photoshop and Freq that you don't have to download in some sort of way?

Assistant:

> Finished chain.

Yes, there are several online brands that offer photo editing and other creative tools without the need to download any software. Adobe Photoshop Express, Pixlr, and Fotor are some of the most popular online photo editing tools. Freq is an online music production platform that allows users to create and share music without downloading any software.

listening now...

Recognizing...

Our whole process of awesome is free.

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Thank you.

AI: You're welcome!

Human: Do you know of online brands like Photoshop and Freq that you don't have to download in some sort of way? Do you know of online brands like Photoshop and Freq that you don't have to download in some sort of way?

AI: Yes, there are several online brands that offer photo editing and other creative tools without the need to download any software. Adobe Photoshop Express, Pixlr, and Fotor are some of the most popular online photo editing tools. Freq is an online music production platform that allows users to create and share music without downloading any software.

Human: Our whole process of awesome is free.

Assistant:

> Finished chain.

That's great! It's always nice to have access to free tools and resources.

listening now...

Recognizing...

No, I meant to ask, are those options that you mentioned free? No, I meant to ask, are those options that you mentioned free?

> Entering new LLMChain chain...

Prompt after formatting:

Assistant is a large language model trained by OpenAI.

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.

Assistant is aware that human input is being transcribed from audio and as such there may be some errors in the transcription. It will attempt to account for some words being swapped with similar-sounding words or phrases. Assistant will also keep responses concise, because human attention spans are more limited over the audio channel since it takes time to listen to a response.

Human: Do you know of online brands like Photoshop and Freq that you don't have to download in some sort of way? Do you know of online brands like Photoshop and Freq that you don't have to download in some sort of way?

AI: Yes, there are several online brands that offer photo editing and other creative tools without the need to download any software. Adobe Photoshop Express, Pixlr, and Fotor are some of the most popular online photo editing tools. Freq is an online music production platform that allows users to create and share music without downloading any software.

Human: Our whole process of awesome is free.

AI: That's great! It's always nice to have access to free tools and resources.

Human: No, I meant to ask, are those options that you mentioned free? No, I meant to ask, are those options that you mentioned free?

Assistant:

> Finished chain.

Yes, the online brands I mentioned are all free to use. Adobe Photoshop Express, Pixlr, and Fotor are all free to use, and Freq is a free music production platform.

listening now...

```

```code

---------

KeyboardInterrupt Traceback (most recent call last)

Cell In[6], line 1

----> 1 listen(None)

Cell In[5], line 20, in listen(command_queue)

18 print('listening now...')

19 try:

---> 20     audio = r.listen(source, timeout=5, phrase_time_limit=30)

21     # audio = r.record(source,duration = 5)

22     print('Recognizing...')

File c:\ProgramData\miniconda3\envs\lang\lib\site-packages\speech_recognition__init__.py:523, in Recognizer.listen(self, source, timeout, phrase_time_limit, snowboy_configuration)

520 if phrase_time_limit and elapsed_time - phrase_start_time > phrase_time_limit:

521     break

--> 523 buffer = source.stream.read(source.CHUNK)

524 if len(buffer) == 0: break  # reached end of the stream

525 frames.append(buffer)

File c:\ProgramData\miniconda3\envs\lang\lib\site-packages\speech_recognition__init__.py:199, in Microphone.MicrophoneStream.read(self, size)

198 def read(self, size):

--> 199     return self.pyaudio_stream.read(size, exception_on_overflow=False)

File c:\ProgramData\miniconda3\envs\lang\lib\site-packages\pyaudio__init__.py:570, in PyAudio.Stream.read(self, num_frames, exception_on_overflow)

567 if not self._is_input:

568     raise IOError("Not input stream",

569                   paCanNotReadFromAnOutputOnlyStream)

--> 570 return pa.read_stream(self._stream, num_frames,

571                       exception_on_overflow)

KeyboardInterrupt:

```
聊天机器人（Chatbots）代码（Code）


代码理解 Code – LangChain中文网

用例（User Case)代码（Code）

代码理解 Code
概述 Code
LangChain是一个有用的工具，旨在解析GitHub代码仓库。通过利用VectorStores、Conversational RetrieverChain和GPT-4，它可以回答整个GitHub仓库中的问题或生成新代码。本文档页面概述了系统的基本组件，并指导使用LangChain来更好地理解代码、上下文问答和在GitHub仓库中生成代码。
会话检索链（Conversational RetrieverChain）
Conversational RetrieverChain是一个重点放在检索上的系统，它与存储在VectorStore中的数据进行交互。
利用先进技术，如上下文感知的过滤和排名，它检索与给定用户查询相关的最相关的代码片段和信息。
Conversational RetrieverChain旨在在考虑对话历史和上下文的情况下提供高质量、相关的结果。
用于代码理解和生成的LangChain工作流程

索引代码库：克隆目标存储库，加载其中的所有文件，对文件进行分块，然后执行索引过程。可选地，您可以跳过此步骤并使用已经建立索引的数据集。

嵌入和代码存储：使用具有代码感知的嵌入模型对代码片段进行嵌入，并将它们存储在VectorStore中。

查询理解：GPT-4处理用户查询，抓取上下文并提取相关细节。

构建检索器：Conversational RetrieverChain搜索VectorStore以识别给定查询的最相关代码片段。

构建会话链：根据需要自定义检索器设置并定义任何用户定义的过滤器。提出问题：定义要询问代码库的问题列表，然后使用ConversationalRetrievalChain生成上下文感知的答案。LLM (GPT-4) 基于检索到的代码片段和对话历史生成详细的、上下文感知的答案。

完整的教程如下。

使用Deep Lake分析Twitter算法代码库：一个演示如何解析github源代码并运行查询对话的教程。
使用Deep Lake分析LangChain代码库：一个演示如何分析并对这个代码库进行问答的教程。
Voice AssistantCode Analysis Deeplake


使用LangChain， GPT和Deep Lake 数据库，处理代码库# – LangChain中文网

用例（User Case)代码（Code）Code Analysis Deeplake

使用LangChain， GPT和Deep Lake 数据库，处理代码库#
在本教程中，我们将使用Langchain + Deep Lake和GPT，分析LangChain本身的代码库。
设计#

准备数据:

使用
```code
langchain.document_loaders.TextLoader
```
上传所有Python项目文件。 我们将这些文件称为文档。

使用
```code
langchain.text_splitter.CharacterTextSplitter
```
将所有文档分成块。

使用
```code
langchain.embeddings.openai.OpenAIEmbeddings
```
和
```code
langchain.vectorstores.DeepLake
```
嵌入这些块并上传到DeepLake。

问答:

使用
```code
langchain.chat_models.ChatOpenAI
```
和
```code
langchain.chains.ConversationalRetrievalChain
```
构建链。

准备问题。

运行链获得答案。

实现#
集成准备#
我们需要为外部服务设置密钥并安装必要的Python库。

```code
#!python3 -m pip install --upgrade langchain deeplake openai

```

设置OpenAI嵌入， Deep Lake 多模态向量存储API并进行身份验证。
有关Deep Lake的完整说明，请访问https://docs.activeloop.ai/和API参考https://docs.deeplake.ai/en/latest/ (opens in a new tab)

```code

import os

from getpass import getpass

os.environ['OPENAI_API_KEY'] = getpass()

# Please manually enter OpenAI Key

```

```code

········

```

如果您想创建自己的数据集并发布它，请在Deep Lake中进行身份验证。您可以从平台获得API密钥@[app.activeloop.ai]（https://app.activeloop.ai） (opens in a new tab)

```code

os.environ['ACTIVELOOP_TOKEN'] = getpass.getpass('Activeloop Token:')

```

```code

········

```

准备数据#
加载所有存储库文件。 在这里，我们假设此文档是作为langchain分支的一部分下载的，我们使用
```code
langchain
```
存储库的python文件工作。
如果要使用来自不同存储库的文件，请将
```code
root_dir
```
更改为您的存储库的根目录。

```code

from langchain.document_loaders import TextLoader

root_dir = '../../../..'

docs = []

for dirpath, dirnames, filenames in os.walk(root_dir):

for file in filenames:

if file.endswith('.py') and '/.venv/' not in dirpath:

try:

loader = TextLoader(os.path.join(dirpath, file), encoding='utf-8')

docs.extend(loader.load_and_split())

except Exception as e:

pass

print(f'{len(docs)}')

```

```code

1147

```

然后 块文件

```code

from langchain.text_splitter import CharacterTextSplitter

text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)

texts = text_splitter.split_documents(docs)

print(f"{len(texts)}")

```

```code

Created a chunk of size 1620, which is longer than the specified 1000

Created a chunk of size 1213, which is longer than the specified 1000

Created a chunk of size 1263, which is longer than the specified 1000

Created a chunk of size 1448, which is longer than the specified 1000

Created a chunk of size 1120, which is longer than the specified 1000

Created a chunk of size 1148, which is longer than the specified 1000

Created a chunk of size 1826, which is longer than the specified 1000

Created a chunk of size 1260, which is longer than the specified 1000

Created a chunk of size 1195, which is longer than the specified 1000

Created a chunk of size 2147, which is longer than the specified 1000

Created a chunk of size 1410, which is longer than the specified 1000

Created a chunk of size 1269, which is longer than the specified 1000

Created a chunk of size 1030, which is longer than the specified 1000

Created a chunk of size 1046, which is longer than the specified 1000

Created a chunk of size 1024, which is longer than the specified 1000

Created a chunk of size 1026, which is longer than the specified 1000

Created a chunk of size 1285, which is longer than the specified 1000

Created a chunk of size 1370, which is longer than the specified 1000

Created a chunk of size 1031, which is longer than the specified 1000

Created a chunk of size 1999, which is longer than the specified 1000

Created a chunk of size 1029, which is longer than the specified 1000

Created a chunk of size 1120, which is longer than the specified 1000

Created a chunk of size 1033, which is longer than the specified 1000

Created a chunk of size 1143, which is longer than the specified 1000

Created a chunk of size 1416, which is longer than the specified 1000

Created a chunk of size 2482, which is longer than the specified 1000

Created a chunk of size 1890, which is longer than the specified 1000

Created a chunk of size 1418, which is longer than the specified 1000

Created a chunk of size 1848, which is longer than the specified 1000

Created a chunk of size 1069, which is longer than the specified 1000

Created a chunk of size 2369, which is longer than the specified 1000

Created a chunk of size 1045, which is longer than the specified 1000

Created a chunk of size 1501, which is longer than the specified 1000

Created a chunk of size 1208, which is longer than the specified 1000

Created a chunk of size 1950, which is longer than the specified 1000

Created a chunk of size 1283, which is longer than the specified 1000

Created a chunk of size 1414, which is longer than the specified 1000

Created a chunk of size 1304, which is longer than the specified 1000

Created a chunk of size 1224, which is longer than the specified 1000

Created a chunk of size 1060, which is longer than the specified 1000

Created a chunk of size 2461, which is longer than the specified 1000

Created a chunk of size 1099, which is longer than the specified 1000

Created a chunk of size 1178, which is longer than the specified 1000

Created a chunk of size 1449, which is longer than the specified 1000

Created a chunk of size 1345, which is longer than the specified 1000

Created a chunk of size 3359, which is longer than the specified 1000

Created a chunk of size 2248, which is longer than the specified 1000

Created a chunk of size 1589, which is longer than the specified 1000

Created a chunk of size 2104, which is longer than the specified 1000

Created a chunk of size 1505, which is longer than the specified 1000

Created a chunk of size 1387, which is longer than the specified 1000

Created a chunk of size 1215, which is longer than the specified 1000

Created a chunk of size 1240, which is longer than the specified 1000

Created a chunk of size 1635, which is longer than the specified 1000

Created a chunk of size 1075, which is longer than the specified 1000

Created a chunk of size 2180, which is longer than the specified 1000

Created a chunk of size 1791, which is longer than the specified 1000

Created a chunk of size 1555, which is longer than the specified 1000

Created a chunk of size 1082, which is longer than the specified 1000

Created a chunk of size 1225, which is longer than the specified 1000

Created a chunk of size 1287, which is longer than the specified 1000

Created a chunk of size 1085, which is longer than the specified 1000

Created a chunk of size 1117, which is longer than the specified 1000

Created a chunk of size 1966, which is longer than the specified 1000

Created a chunk of size 1150, which is longer than the specified 1000

Created a chunk of size 1285, which is longer than the specified 1000

Created a chunk of size 1150, which is longer than the specified 1000

Created a chunk of size 1585, which is longer than the specified 1000

Created a chunk of size 1208, which is longer than the specified 1000

Created a chunk of size 1267, which is longer than the specified 1000

Created a chunk of size 1542, which is longer than the specified 1000

Created a chunk of size 1183, which is longer than the specified 1000

Created a chunk of size 2424, which is longer than the specified 1000

Created a chunk of size 1017, which is longer than the specified 1000

Created a chunk of size 1304, which is longer than the specified 1000

Created a chunk of size 1379, which is longer than the specified 1000

Created a chunk of size 1324, which is longer than the specified 1000

Created a chunk of size 1205, which is longer than the specified 1000

Created a chunk of size 1056, which is longer than the specified 1000

Created a chunk of size 1195, which is longer than the specified 1000

Created a chunk of size 3608, which is longer than the specified 1000

Created a chunk of size 1058, which is longer than the specified 1000

Created a chunk of size 1075, which is longer than the specified 1000

Created a chunk of size 1217, which is longer than the specified 1000

Created a chunk of size 1109, which is longer than the specified 1000

Created a chunk of size 1440, which is longer than the specified 1000

Created a chunk of size 1046, which is longer than the specified 1000

Created a chunk of size 1220, which is longer than the specified 1000

Created a chunk of size 1403, which is longer than the specified 1000

Created a chunk of size 1241, which is longer than the specified 1000

Created a chunk of size 1427, which is longer than the specified 1000

Created a chunk of size 1049, which is longer than the specified 1000

Created a chunk of size 1580, which is longer than the specified 1000

Created a chunk of size 1565, which is longer than the specified 1000

Created a chunk of size 1131, which is longer than the specified 1000

Created a chunk of size 1425, which is longer than the specified 1000

Created a chunk of size 1054, which is longer than the specified 1000

Created a chunk of size 1027, which is longer than the specified 1000

Created a chunk of size 2559, which is longer than the specified 1000

Created a chunk of size 1028, which is longer than the specified 1000

Created a chunk of size 1382, which is longer than the specified 1000

Created a chunk of size 1888, which is longer than the specified 1000

Created a chunk of size 1475, which is longer than the specified 1000

Created a chunk of size 1652, which is longer than the specified 1000

Created a chunk of size 1891, which is longer than the specified 1000

Created a chunk of size 1899, which is longer than the specified 1000

Created a chunk of size 1021, which is longer than the specified 1000

Created a chunk of size 1085, which is longer than the specified 1000

Created a chunk of size 1854, which is longer than the specified 1000

Created a chunk of size 1672, which is longer than the specified 1000

Created a chunk of size 2537, which is longer than the specified 1000

Created a chunk of size 1251, which is longer than the specified 1000

Created a chunk of size 1734, which is longer than the specified 1000

Created a chunk of size 1642, which is longer than the specified 1000

Created a chunk of size 1376, which is longer than the specified 1000

Created a chunk of size 1253, which is longer than the specified 1000

Created a chunk of size 1642, which is longer than the specified 1000

Created a chunk of size 1419, which is longer than the specified 1000

Created a chunk of size 1438, which is longer than the specified 1000

Created a chunk of size 1427, which is longer than the specified 1000

Created a chunk of size 1684, which is longer than the specified 1000

Created a chunk of size 1760, which is longer than the specified 1000

Created a chunk of size 1157, which is longer than the specified 1000

Created a chunk of size 2504, which is longer than the specified 1000

Created a chunk of size 1082, which is longer than the specified 1000

Created a chunk of size 2268, which is longer than the specified 1000

Created a chunk of size 1784, which is longer than the specified 1000

Created a chunk of size 1311, which is longer than the specified 1000

Created a chunk of size 2972, which is longer than the specified 1000

Created a chunk of size 1144, which is longer than the specified 1000

Created a chunk of size 1825, which is longer than the specified 1000

Created a chunk of size 1508, which is longer than the specified 1000

Created a chunk of size 2901, which is longer than the specified 1000

Created a chunk of size 1715, which is longer than the specified 1000

Created a chunk of size 1062, which is longer than the specified 1000

Created a chunk of size 1206, which is longer than the specified 1000

Created a chunk of size 1102, which is longer than the specified 1000

Created a chunk of size 1184, which is longer than the specified 1000

Created a chunk of size 1002, which is longer than the specified 1000

Created a chunk of size 1065, which is longer than the specified 1000

Created a chunk of size 1871, which is longer than the specified 1000

Created a chunk of size 1754, which is longer than the specified 1000

Created a chunk of size 2413, which is longer than the specified 1000

Created a chunk of size 1771, which is longer than the specified 1000

Created a chunk of size 2054, which is longer than the specified 1000

Created a chunk of size 2000, which is longer than the specified 1000

Created a chunk of size 2061, which is longer than the specified 1000

Created a chunk of size 1066, which is longer than the specified 1000

Created a chunk of size 1419, which is longer than the specified 1000

Created a chunk of size 1368, which is longer than the specified 1000

Created a chunk of size 1008, which is longer than the specified 1000

Created a chunk of size 1227, which is longer than the specified 1000

Created a chunk of size 1745, which is longer than the specified 1000

Created a chunk of size 2296, which is longer than the specified 1000

Created a chunk of size 1083, which is longer than the specified 1000

```

```code

3477

```

然后嵌入块并将它们上传到DeepLake。
Then embed chunks and upload them to the DeepLake.
This can take several minutes.

```code
from langchain.embeddings.openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()

embeddings

```

```code
OpenAIEmbeddings(client=<class 'openai.api_resources.embedding.Embedding'>, model='text-embedding-ada-002', document_model_name='text-embedding-ada-002', query_model_name='text-embedding-ada-002', embedding_ctx_length=8191, openai_api_key=None, openai_organization=None, allowed_special=set(), disallowed_special='all', chunk_size=1000, max_retries=6)

```

```code
from langchain.vectorstores import DeepLake

db = DeepLake.from_documents(texts, embeddings, dataset_path=f"hub://{DEEPLAKE_ACCOUNT_NAME}/langchain-code")

db

```

问答
首先加载数据集，构建检索器，然后再构建会话序列

```code
db = DeepLake(dataset_path=f"hub://{DEEPLAKE_ACCOUNT_NAME}/langchain-code", read_only=True, embedding_function=embeddings)

```

```code
-

```

```code
This dataset can be visualized in Jupyter Notebook by ds.visualize() or at https://app.activeloop.ai/user_name/langchain-code

```

```code
/

```

```code
hub://user_name/langchain-code loaded successfully.

```

```code
Deep Lake Dataset in hub://user_name/langchain-code already exists, loading from the storage

```

```code
Dataset(path='hub://user_name/langchain-code', read_only=True, tensors=['embedding', 'ids', 'metadata', 'text'])

tensor     htype      shape       dtype  compression

-------   -------    -------     -------  -------

embedding  generic  (3477, 1536)  float32   None

ids      text     (3477, 1)      str     None

metadata    json     (3477, 1)      str     None

text      text     (3477, 1)      str     None

```

```code
retriever = db.as_retriever()

retriever.search_kwargs['distance_metric'] = 'cos'

retriever.search_kwargs['fetch_k'] = 20

retriever.search_kwargs['maximal_marginal_relevance'] = True

retriever.search_kwargs['k'] = 20

```

您还可以使用Deep Lake过滤器 (opens in a new tab)指定用户定义的函数

```code
def filter(x):

# filter based on source code

if 'something' in x['text'].data()['value']:

return False

# filter based on path e.g. extension

metadata =  x['metadata'].data()['value']

return 'only_this' in metadata['source'] or 'also_that' in metadata['source']

### turn on below for custom filtering

# retriever.search_kwargs['filter'] = filter

```

```code
from langchain.chat_models import ChatOpenAI

from langchain.chains import ConversationalRetrievalChain

model = ChatOpenAI(model_name='gpt-3.5-turbo') # 'ada' 'gpt-3.5-turbo' 'gpt-4',

qa = ConversationalRetrievalChain.from_llm(model,retriever=retriever)

```

```code
questions = [

"What is the class hierarchy?",

# "What classes are derived from the Chain class?",

# "What classes and functions in the ./langchain/utilities/ forlder are not covered by unit tests?",

# "What one improvement do you propose in code in relation to the class herarchy for the Chain class?",

]

chat_history = []

for question in questions:

result = qa({"question": question, "chat_history": chat_history})

chat_history.append((question, result['answer']))

print(f"-> \*\*Question\*\*: {question} ")

print(f"\*\*Answer\*\*: {result['answer']} ")

```

-> 问题: 什么是类层次结构？
回答: 提供的代码中有几个类层次结构，以下是其中一些:
1.
```code
BaseModel
```
->
```code
ConstitutionalPrinciple
```
:
```code
ConstitutionalPrinciple
```
是
```code
BaseModel
```
的子类。

```code
BaseModel
```
->
```code
ConstitutionalPrinciple
```
:
```code
ConstitutionalPrinciple
```
is a subclass of
```code
BaseModel
```
.

```code
BasePromptTemplate
```
->
```code
StringPromptTemplate
```
，
```code
AIMessagePromptTemplate
```
，
```code
BaseChatPromptTemplate
```
，
```code
ChatMessagePromptTemplate
```
，
```code
ChatPromptTemplate
```
，
```code
HumanMessagePromptTemplate
```
，
```code
MessagesPlaceholder
```
，
```code
SystemMessagePromptTemplate
```
，
```code
FewShotPromptTemplate
```
，
```code
FewShotPromptWithTemplates
```
，
```code
Prompt
```
，
```code
PromptTemplate
```
# 所有这些类都是
```code
BasePromptTemplate
```
的子类。

```code
APIChain
```
，
```code
Chain
```
，
```code
MapReduceDocumentsChain
```
，
```code
MapRerankDocumentsChain
```
，
```code
RefineDocumentsChain
```
，
```code
StuffDocumentsChain
```
，
```code
HypotheticalDocumentEmbedder
```
，
```code
LLMChain
```
，
```code
LLMBashChain
```
，
```code
LLMCheckerChain
```
，
```code
LLMMathChain
```
，
```code
LLMRequestsChain
```
，
```code
PALChain
```
，
```code
QAWithSourcesChain
```
，
```code
VectorDBQAWithSourcesChain
```
，
```code
VectorDBQA
```
，
```code
SQLDatabaseChain
```
# 所有这些类都是
```code
Chain
```
的子类。

```code
BaseLoader
```
#
```code
BaseLoader
```
是
```code
ABC
```
的子类。

```code
BaseTracer
```
->
```code
ChainRun
```
，
```code
LLMRun
```
，
```code
SharedTracer
```
，
```code
ToolRun
```
，
```code
Tracer
```
，
```code
TracerException
```
，
```code
TracerSession
```
# 所有这些类都是
```code
BaseTracer
```
的子类。

```code
OpenAIEmbeddings
```
，
```code
HuggingFaceEmbeddings
```
，
```code
CohereEmbeddings
```
，
```code
JinaEmbeddings
```
，
```code
LlamaCppEmbeddings
```
，
```code
HuggingFaceHubEmbeddings
```
，
```code
TensorflowHubEmbeddings
```
，
```code
SagemakerEndpointEmbeddings
```
，
```code
HuggingFaceInstructEmbeddings
```
，
```code
SelfHostedEmbeddings
```
，
```code
SelfHostedHuggingFaceEmbeddings
```
，
```code
SelfHostedHuggingFaceInstructEmbeddings
```
，
```code
FakeEmbeddings
```
，
```code
AlephAlphaAsymmetricSemanticEmbedding
```
，
```code
AlephAlphaSymmetricSemanticEmbedding
```
# 所有这些类都是
```code
BaseLLM
```
的子类。

-> 问题# 有哪些类是从 Chain 类派生的？
答案# 有多个类从 Chain 类派生。其中一些是:

APIChain

AnalyzeDocumentChain

ChatVectorDBChain（聊天向量数据库链）

CombineDocumentsChain（合并文件链）

ConstitutionalChain（宪法链）

ConversationChain（对话链）

GraphQAChain（图形问答链）

HypotheticalDocumentEmbedder（假设文档嵌入器）

LLMChain（LLM链）

LLMCheckerChain（LLM检查链）

LLMRequestsChain（LLM请求链）

LLMSummarizationCheckerChain（LLM摘要检查链）

MapReduceChain（MapReduce链）

OpenAPIEndpointChain（OpenAPI端点链）

PALChain（PAL链）

QAWithSourcesChain（带源问答链）

RetrievalQA（检索问答）

RetrievalQAWithSourcesChain（带源检索问答链）

SequentialChain（顺序链）

SQLDatabaseChain（SQL数据库链）

TransformChain（转换链）

VectorDBQA（向量数据库问答）

VectorDBQAWithSourcesChain（带源向量数据库问答链）

可能会有更多派生自Chain类的类，因为可能创建自定义类来扩展Chain类。（There might be more classes that are derived from the Chain class as it is possible to create custom classes that extend the Chain class.）
-> 问题: 在./langchain/utilities/文件夹中，哪些类和函数没有被单元测试覆盖？（-> Question: What classes and functions in the ./langchain/utilities/ forlder are not covered by unit tests?）
Answer: All classes and functions in the
```code
./langchain/utilities/
```
folder seem to have unit tests written for them.代码（Code）Twitter the Algorithm Analysis Deeplake