Skip to main content
Open In ColabOpen on GitHub

Robocorp 工具包

这个笔记本介绍了如何使用Robocorp Action Server动作工具包和LangChain。

Robocorp 是将自定义操作扩展到 AI 代理、助手和副驾的最简单方式。

安装

首先,查看Robocorp Quickstart以了解如何设置Action Server并创建您的动作。

在您的LangChain应用程序中,安装langchain-robocorp包:

# Install package
%pip install --upgrade --quiet langchain-robocorp

按照上述快速入门,在创建新的Action Server时。

这将创建一个包含文件的目录,包括action.py

我们可以将Python函数作为操作添加,如这里所示。

让我们在action.py中添加一个占位函数。

@action
def get_weather_forecast(city: str, days: int, scale: str = "celsius") -> str:
"""
Returns weather conditions forecast for a given city.

Args:
city (str): Target city to get the weather conditions for
days: How many day forecast to return
scale (str): Temperature scale to use, should be one of "celsius" or "fahrenheit"

Returns:
str: The requested weather conditions forecast
"""
return "75F and sunny :)"

然后启动服务器:<br/>

action-server start

And we can see:

Found new action: get_weather_forecast

通过访问运行在http://localhost:8080的服务器并在UI中运行函数来本地测试。

环境设置

可以设置以下环境变量(可选):

  • LANGSMITH_TRACING=true: 为启用 LangSmith 日志记录运行跟踪,这些日志也可以绑定到相应的 Action Server 动作运行日志。更多详情请参见 LangSmith 文档

用法

我们已在上方启动了本地动作服务器,运行在 http://localhost:8080

from langchain.agents import AgentExecutor, OpenAIFunctionsAgent
from langchain_core.messages import SystemMessage
from langchain_openai import ChatOpenAI
from langchain_robocorp import ActionServerToolkit

# Initialize LLM chat model
llm = ChatOpenAI(model="gpt-4", temperature=0)

# Initialize Action Server Toolkit
toolkit = ActionServerToolkit(url="http://localhost:8080", report_trace=True)
tools = toolkit.get_tools()

# Initialize Agent
system_message = SystemMessage(content="You are a helpful assistant")
prompt = OpenAIFunctionsAgent.create_prompt(system_message)
agent = OpenAIFunctionsAgent(llm=llm, prompt=prompt, tools=tools)

executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

executor.invoke("What is the current weather today in San Francisco in fahrenheit?")


> Entering new AgentExecutor chain...

Invoking: `robocorp_action_server_get_weather_forecast` with `{'city': 'San Francisco', 'days': 1, 'scale': 'fahrenheit'}`


"75F and sunny :)"The current weather today in San Francisco is 75F and sunny.

> Finished chain.
{'input': 'What is the current weather today in San Francisco in fahrenheit?',
'output': 'The current weather today in San Francisco is 75F and sunny.'}

单输入工具

默认情况下,toolkit.get_tools()将返回作为结构化工具的动作。

要返回单个输入工具,请传递一个聊天模型以处理这些输入。

# Initialize single input Action Server Toolkit
toolkit = ActionServerToolkit(url="http://localhost:8080")
tools = toolkit.get_tools(llm=llm)