### Install Dependencies with Pip Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot/examples/retrieval_function_call/README.md Installs project dependencies by navigating to the example directory and running pip install with the requirements.txt file. Requires Python version 3.8 or higher. ```shell cd examples/retrieval_function_call pip install -r requirements.txt ``` -------------------------------- ### Initialize ERNIE Bot LangChain Components Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/how_to_use_langchain_extension.ipynb Setup the environment by installing dependencies, configuring the access token, and initializing the ErnieBot LLM component. ```python !pip install erniebot-agent langchain import getpass from erniebot_agent.extensions.langchain.llms import ErnieBot access_token = getpass.getpass(prompt="Access token: ") llm = ErnieBot(aistudio_access_token=access_token) ``` -------------------------------- ### Quick Start ERNIE Bot Agent Application (Python) Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/README.md Demonstrates how to quickly build an agent application using ERNIE Bot Agent. This example initializes an ERNIEBot model, retrieves a text-to-speech tool, creates a FunctionAgent, and interacts with it through general conversation and tool invocation. It also shows how to save the generated audio to a file. Requires setting an AI Studio Access Token as an environment variable. ```python import asyncio from erniebot_agent.agents import FunctionAgent from erniebot_agent.chat_models import ERNIEBot from erniebot_agent.tools import RemoteToolkit async def main(): llm = ERNIEBot(model="ernie-3.5") # Initialize large language model tts_tool = RemoteToolkit.from_aistudio("texttospeech").get_tools() # Get speech synthesis tool agent = FunctionAgent(llm=llm, tools=tts_tool) # Create agent, integrating language model and tools # General conversation with the agent result = await agent.run("你好,请自我介绍一下") print(result.text) # Model returns something like: # 你好,我叫文心一言,是百度研发的知识增强大语言模型,能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。 # Request the agent to automatically call the speech synthesis tool based on input text result = await agent.run("把上一轮的自我介绍转成语音") print(result.text) # Model returns something like: # 根据你的请求,我已经将自我介绍转换为语音文件,文件名为file-local-c70878b4-a3f6-11ee-95d0-506b4b225bd6。 # 你可以使用任何支持播放音频文件的设备或软件来播放这个文件。如果你需要进一步操作或有其他问题,请随时告诉我。 # Write the agent's output audio file to test.wav, you can try playing it audio_file = result.steps[-1].output_files[0] await audio_file.write_contents_to("./test.wav") asyncio.run(main()) ``` -------------------------------- ### ERNIE Bot Agent LangChain Plugin Setup Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/how_to_use_langchain_extension.ipynb This section covers the installation of the necessary libraries and the setup for authentication using an access token. ```APIDOC ## Installation and Authentication ### Description Install the ERNIE Bot Agent and LangChain libraries, and obtain your AI Studio access token for authentication. ### Installation ```python !pip install erniebot-agent langchain ``` ### Authentication Follow the [ERNIE Bot Authentication Documentation](https://github.com/PaddlePaddle/ERNIE-SDK/blob/develop/docs/authentication.md) to get your AI Studio access token. Then, use the following code to securely input your token: ```python import getpass access_token = getpass.getpass(prompt="Access token: ") ``` ``` -------------------------------- ### Install ERNIE Bot SDK from Source Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/sdk/installation.md Installs the ERNIE Bot Python SDK from its source code repository. This involves cloning the repository, navigating into the directory, and then installing the package. ```shell git clone https://github.com/PaddlePaddle/ERNIE-SDK cd ERNIE-SDK pip install --upgrade setuptools pip install . ``` -------------------------------- ### Serve Tools using ToolManager in Python Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/remote_tool.ipynb Demonstrates how to initialize and run a ToolManager to serve a collection of custom tools. The ToolManager starts a web server (using Uvicorn) that exposes the defined tools, making them accessible for agent interactions. This example serves AddWordTool and GetWordsTool on port 8021. ```python from erniebot_agent.tools.tool_manager import ToolManager from threading import Thread tool_manager = ToolManager([AddWordTool(), GetWordsTool()]) thread = Thread(target=tool_manager.serve, args=(8021,)) thread.daemon = True thread.start() ``` -------------------------------- ### LocalTool: CurrentTimeTool Example Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/tools.md Example implementation of a LocalTool for getting the current time, including input/output parameter definitions and tool logic. ```APIDOC ## LocalTool: CurrentTimeTool Example ### Description This section details the implementation of `CurrentTimeTool`, a `LocalTool` designed to retrieve the current date and time. It demonstrates how to define input/output parameters using `ToolParameterView`, provide descriptive information for the Agent, implement the core logic in the `__call__` method, and include conversational examples. ### Method N/A (This is a class definition, not an API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Code Structure ```python from datetime import datetime from typing import Dict, Type, List from erniebot_agent.tools import Tool, ToolParameterView from erniebot_agent.message import HumanMessage, AIMessage from pydantic import Field class CurrentTimeToolOutputView(ToolParameterView): current_time: str = Field(description="当前时间") class CurrentTimeTool(Tool): description: str = "CurrentTimeTool 用于获取当前时间" output_type: Type[ToolParameterView] = CurrentTimeToolOutputView async def __call__(self) -> Dict[str, str]: return {"current_time": datetime.strftime(datetime.now(), "%Y年%m月%d日 %H时%M分%S秒")} @property def examples(self) -> List[Message]: return [ HumanMessage("现在几点钟了"), AIMessage( "", function_call={ "name": self.tool_name, "thoughts": f"用户想知道现在几点了,我可以使用{self.tool_name}来获取当前时间,并从其中获得当前小时时间。", "arguments": "{}", }, token_usage={"prompt_tokens": 5, "completion_tokens": 7}, # For test only ), HumanMessage("现在是什么时候?"), AIMessage( "", function_call={ "name": self.tool_name, "thoughts": f"用户想知道现在几点了,我可以使用{self.tool_name}来获取当前时间", "arguments": "{}", }, token_usage={"prompt_tokens": 5, "completion_tokens": 7}, # For test only ), ] ``` ``` -------------------------------- ### Install Dependencies Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/langchain_function_agent_with_retrieval.ipynb Installs the necessary LangChain library required for the agent functionality. ```shell !pip install langchain ``` -------------------------------- ### Executing Agent Steps with Tools Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/function_agent.ipynb Demonstrates how an agent executes steps, which involve calling specific tools with arguments and processing input/output files. This example shows an OCR tool followed by a chat tool and a word addition tool. ```python response.steps ``` ``` Result: [ToolStep(info={'tool_name': 'highacc-ocr/v1.8/OCR', 'tool_args': '{"image":"file-local-4ea15200-a569-11ee-a73d-56c70f692df9","language_type":"ENG"}'}, result='{"words_result": ["BEWARE", "OF FALLING", "COCONUTS"], "words_result_num": 3}', input_files=[], output_files=[]), ToolStep(info={'tool_name': 'ChatWithEB', 'tool_args': '{"word":"BEWARE"}'}, result='{"response": "<单词翻译>: 当心、小心\n\n<近义词>: Careful, Cautious, Wary, Alert\n\n<反义词>: Reckless, Careless, Negligent, Unmindful\n\n<例句>:\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\n2. You should always beware of scams when shopping online. (在网上购物时,你应该始终小心诈骗。)\n3. Beware of the icy road, it\'s very slippery. (小心结冰的路面,非常滑。)\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时,要小心蛇和其他野生动物。)\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)"}', input_files=[], output_files=[]), ToolStep(info={'tool_name': 'AddWordTool', 'tool_args': '{"word":"BEWARE","des":"<单词翻译>: 当心、小心\n\n<近义词>: Careful, Cautious, Wary, Alert\n\n<反义词>: Reckless, Careless, Negligent, Unmindful\n\n<例句>:\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\n2. You should always beware of scams when shopping online. (在网上购物时,你应该始终小心诈骗。)\n3. Beware of the icy road, it\'s very slippery. (小心结冰的路面,非常滑。)\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时,要小心蛇和其他野生动物。)\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)"}'}, result='{"result": "单词已添加成功, 当前单词本中有如下单词:BEWARE,释义如下<单词翻译>: 当心、小心\n\n<近义词>: Careful, Cautious, Wary, Alert\n\n<反义词>: Reckless, Careless, Negligent, Unmindful\n\n<例句>:\n1. Beware of dogs when you enter the park. (当你进入公园时要小心狗。)\n2. You should always beware of scams when shopping online. (在网上购物时,你应该始终小心诈骗。)\n3. Beware of the icy road, it\'s very slippery. (小心结冰的路面,非常滑。)\n4. When hiking in the woods, beware of snakes and other wildlife. (在树林里徒步旅行时,要小心蛇和其他野生动物。)\n5. Beware of opening email attachments from unknown sources. (小心打开来自未知来源的电子邮件附件。)"}', input_files=[], output_files=[])] ``` -------------------------------- ### Configure and Create Remote File using GlobalFileManagerHandler Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/file.md This example illustrates how to enable remote file handling by configuring the GlobalFileManagerHandler with `enable_remote_file=True` and an access token. It then shows how to create a remote File object from a path. ```python async def demo_function(): # 需要在事件循环最开始配置,打开远程文件开关,注意需配置access token GlobalFileManagerHandler().configure(enable_remote_file=True) ... # 此处省略一些其他的中间过程 # 获取全局的FileManager,通过它来创建RemoteFile file_manager = GlobalFileManagerHandler().get() # 从文件路径创建File, file_type可选择local或者remote,file_path需要具体到文件名,此处为remote的示例 remote_file = file_manager.create_file_from_path(file_path='your_file_path', file_type='remote') # 获取File的id,用于以后的查找 print(remote_file.id) ``` -------------------------------- ### Install FastAPI Dependency Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/remote_tool.ipynb Installs the FastAPI framework, which is used for building the RESTful API service in this example. FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. ```python !pip install fastapi ``` -------------------------------- ### Install ERNIE SDK via Shell Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/README.md Commands to install the ERNIE Bot Agent and its dependencies. Users can choose between source installation or quick installation via pip. ```shell git clone https://github.com/PaddlePaddle/ERNIE-SDK.git cd ERNIE-SDK pip install ./erniebot pip install ./erniebot-agent # Alternatively for quick install: pip install --upgrade erniebot-agent[all] ``` -------------------------------- ### Clone ERNIE-SDK and Install Dependencies Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/applications/eb-agent-qa-bot/README.md This bash script demonstrates how to clone the ERNIE-SDK repository from GitHub and install the necessary ernie_agent Python package. This is the first step in setting up the ERNIE Bot Agent QA Bot. ```bash git clone https://github.com/PaddlePaddle/ERNIE-SDK.git cd ERNIE-SDK pip install ernie_agent ``` -------------------------------- ### Install ERNIE Bot Function Calling Dependencies Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot/examples/function_calling/README.md Commands to set up the environment for the function calling demo. Requires Python 3.8 or higher. ```shell cd examples/function_calling pip install -r requirements.txt ``` -------------------------------- ### Initialize Function Agent for Multi-turn Dialogue Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/agents.md Demonstrates how to instantiate a FunctionAgent without tools and perform multi-turn conversations using a memory component. This setup allows the agent to maintain context across multiple interactions. ```python from erniebot_agent.agents import FunctionAgent from erniebot_agent.chat_models import ERNIEBot from erniebot_agent.memory import WholeMemory agent = FunctionAgent(llm=ERNIEBot(model="ernie-3.5"), tools=[], memory=WholeMemory()) response = await agent.run("你好,小度!") print(response.text) response = await agent.run("我刚刚怎么称呼你?") for message in response.chat_history: print(message.content) ``` -------------------------------- ### Configure GlobalFileManagerHandler for Agent Use Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/file.md This example shows how to configure the GlobalFileManagerHandler with a save directory, which is useful when integrating file management with Agents. It also demonstrates how to retrieve output files from an Agent's response. ```python from erniebot_agent.file import GlobalFileManagerHandler async def demo_function(): GlobalFileManagerHandler().configure(save_dir='your_path') # 需要在事件循环最开始配置 ... # 此处省略agent创建过程 response = await agent.async_run('请帮我画一张北京市的图') # 您可以通过AgentResponse.steps[-1]获取agent的最后一个步骤,然后最后一步的输出文件;或者在save_dir中找到所有文件 files = response.steps[-1].output_files ``` -------------------------------- ### Listing and Managing Agent Tools Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/function_agent.ipynb Shows how to retrieve a list of all available tools for the agent, get a specific tool by name, and unload or load tools. ```python # 获取当前所有工具 agent_all.get_tools() ``` ``` Result: [, , ] ``` ```python # 查找某个工具 eb_tool = agent_all.get_tool("ChatWithEB") # 取消某个工具 agent_all.unload_tool(eb_tool) # 加载某个工具 agent_all.load_tool(eb_tool) ``` ``` -------------------------------- ### ERNIEBot - Text Completion Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/chat_models.md This example demonstrates how to perform text completion using the ERNIEBot class. It shows both a standard response and a streaming response. ```APIDOC ## ERNIEBot - Text Completion ### Description This example demonstrates how to perform text completion using the ERNIEBot class. It shows both a standard response and a streaming response. ### Method `chat` method of `ERNIEBot` class ### Endpoint N/A (This is a client-side SDK usage example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **messages** (List[BaseMessage]) - Required - A list of messages representing the conversation history. - **stream** (bool) - Optional - If True, the response will be streamed. ### Request Example ```python import os import asyncio from erniebot_agent.chat_models import ERNIEBot from erniebot_agent.memory import HumanMessage os.environ["EB_AGENT_ACCESS_TOKEN"] = "your access token" async def demo(): model = ERNIEBot(model="ernie-3.5") human_message = HumanMessage(content='你好,你是谁') ai_message = await model.chat(messages=[human_message]) print(ai_message.content, '\n') human_message = HumanMessage(content='推荐三个深圳有名的景点') ai_message = await model.chat(messages=[human_message], stream=True) # 流式返回 async for chunk in ai_message: print(chunk.content, end='') asyncio.run(demo()) ``` ### Response #### Success Response (200) - **content** (str) - The response from the AI model. #### Response Example ``` 你好,我是百度公司开发的人工智能语言模型,我的中文名是文心一言,英文名是ERNIE Bot。如果您有任何问题,请随时向我提问。 深圳有许多著名的景点,以下是三个推荐景点: 1. 深圳世界之窗 2. 深圳欢乐谷 3. 深圳东部华侨城 ``` ``` -------------------------------- ### Implement a LocalTool Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/tools.md Demonstrates how to create a custom LocalTool by inheriting from the Tool class and implementing the asynchronous __call__ method. It includes defining output schemas using ToolParameterView and providing usage examples. ```python class CurrentTimeToolOutputView(ToolParameterView): current_time: str = Field(description="当前时间") class CurrentTimeTool(Tool): description: str = "CurrentTimeTool 用于获取当前时间" output_type: Type[ToolParameterView] = CurrentTimeToolOutputView async def __call__(self) -> Dict[str, str]: return {"current_time": datetime.strftime(datetime.now(), "%Y年%m月%d日 %H时%M分%S秒")} @property def examples(self) -> List[Message]: return [ HumanMessage("现在几点钟了"), AIMessage( "", function_call={ "name": self.tool_name, "thoughts": f"用户想知道现在几点了,我可以使用{self.tool_name}来获取当前时间,并从其中获得当前小时时间。", "arguments": "{}", }, token_usage={"prompt_tokens": 5, "completion_tokens": 7}, ), ] ``` -------------------------------- ### RemoteTool Execution Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/tools.md Example of how to get a specific RemoteTool from a toolkit and execute it. ```APIDOC ## RemoteTool Execution ### Description Once a `RemoteToolkit` is initialized, individual `RemoteTool` instances can be retrieved and executed. A `RemoteTool` corresponds to a specific API defined in the OpenAPI specification and is responsible for invoking that API, typically via a RESTful request. ### Method N/A (This section describes class methods for execution) ### Endpoint N/A ### Parameters N/A ### Request Example ```python # Assuming 'toolkit' is an initialized RemoteToolkit instance tool = toolkit.get_tool("moderation") result = await tool("”欢迎使用 ERNIE-Bot Agent“这句话是否含有政治敏感内容") ``` ### Response #### Success Response (200) - **result** (any) - The result returned by the remote API call. #### Response Example ```json { "example": "The result of the tool execution, e.g., a JSON object or string" } ``` ``` -------------------------------- ### Initialize ERNIE SDK and Generate Data Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot/examples/cookbook/10-Data-Generation.ipynb Sets up the ERNIE SDK with API credentials and defines functions to interact with AI models. It retrieves user reviews for various Baidu products and processes the raw output into a usable format. ```python import erniebot, os, math, time from typing import List erniebot.api_type = "aistudio" erniebot.access_token = "" def transform_list(s): md_content = s.split("```")[1] md_content = md_content[md_content.find("\n") :] md_content = md_content.replace("\n", "").replace(" ", "") return md_content[md_content.find("[") :] def get_data(query: str) -> str: chat_message = [{"role": "user", "content": f"{query},结果请用python的列表返回"}] response = erniebot.ChatCompletion.create(model="ernie-4.0", messages=chat_message) return eval(transform_list(response.get_result())) wenxin_reviews = get_data("请帮我生成二十条关于百度文心一言产品的用户评论") map_reviews = get_data("请帮我生成二十条关于百度地图的用户评论") wenku_reviews = get_data("请帮我生成二十条关于百度网盘的用户评论") trans_reviews = get_data("请帮我生成二十条关于百度翻译的用户评论") ``` -------------------------------- ### Loading and Using RemoteToolkits in Python Source: https://context7.com/paddlepaddle/ernie-sdk/llms.txt Demonstrates how to load and use RemoteToolkits from AI Studio, URLs, or local OpenAPI files. It shows initializing an agent with tools from a toolkit and calling individual tools. ```python import asyncio from erniebot_agent.agents import FunctionAgent from erniebot_agent.chat_models import ERNIEBot from erniebot_agent.tools import RemoteToolkit async def main(): # 从AI Studio加载远程工具集 toolkit = RemoteToolkit.from_aistudio("text-moderation") agent = FunctionAgent( llm=ERNIEBot(model="ernie-3.5"), tools=toolkit.get_tools() ) response = await agent.run(""欢迎使用ERNIE-Bot-Agent"这句话合规吗?") print(response.text) # 加载多个工具集 ocr_toolkit = RemoteToolkit.from_aistudio("pp-ocrv4") tts_toolkit = RemoteToolkit.from_aistudio("texttospeech") agent = FunctionAgent( llm=ERNIEBot(model="ernie-3.5"), tools=[*ocr_toolkit.get_tools(), *tts_toolkit.get_tools()] ) # 从URL加载自定义远程工具 # toolkit = RemoteToolkit.from_url("http://127.0.0.1:8000") # 从本地OpenAPI文件加载 # toolkit = RemoteToolkit.from_openapi_file("./openapi.yaml") # 获取工具集中的特定工具 tool = toolkit.get_tool("moderation") result = await tool("检查这段文字是否合规") print(result) asyncio.run(main()) ``` -------------------------------- ### Chat Completion with System Prompt Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot/examples/cookbook/01-Chat-Completion.ipynb Demonstrates how to use a `system` prompt to guide the AI's persona and conversational style. In this example, the AI is instructed to respond as Elon Musk. ```python chat_message = [{"role": "user", "content": "你好"}] response = erniebot.ChatCompletion.create( system="假设你是马斯克,请用马斯克的语气和用户进行对话", model="ernie-4.0", messages=chat_message, ) print(response.get_result()) ``` -------------------------------- ### RemoteToolkit Initialization Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/tools.md Demonstrates how to initialize a RemoteToolkit using different methods: from AI Studio, from a URL, or from a local OpenAPI file. ```APIDOC ## RemoteToolkit Initialization ### Description The `RemoteToolkit` class allows for the initialization of toolkits from remote sources. This is useful for integrating external tools defined using the OpenAPI specification. Initialization can be done via AI Studio's tool ID, a URL pointing to an OpenAPI YAML file, or a local OpenAPI YAML file. ### Method N/A (This section describes class methods for initialization) ### Endpoint N/A ### Parameters N/A ### Request Example ```python # Initialize from AI Studio tool ID toolkit_from_aistudio = RemoteToolkit.from_aistudio("text-moderation") # Initialize from a URL toolkit_from_url = RemoteToolkit.from_url("http://www.xxx.com/well-known/openapi.yaml") # Initialize from a local OpenAPI file toolkit_from_file = RemoteToolkit.from_openapi_file("/path/to/your/openapi.yaml") ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Start Local Demo Service with ERNIE Bot Credentials Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot/examples/retrieval_function_call/README.md Launches a local demonstration service for the ERNIE Bot application. It requires ERNIE Bot API and secret keys, specifies the paths to the documents for indexing, and sets the port for the Gradio demo. Optional parameters control retrieval settings and indexing. ```python python demo.py \ --api_key \ --secret_key \ --file_paths construction_regulations \ --port 8081 ``` -------------------------------- ### Quick Install ERNIE Bot Agent (Python) Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/README.md Installs the latest version of ERNIE Bot Agent using pip. Supports installing the core module or all modules including extra dependencies like Gradio. Requires Python 3.8+. ```shell # Install core module pip install --upgrade erniebot-agent # Install all modules pip install --upgrade erniebot-agent[all] ``` -------------------------------- ### Run the Function Calling Demo Application Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot/examples/function_calling/README.md Commands to launch the Gradio-based web interface. Supports an optional port argument to customize the server address. ```shell python function_calling_demo.py # Or with a custom port: python function_calling_demo.py --port 8188 ``` -------------------------------- ### Install ERNIE Bot Agent Source: https://context7.com/paddlepaddle/ernie-sdk/llms.txt Installs the ERNIE Bot Agent core module or all modules including optional dependencies like gradio. ```bash # Install core module pip install --upgrade erniebot-agent # Install all modules (including gradio etc.) pip install --upgrade erniebot-agent[all] ``` -------------------------------- ### Install ERNIE Bot SDK Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/sdk/README.md Installs the latest version of the ERNIE Bot SDK using pip. Requires Python version 3.8 or higher. ```shell pip install --upgrade erniebot ``` -------------------------------- ### Manage Files in Agent Workflows Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/agents.md Demonstrates how to download a file, register it with the GlobalFileManagerHandler, pass it to an agent, and retrieve output files generated by tools. ```python async with aiohttp.ClientSession() as session: async with session.get("https://paddlenlp.bj.bcebos.com/ebagent/ci/fixtures/remote-tools/ocr_example_input.png") as response: with open("example.png", "wb") as f: f.write(await response.read()) file_manager = GlobalFileManagerHandler().get() input_file = await file_manager.create_file_from_path("example.png") response = await agent.run("请识别这张图片中的文字。", files=[input_file]) output_files = response.steps[0].output_files await output_files[0].write_contents_to("output.wav") ``` -------------------------------- ### Install ERNIE Bot Agent SDK Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/introduction.md Installs the latest version of the ERNIE Bot Agent SDK using pip. Requires Python version 3.8 or higher. ```shell pip install --upgrade erniebot-agent ``` -------------------------------- ### Initialize Environment and Imports Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/langchain_function_agent_with_retrieval.ipynb Imports essential libraries for RAG implementation and configures the access token for the ERNIEBot agent. ```python import os from erniebot_agent.agents.function_agent_with_retrieval import FunctionAgentWithRetrieval from erniebot_agent.memory.whole_memory import WholeMemory from erniebot_agent.chat_models.erniebot import ERNIEBot from langchain.text_splitter import SpacyTextSplitter from langchain.vectorstores import FAISS from langchain.document_loaders import PyPDFDirectoryLoader from erniebot_agent.extensions.langchain.embeddings import ErnieEmbeddings from sklearn.metrics.pairwise import cosine_similarity from erniebot_agent.tools import RemoteToolkit os.environ["EB_AGENT_ACCESS_TOKEN"] = "your access token" ``` -------------------------------- ### ERNIE Bot Function Calling Example Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/sdk/README.md This example demonstrates how to use the ernie-3.5 model for function calling. The model identifies when to call the 'get_current_temperature' function based on the user's query and provides structured arguments. ```APIDOC ## POST /ernie-bot/function-calling ### Description This endpoint allows you to utilize ERNIE Bot's function calling feature. The large model can determine when and how to call functions based on the conversation context, enabling you to retrieve structured data and integrate the model with your internal or external APIs. ### Method POST ### Endpoint (This is a conceptual endpoint for the function calling feature, actual implementation might vary based on the SDK) ### Parameters #### Request Body - **model** (string) - Required - The name of the ERNIE Bot model to use (e.g., "ernie-3.5"). - **messages** (array) - Required - A list of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender ('user' or 'assistant'). - **content** (string) - Required - The content of the message. - **functions** (array) - Optional - A list of function definitions that the model can call. - **name** (string) - Required - The name of the function. - **description** (string) - Optional - A description of what the function does. - **parameters** (object) - Required - The parameters the function accepts. - **type** (string) - Required - The type of the parameters (usually "object"). - **properties** (object) - Required - An object defining the properties of the parameters. - **param_name** (object) - Required - Definition of a specific parameter. - **type** (string) - Required - The data type of the parameter (e.g., "string", "integer", "boolean"). - **description** (string) - Optional - A description of the parameter. - **enum** (array) - Optional - A list of allowed values for the parameter. - **required** (array) - Optional - A list of parameter names that are required. - **responses** (object) - Optional - The expected structure of the function's response. - **type** (string) - Required - The type of the response (usually "object"). - **properties** (object) - Required - An object defining the properties of the response. - **field_name** (object) - Required - Definition of a specific response field. - **type** (string) - Required - The data type of the response field. - **description** (string) - Optional - A description of the response field. - **enum** (array) - Optional - A list of allowed values for the response field. - **stream** (boolean) - Optional - Whether to stream the response. Defaults to false. ### Request Example ```python import erniebot erniebot.api_type = "aistudio" erniebot.access_token = "" response = erniebot.ChatCompletion.create( model="ernie-3.5", messages=[ { "role": "user", "content": "深圳市今天气温多少摄氏度?", }, ], functions=[ { "name": "get_current_temperature", "description": "获取指定城市的气温", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名称", }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度", ], }, }, "required": [ "location", "unit", ], }, "responses": { "type": "object", "properties": { "temperature": { "type": "integer", "description": "城市气温", }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度", ], }, }, }, }, ], stream=False) print(response.get_result()) ``` ### Response #### Success Response (200) - **result** (string) - The result of the function call or the model's response. #### Response Example (Example response will vary based on the model's output and function execution. It might contain the function call details or the final answer.) ```json { "result": "{\"thought\": \"用户想知道深圳市今天气温多少摄氏度,我需要调用get_current_temperature函数来获取信息。\", \"func_call\": {\"name\": \"get_current_temperature\", \"arguments\": \"{\\\"location\\\": \\\"深圳市\\\", \\\"unit\\\": \\\"摄氏度\\\"}\", \"response\": {\"temperature\": 25, \"unit\": \"摄氏度\"}}}" } ``` ``` -------------------------------- ### Install ERNIE Bot Agent from Source (Python) Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/README.md Installs ERNIE Bot Agent and its core module from source code. Requires Python version 3.8 or higher. This method is useful for development or when needing the latest unreleased features. ```shell git clone https://github.com/PaddlePaddle/ERNIE-SDK.git cd ERNIE-SDK pip install ./erniebot pip install ./erniebot-agent # Install core module # pip install './erniebot-agent/.[all]' # Install all modules including gradio dependencies ``` -------------------------------- ### Initialize and Use BaizhongSearch for Retrieval Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/retrieval.md Demonstrates how to connect to an AI Studio knowledge base using BaizhongSearch and perform a search query. This involves initializing the BaizhongSearch object with a knowledge base ID and then calling the search method with a query string. ```python knowledge_base_id = baizhong_db = BaizhongSearch(knowledge_base_id=knowledge_base_id) baizhong_db.search('百度今天的股价是多少?') ``` -------------------------------- ### GET /tools/current_time Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/tools_intro.ipynb Retrieves the current system time using the CurrentTimeTool. ```APIDOC ## GET /tools/current_time ### Description Retrieves the current date and time formatted as a string. ### Method GET (via CurrentTimeTool.__call__) ### Endpoint N/A (Local Tool) ### Parameters None ### Request Example await current_time_tool() ### Response #### Success Response (200) - **current_time** (string) - The formatted current date and time. #### Response Example { "current_time": "2023年12月28日 16时57分37秒" } ``` -------------------------------- ### Using LocalTool with ERNIE Bot Agent Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/quickstart/use-tool.md Demonstrates how to initialize a FunctionAgent with a built-in LocalTool, specifically the CurrentTimeTool, to retrieve real-time information. It requires the erniebot_agent library and an asynchronous execution environment. ```python import asyncio from erniebot_agent.agents import FunctionAgent from erniebot_agent.chat_models import ERNIEBot from erniebot_agent.tools.current_time_tool import CurrentTimeTool async def main(): agent = FunctionAgent(llm=ERNIEBot(model="ernie-3.5"), tools=[CurrentTimeTool()]) result = await agent.run("现在北京时间是什么时候?") print(result.text) asyncio.run(main()) ``` -------------------------------- ### ERNIEBot - Multi-turn Conversation Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/docs/modules/chat_models.md This example demonstrates how to conduct multi-turn conversations with the ERNIEBot, maintaining context across multiple exchanges. ```APIDOC ## ERNIEBot - Multi-turn Conversation ### Description This example demonstrates how to conduct multi-turn conversations with the ERNIEBot, maintaining context across multiple exchanges. The previous turn's messages are passed to the next `chat` call. ### Method `chat` method of `ERNIEBot` class ### Endpoint N/A (This is a client-side SDK usage example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **messages** (List[BaseMessage]) - Required - A list of messages representing the conversation history, including previous user and AI messages. ### Request Example ```python import os import asyncio from erniebot_agent.chat_models import ERNIEBot from erniebot_agent.memory import HumanMessage os.environ["EB_AGENT_ACCESS_TOKEN"] = "your access token" async def demo(): model = ERNIEBot(model="ernie-3.5") messages = [] messages.append(HumanMessage(content='推荐三个深圳有名的景点')) ai_message = await model.chat(messages=messages) messages.append(ai_message) print(ai_message.content, '\n') messages.append(HumanMessage(content='根据你推荐的景点,帮我做一份一日游的攻略')) ai_message = await model.chat(messages=messages) messages.append(ai_message) print(ai_message.content, '\n') asyncio.run(demo()) ``` ### Response #### Success Response (200) - **content** (str) - The response from the AI model, considering the conversation history. #### Response Example ``` 深圳有很多有名的景点,以下是三个推荐的景点: 1. **深圳世界之窗**: 2. **深圳欢乐谷**: 3. **深圳东部华侨城**: 好的,以下是一份深圳一日游的攻略: 早上: * 早上9点左右到达深圳世界之窗。首先可以参观非洲区的莫高窟、埃塞俄比亚院及四大文明古国馆,了解不同文化的历史和特点。 * 然后可以前往亚洲区的比萨斜塔、悉尼歌剧院等著名建筑,感受不同国家的建筑风格和文化内涵。 * 接着可以参观欧洲区的罗马斗兽场、白宫等著名景点,了解不同国家的政治、历史和文化。 中午: * 在世界之窗内的餐厅享用午餐,品尝当地美食。 下午: * 下午可以前往深圳欢乐谷,游览各种刺激和好玩的游乐设施。可以先体验一下高速过山车、云霄飞车等刺激的项目,然后再尝试其他的游乐设施。 * 可以选择在欢乐谷内游玩一整个下午,尽情享受游乐园的乐趣。 晚上: * 晚上可以选择在东部华侨城内度过。可以先去温泉浴场放松一下身心,然后再去主题公园欣赏各种表演和娱乐活动。 ``` ``` -------------------------------- ### Build an AI Agent with ERNIE Bot Agent Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/README.md Demonstrates how to initialize an ERNIEBot model, integrate remote tools like text-to-speech, and execute tasks using a FunctionAgent. ```python import asyncio from erniebot_agent.agents import FunctionAgent from erniebot_agent.chat_models import ERNIEBot from erniebot_agent.tools import RemoteToolkit async def main(): llm = ERNIEBot(model="ernie-3.5") tts_tool = RemoteToolkit.from_aistudio("texttospeech").get_tools() agent = FunctionAgent(llm=llm, tools=tts_tool) result = await agent.run("你好,请自我介绍一下") print(result.text) result = await agent.run("把上一轮的自我介绍转成语音") audio_file = result.steps[-1].output_files[0] await audio_file.write_contents_to("./test.wav") asyncio.run(main()) ``` -------------------------------- ### Initialize ERNIE SDK Client Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot/examples/cookbook/01-Chat-Completion.ipynb Sets up the authentication and API type for the ERNIE SDK. This is a prerequisite for making any API calls. ```python import erniebot, os erniebot.api_type = "aistudio" erniebot.access_token = "" ``` -------------------------------- ### Instantiate and Use CurrentTimeTool (Python) Source: https://github.com/paddlepaddle/ernie-sdk/blob/develop/erniebot-agent/cookbook/tools_intro.ipynb Demonstrates how to instantiate the CurrentTimeTool and call its asynchronous function to retrieve the current time. This tool is essential for agents that need to access real-time information. ```python from erniebot_agent.tools.current_time_tool import CurrentTimeTool current_time_tool = CurrentTimeTool() await current_time_tool() ```