Skip to main content
Bearly Code Interpreter 允许远程执行代码。这使其成为代理的代码沙箱的完美选择,可安全实现诸如代码解释器等功能。
在此处获取您的 API 密钥:bearly.ai/dashboard/developers
pip install -qU langchain-community
在本笔记本中,我们将创建一个使用 Bearly 与数据交互的代理示例。
from langchain_community.tools import BearlyInterpreterTool
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
初始化解释器。
bearly_tool = BearlyInterpreterTool(api_key="...")
让我们向沙箱添加一些文件。
bearly_tool.add_file(
    source_path="sample_data/Bristol.pdf", target_path="Bristol.pdf", description=""
)
bearly_tool.add_file(
    source_path="sample_data/US_GDP.csv", target_path="US_GDP.csv", description=""
)
现在创建一个 Tool 对象。这是必要的,因为我们添加了文件,并且我们希望工具描述能反映这一点。
tools = [bearly_tool.as_tool()]
tools[0].name
'bearly_interpreter'
print(tools[0].description)
在沙箱环境中评估 Python 代码。环境在每次执行时重置。您必须每次都发送整个脚本并打印输出。脚本应为可评估的纯 Python 代码。它应为 Python 格式,而不是 Markdown。代码不应用反引号包裹。所有 Python 包,包括 requests、matplotlib、scipy、numpy、pandas 等都可用。如果您有任何输出文件,请将它们写入执行路径相对的 "output/" 目录。输出只能从目录、stdout 和 stdin 读取。不要使用诸如 plot.show() 之类的东西,因为它不会起作用,而是将它们写入 `output/`,并将返回文件的链接。打印任何输出和结果,以便您可以捕获输出。

评估环境中可用的以下文件:
- 路径:`Bristol.pdf`
 前四行:[]
 描述:``
- 路径:`US_GDP.csv`
 前四行:['DATE,GDP\n', '1947-01-01,243.164\n', '1947-04-01,245.968\n', '1947-07-01,249.585\n']
 描述:``
初始化代理。
llm = ChatOpenAI(model="gpt-4", temperature=0)

agent = create_agent(
    model=llm,
    tools=tools,
)
# 提取 PDF 内容
agent.invoke("PDF 第 3 页的文本是什么?")
> 进入新的 AgentExecutor 链...

调用:`bearly_interpreter`,参数为 `{'python_code': "import PyPDF2\n\n# 以二进制读取模式打开 PDF 文件\npdf_file = open('Bristol.pdf', 'rb')\n\n# 创建 PDF 文件读取器对象\npdf_reader = PyPDF2.PdfFileReader(pdf_file)\n\n# 获取第 3 页的文本\npage_obj = pdf_reader.getPage(2)\npage_text = page_obj.extractText()\n\n# 关闭 PDF 文件\npdf_file.close()\n\nprint(page_text)"}`


{'stdout': '', 'stderr': 'Traceback (most recent call last):\n  File "/tmp/project/main.py", line 7, in <module>\n    pdf_reader = PyPDF2.PdfFileReader(pdf_file)\n  File "/venv/lib/python3.10/site-packages/PyPDF2/_reader.py", line 1974, in __init__\n    deprecation_with_replacement("PdfFileReader", "PdfReader", "3.0.0")\n  File "/venv/lib/python3.10/site-packages/PyPDF2/_utils.py", line 369, in deprecation_with_replacement\n    deprecation(DEPR_MSG_HAPPENED.format(old_name, removed_in, new_name))\n  File "/venv/lib/python3.10/site-packages/PyPDF2/_utils.py", line 351, in deprecation\n    raise DeprecationError(msg)\nPyPDF2.errors.DeprecationError: PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead.\n', 'fileLinks': [], 'exitCode': 1}
调用:`bearly_interpreter`,参数为 `{'python_code': "from PyPDF2 import PdfReader\n\n# 打开 PDF 文件\npdf = PdfReader('Bristol.pdf')\n\n# 获取第 3 页的文本\npage = pdf.pages[2]\npage_text = page.extract_text()\n\nprint(page_text)"}`


{'stdout': '1 COVID-19 at Work: \nExposing h ow risk is assessed and its consequences in England and Sweden \nPeter Andersson and Tonia Novitz* \n1.Introduction\nT\nhe crisis which arose suddenly at the beginning of 2020 relating to coronavirus was immediately \ncentred on risk. Predictions ha d to be made swiftly regarding how it would spread, who it might \naffect and what measures could be taken to prevent exposure in everyday so cial interaction, \nincluding in the workplace. This was in no way a straightforward assessment, because initially so \nmuch was unknown. Those gaps in our knowledge have since, partially, been ameliorated. It is \nevident that not all those exposed to COVID-19 become ill, and many who contract the virus remain \nasymptomatic, so that the odds on becoming seriously ill may seem small. But those odds are also stacked against certain segments of the population. The likelihood of mortality and morbidity are associated  with age and ethnicity as well as pre -existing medical conditions (such as diabetes), but \nalso with poverty which correlates to the extent of exposure in certain occupations.\n1 Some risks \narise which remain  less predictable, as previously healthy people with no signs of particular \nvulnerability can experience serious long term illness as well and in rare cases will even die.2 \nPerceptions of risk in different countries have led to particular measures taken, ranging from handwashing to social distancing, use of personal protective equipment (PPE) such as face coverings, and even ‘lockdowns’ which have taken various forms.\n3 Use of testing and vaccines \nalso bec ame part of the remedial landscape, with their availability and administration  being \n*This paper is part of the project An  i nclusive and sustainable Swedish labour law – the way\nahead, dnr. 2017-03134 financed by the Swedish research council led by Petra Herzfeld Olssonat Stockholm University. The authors would like to thank her and other participants, Niklas\nBruun and Erik Sjödin for their helpful comments on earlier drafts. A much shorter article titled\n‘Risk Assessment and COVID -19: Systems at work (or not) in England and Sweden’ is published\nin the (2021) Comparative Labour and Social Security Review /\n Revue de droit comparé du\ntravail et de la sécurité sociale.\n1 Public Health England, Disparities in the risk and outcomes of COVID-19 (2 June 2020 -\nhttps://assets.publishing.service.gov.uk/government/uploads/ system /uploads/attachment_data/file\n/890258/disparities_review.pdf.\n2 Nisreen A. Alwan, ‘Track COVID- 19 sickness, not just positive tests and deaths’ ( 2020)\n584.7820 Nature  170- 171; Elisabeth Mahase, ‘Covid-19: What do we know about “long covid”?’\n(2020) BMJ  370.\n3 Sarah Dryhurst, Claudia R. Schneider, John Kerr, Alexandra LJ Freeman, Gabriel Recchia,\nAnne Marthe Van Der Bles, David Spiegelhalter, and Sander van der Linden, ‘Risk perceptionsof COVID-19 around the world’ (2020) 23(7- 8) Journal of Risk Research  994; Wändi Bruine de\nBruin, and Daniel Bennett, ‘Relationships between initial COVID -19 risk perceptions and\nprotective health behaviors: A national survey’ (2020) 59(2) American Journal of Prev entive\nMedicine  157; and Simon Deakin and Gaofeng Meng, ‘The Governance of Covid- 19:\nAnthropogenic Risk, Evolutionary Learning, and the Future of the Social State’ (2020)49(4) Industrial Law Journal  539.\n', 'stderr': '', 'fileLinks': [], 'exitCode': 0}PDF 第 3 页的文本是:

"1 COVID-19 at Work:
Exposing how risk is assessed and its consequences in England and Sweden
Peter Andersson and Tonia Novitz*
1.Introduction
The crisis which arose suddenly at the beginning of 2020 relating to coronavirus was immediately
centred on risk. Predictions had to be made swiftly regarding how it would spread, who it might
affect and what measures could be taken to prevent exposure in everyday social interaction,
including in the workplace. This was in no way a straightforward assessment, because initially so
much was unknown. Those gaps in our knowledge have since, partially, been ameliorated. It is
evident that not all those exposed to COVID-19 become ill, and many who contract the virus remain
asymptomatic, so that the odds on becoming seriously ill may seem small. But those odds are also stacked against certain segments of the population. The likelihood of mortality and morbidity are associated  with age and ethnicity as well as pre-existing medical conditions (such as diabetes), but
also with poverty which correlates to the extent of exposure in certain occupations.
1 Some risks
arise which remain  less predictable, as previously healthy people with no signs of particular
vulnerability can experience serious long term illness as well and in rare cases will even die.2
Perceptions of risk in different countries have led to particular measures taken, ranging from handwashing to social distancing, use of personal protective equipment (PPE) such as face coverings, and even ‘lockdowns’ which have taken various forms.
3 Use of testing and vaccines
also became part of the remedial landscape, with their availability and administration  being
*This paper is part of the project An  inclusive and sustainable Swedish labour law – the way
ahead, dnr. 2017-03134 financed by the Swedish research council led by Petra Herzfeld Olssonat Stockholm University. The authors would like to thank her and other participants, Niklas
Bruun and Erik Sjödin for their helpful comments on earlier drafts. A much shorter article titled
‘Risk Assessment and COVID -19: Systems at work (or not) in England and Sweden’ is published
in the (2021) Comparative Labour and Social Security Review /
 Revue de droit comparé du
travail et de la sécurité sociale.
1 Public Health England, Disparities in the risk and outcomes of COVID-19 (2 June 2020 -
https://assets.publishing.service.gov.uk/government/uploads/ system /uploads/attachment_data/file
/890258/disparities_review.pdf.
2 Nisreen A. Alwan, ‘Track COVID- 19 sickness, not just positive tests and deaths’ ( 2020)
584.7820 Nature  170- 171; Elisabeth Mahase, ‘Covid-19: What do we know about “long covid”?’
(2020) BMJ  370.
3 Sarah Dryhurst, Claudia R. Schneider, John Kerr, Alexandra LJ Freeman, Gabriel Recchia,
Anne Marthe Van Der Bles, David Spiegelhalter, and Sander van der Linden, ‘Risk perceptionsof COVID-19 around the world’ (2020) 23(7- 8) Journal of Risk Research  994; Wändi Bruine de
Bruin, and Daniel Bennett, ‘Relationships between initial COVID -19 risk perceptions and
protective health behaviors: A national survey’ (2020) 59(2) American Journal of Preventive
Medicine  157; and Simon Deakin and Gaofeng Meng, ‘The Governance of Covid- 19:
Anthropogenic Risk, Evolutionary Learning, and the Future of the Social State’ (2020)49(4) Industrial Law Journal  539."

> 链结束。
'PDF 第 3 页的文本是:\n\n"1 COVID-19 at Work: \nExposing how risk is assessed and its consequences in England and Sweden \nPeter Andersson and Tonia Novitz* \n1.Introduction\nThe crisis which arose suddenly at the beginning of 2020 relating to coronavirus was immediately \ncentred on risk. Predictions had to be made swiftly regarding how it would spread, who it might \naffect and what measures could be taken to prevent exposure in everyday social interaction, \nincluding in the workplace. This was in no way a straightforward assessment, because initially so \nmuch was unknown. Those gaps in our knowledge have since, partially, been ameliorated. It is \nevident that not all those exposed to COVID-19 become ill, and many who contract the virus remain \nasymptomatic, so that the odds on becoming seriously ill may seem small. But those odds are also stacked against certain segments of the population. The likelihood of mortality and morbidity are associated  with age and ethnicity as well as pre-existing medical conditions (such as diabetes), but \nalso with poverty which correlates to the extent of exposure in certain occupations.\n1 Some risks \narise which remain  less predictable, as previously healthy people with no signs of particular \nvulnerability can experience serious long term illness as well and in rare cases will even die.2 \nPerceptions of risk in different countries have led to particular measures taken, ranging from handwashing to social distancing, use of personal protective equipment (PPE) such as face coverings, and even ‘lockdowns’ which have taken various forms.\n3 Use of testing and vaccines \nalso became part of the remedial landscape, with their availability and administration  being \n*This paper is part of the project An  inclusive and sustainable Swedish labour law – the way\nahead, dnr. 2017-03134 financed by the Swedish research council led by Petra Herzfeld Olssonat Stockholm University. The authors would like to thank her and other participants, Niklas\nBruun and Erik Sjödin for their helpful comments on earlier drafts. A much shorter article titled\n‘Risk Assessment and COVID -19: Systems at work (or not) in England and Sweden’ is published\nin the (2021) Comparative Labour and Social Security Review /\n Revue de droit comparé du\ntravail et de la sécurité sociale.\n1 Public Health England, Disparities in the risk and outcomes of COVID-19 (2 June 2020 -\nhttps://assets.publishing.service.gov.uk/government/uploads/ system /uploads/attachment_data/file\n/890258/disparities_review.pdf.\n2 Nisreen A. Alwan, ‘Track COVID- 19 sickness, not just positive tests and deaths’ ( 2020)\n584.7820 Nature  170- 171; Elisabeth Mahase, ‘Covid-19: What do we know about “long covid”?’\n(2020) BMJ  370.\n3 Sarah Dryhurst, Claudia R. Schneider, John Kerr, Alexandra LJ Freeman, Gabriel Recchia,\nAnne Marthe Van Der Bles, David Spiegelhalter, and Sander van der Linden, ‘Risk perceptionsof COVID-19 around the world’ (2020) 23(7- 8) Journal of Risk Research  994; Wändi Bruine de\nBruin, and Daniel Bennett, ‘Relationships between initial COVID -19 risk perceptions and\nprotective health behaviors: A national survey’ (2020) 59(2) American Journal of Preventive\nMedicine  157; and Simon Deakin and Gaofeng Meng, ‘The Governance of Covid- 19:\nAnthropogenic Risk, Evolutionary Learning, and the Future of the Social State’ (2020)49(4) Industrial Law Journal  539."'
# 简单查询
agent.invoke("2019 年美国 GDP 是多少?")
> 进入新的 AgentExecutor 链...

调用:`bearly_interpreter`,参数为 `{'python_code': "import pandas as pd\n\n# 加载数据\nus_gdp = pd.read_csv('US_GDP.csv')\n\n# 将 'DATE' 列转换为日期时间\nus_gdp['DATE'] = pd.to_datetime(us_gdp['DATE'])\n\n# 筛选 2019 年的数据\nus_gdp_2019 = us_gdp[us_gdp['DATE'].dt.year == 2019]\n\n# 打印 2019 年的 GDP\nprint(us_gdp_2019['GDP'].values)"}`


{'stdout': '[21104.133 21384.775 21694.282 21902.39 ]\n', 'stderr': '', 'fileLinks': [], 'exitCode': 0}2019 年每个季度的美国 GDP 如下:

- Q1:21104.133 亿美元
- Q2:21384.775 亿美元
- Q3:21694.282 亿美元
- Q4:21902.39 亿美元

> 链结束。
'2019 年每个季度的美国 GDP 如下:\n\n- Q1:21104.133 亿美元\n- Q2:21384.775 亿美元\n- Q3:21694.282 亿美元\n- Q4:21902.39 亿美元'
# 计算
agent.invoke("如果最新的 GDP 数字增长 50%,2030 年的 GDP 会是多少?")
> 进入新的 AgentExecutor 链...

调用:`bearly_interpreter`,参数为 `{'python_code': "import pandas as pd\n\n# 加载数据\nus_gdp = pd.read_csv('US_GDP.csv')\n\n# 获取最新的 GDP\nlatest_gdp = us_gdp['GDP'].iloc[-1]\n\n# 计算如果最新的 GDP 数字增长 50%,2030 年的 GDP\ngdp_2030 = latest_gdp * 1.5\nprint(gdp_2030)"}`


{'stdout': '40594.518\n', 'stderr': '', 'fileLinks': [], 'exitCode': 0}如果最新的 GDP 数字增长 50%,2030 年的 GDP 将约为 40,594.518 亿美元。

> 链结束。
'如果最新的 GDP 数字增长 50%,2030 年的 GDP 将约为 40,594.518 亿美元。'
# 图表输出
agent.invoke("创建一个带有标签的 GDP 随时间增长的漂亮图表")
> 进入新的 AgentExecutor 链...
无法解析工具输入:{'name': 'bearly_interpreter', 'arguments': '{\n  "python_code": "\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 加载数据\ndf = pd.read_csv(\'US_GDP.csv\')\n\n# 将 \'DATE\' 列转换为日期时间格式\ndf[\'DATE\'] = pd.to_datetime(df[\'DATE\'])\n\n# 绘制数据\nplt.figure(figsize=(10,6))\nplt.plot(df[\'DATE\'], df[\'GDP\'], label=\'US GDP\')\nplt.xlabel(\'Year\')\nplt.ylabel(\'GDP (in billions)\')\nplt.title(\'US GDP Over Time\')\nplt.legend()\nplt.grid(True)\nplt.savefig(\'output/US_GDP.png\')\n"\n}'} 因为 `arguments` 不是有效的 JSON。无效或不完整的响应
调用:`bearly_interpreter`,参数为 `{'python_code': "\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 加载数据\ndf = pd.read_csv('US_GDP.csv')\n\n# 将 'DATE' 列转换为日期时间格式\ndf['DATE'] = pd.to_datetime(df['DATE'])\n\n# 绘制数据\nplt.figure(figsize=(10,6))\nplt.plot(df['DATE'], df['GDP'], label='US GDP')\nplt.xlabel('Year')\nplt.ylabel('GDP (in billions)')\nplt.title('US GDP Over Time')\nplt.legend()\nplt.grid(True)\nplt.savefig('output/US_GDP.png')\n"}`


{'stdout': '', 'stderr': '', 'fileLinks': [{'pathname': 'US_GDP.png', 'tempLink': 'https://bearly-cubby.c559ae877a0a39985f534614a037d899.r2.cloudflarestorage.com/prod/bearly-cubby/temp/interpreter/2023_10/089daf37e9e343ba5ff21afaaa78b967c3466a550b3b11bd5c710c052b559e97/sxhM8gop2AYP88n5uHCsOJ6yTYNQm-HimZ70DcwQ4VI.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=c058d02de50a3cf0bb7e21c8e2d062c5%2F20231010%2F%2Fs3%2Faws4_request&X-Amz-Date=20231010T000000Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=104dc0d4a4b71eeea1030dda1830059920cb0f354fa00197b439eb8565bf141a', 'size': 34275}], 'exitCode': 0}这是美国 GDP 随时间增长的图表:

![US GDP Over Time](https://bearly-cubby.c559ae877a0a39985f534614a037d899.r2.cloudflarestorage.com/prod/bearly-cubby/temp/interpreter/2023_10/089daf37e9e343ba5ff21afaaa78b967c3466a550b3b11bd5c710c052b559e97/sxhM8gop2AYP88n5uHCsOJ6yTYNQm-HimZ70DcwQ4VI.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=c058d02de50a3cf0bb7e21c8e2d062c5%2F20231010%2F%2Fs3%2Faws4_request&X-Amz-Date=20231010T000000Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=104dc0d4a4b71eeea1030dda1830059920cb0f354fa00197b439eb8565bf141a)

x 轴代表年份,y 轴代表 GDP(以十亿美元计)。折线图显示了美国 GDP 随时间的增长。

> 链结束。
'这是美国 GDP 随时间增长的图表:\n\n![US GDP Over Time](https://bearly-cubby.c559ae877a0a39985f534614a037d899.r2.cloudflarestorage.com/prod/bearly-cubby/temp/interpreter/2023_10/089daf37e9e343ba5ff21afaaa78b967c3466a550b3b11bd5c710c052b559e97/sxhM8gop2AYP88n5uHCsOJ6yTYNQm-HimZ70DcwQ4VI.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=c058d02de50a3cf0bb7e21c8e2d062c5%2F20231010%2F%2Fs3%2Faws4_request&X-Amz-Date=20231010T000000Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=104dc0d4a4b71eeea1030dda1830059920cb0f354fa00197b439eb8565bf141a)\n\nx 轴代表年份,y 轴代表 GDP(以十亿美元计)。折线图显示了美国 GDP 随时间的增长。'