Giter VIP home page Giter VIP logo

paddlepaddle / ernie-sdk Goto Github PK

View Code? Open in Web Editor NEW
304.0 10.0 41.0 3.34 MB

ERNIE Bot Agent is a Large Language Model (LLM) Agent Framework, powered by the advanced capabilities of ERNIE Bot and the platform resources of Baidu AI Studio.

Home Page: http://ernie-bot-agent.readthedocs.io/

License: Apache License 2.0

Python 23.56% Jupyter Notebook 76.41% Makefile 0.03%
chatcompletion embedding ernie-bot function-calling sdk agent llm

ernie-sdk's People

Contributors

bobholamovic avatar jiangjiajun avatar juncaipeng avatar qingzhong1 avatar shiyutang avatar sijunhe avatar southpika avatar w5688414 avatar wj-mcat avatar zeyuchen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ernie-sdk's Issues

我想知道怎么微调它。

如题,我真的很想知道,可以Lora微调吗,数据集格式是什么样。
我打算在对话中调用文生图功能,这个可以训练吧。

官方提供的remote tool识别ocr报错

相关代码如下:
file_manager = GlobalFileManagerHandler().get()
file = await file_manager.create_file_from_path("road_sign.jpeg")
response = await agent_all.run("帮我把图片中的第一个英语单词进行解释之后添加到单词本中", files=[file])
print(response.text)

报错信息如下:
function_call:
{
"name": "highacc-ocr/v1.8/OCR",
"thoughts": "图片格式错误,我需要重新调用OCR工具来提取图片中的文字。",
"arguments": "{"image":"file-local-e8215a4a-ba5b-11ee-95be-ac1f6bb32462","language_type":"auto_detect"}"
}
INFO - [Tool][Start] RemoteTool is about to start running with input:
{
"image": "file-local-e8215a4a-ba5b-11ee-95be-ac1f6bb32462",
"language_type": "auto_detect"
}
INFO - [Tool][End] RemoteTool finished running with output:
{
"error_msg": "image format error",
"error_code": 216201
}
更换了好几张图片都是报这个错误

请问能够接入其他的模型吗?

看docs上现在是只能用文心一言?能不能用本地的chatglm或者是openai的接口呀?

感谢回复🙏目前的使用体验感真的很棒❤️~

请问一下运行retrieval_function_call的时候报错是什么原因

pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'pandas.core.frame.DataFrame'>. Set arbitrary_types_allowed=True in the model_config to ignore this error or implement __get_pydantic_core_schema__ on your type to fully support it.

If you got this error by calling handler() within __get_pydantic_core_schema__ then you likely need to call handler.generate_schema(<some type>) since we do not call __get_pydantic_core_schema__ on <some type> otherwise to avoid infinite recursion.

For further information visit https://errors.pydantic.dev/2.6/u/schema-for-unknown-type
在配置完环境之后运行demo报出如上错误

按教程写代码。报错

chat_completion = erniebot.ChatCompletion.create(model="ernie-bot-3.5", messages=[{"role": "user", "content": "你好,请介绍下你自己"}])

print(chat_completion.result)

19 # Create a chat completion
---> 20 chat_completion = erniebot.ChatCompletion.create(model="ernie-bot-3.5", messages=[{"role": "user", "content": "你好,请介绍下你自己"}])
22 print(chat_completion.result)

File /opt/conda/lib/python3.9/site-packages/erniebot/resources/abc/creatable.py:39, in Creatable.create(cls, **create_kwargs)
28 @classmethod
29 def create(cls,
30 **create_kwargs: Any) -> Union[EBResponse, Iterator[EBResponse]]:
31 """Create a new resource.
32
33 Args:
(...)
37 Response from the server.
38 """
---> 39 resource = cls.new_object()
40 return resource.create_resource(**create_kwargs)

File /opt/conda/lib/python3.9/site-packages/erniebot/resources/resource.py:68, in EBResource.new_object(cls, **kwargs)
66 @classmethod
67 def new_object(cls, **kwargs: Any) -> Self:
---> 68 return cls(**kwargs)

File /opt/conda/lib/python3.9/site-packages/erniebot/resources/resource.py:55, in EBResource.init(self, **kwargs)
54 def init(self, **kwargs: Any) -> None:
---> 55 super().init()
57 self._cfg = self._create_config_dict(**kwargs)
59 self.api_type = self._cfg['api_type']

File /opt/conda/lib/python3.9/typing.py:1083, in _no_init(self, *args, **kwargs)
1082 def _no_init(self, *args, **kwargs):
-> 1083 raise TypeError('Protocols cannot be instantiated')

TypeError: Protocols cannot be instantiated

README中关于提取语义向量部分,示例代码有误

运行环境

erniebot 0.3.1
python 3.10

运行代码

import erniebot

erniebot.api_type = 'aistudio'
erniebot.access_token = '<access-token-for-aistudio>'

response = erniebot.Embedding.create(
    model='ernie-text-embedding',
    input=[
        "我是百度公司开发的人工智能语言模型,我的中文名是文心一言,英文名是ERNIE-Bot,可以协助您完成范围广泛的任务并提供有关各种主题的信息,比如回答问题,提供定义和解释及建议。如果您有任何问题,请随时向我提问。",
        "2018年深圳市各区GDP"
        ])

print(response.get_result())

报错信息

(py310) ➜  ✗ python test_erniebot.py
Traceback (most recent call last):
  File "/Users/xxxx/opt/miniconda3/envs/py310/lib/python3.10/site-packages/erniebot/response.py", line 120, in __getattr__
    val = self.__dict[key]
KeyError: 'get_result'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/xxxx/projects/Knowledge-QA-LLM/test_erniebot.py", line 36, in <module>
    print(response.get_result())
  File "/Users/xxxx/opt/miniconda3/envs/py310/lib/python3.10/site-packages/erniebot/response.py", line 123, in __getattr__
    raise AttributeError
AttributeError

[Enhancement] using jsonref to parse oepnapi.yaml

jsonref lets you use a data structure with JSON reference objects, as if the references had been replaced with the referent data.

>>> from pprint import pprint
>>> import jsonref

>>> # An example json document
>>> json_str = """{"real": [1, 2, 3, 4], "ref": {"$ref": "#/real"}}"""
>>> data = jsonref.loads(json_str)
>>> pprint(data)  # Reference is not evaluated until here
{'real': [1, 2, 3, 4], 'ref': [1, 2, 3, 4]}

refer to:

运行question_bot.py报错请问是哪里出问题了,安装了langchain-community依然报错

E:\jupyter\ERNIE-SDK\py311\Scripts\python.exe E:\jupyter\ERNIE-SDK\erniebot-agent\applications\eb-agent-qa-bot\question_bot.py --init=True --access-token xxxxxxxxxxxxxxxxxxxxxxxxxxxx
0%| | 0/8 [00:00<?, ?it/s]
Traceback (most recent call last):
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\auth.py", line 85, in upsert_auth_token
auth_token = token_requestor()
^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\auth.py", line 172, in _request_auth_token
raise RuntimeError("Invalid API key or secret key")
RuntimeError: Invalid API key or secret key

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "E:\jupyter\ERNIE-SDK\erniebot-agent\applications\eb-agent-qa-bot\question_bot.py", line 99, in
agent = load_agent()
^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\erniebot-agent\applications\eb-agent-qa-bot\question_bot.py", line 67, in load_agent
init_db(faiss_name, faiss_name_module, embeddings)
File "E:\jupyter\ERNIE-SDK\erniebot-agent\applications\eb-agent-qa-bot\init_vector_db.py", line 93, in init_db
content_doc = load_md_files_to_doc(md_file_path, chunk_size, chunk_overlap)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\erniebot-agent\applications\eb-agent-qa-bot\init_vector_db.py", line 75, in load_md_files_to_doc
splits[i].page_content = get_summary(splits[i].page_content)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\erniebot-agent\applications\eb-agent-qa-bot\init_vector_db.py", line 24, in get_summary
summary = erniebot.ChatCompletion.create(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\resources\chat_completion.py", line 261, in create
resp = resource.create_resource(**kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\resources\abc\creatable.py", line 67, in create_resource
resp = self.request(
^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\resources\resource.py", line 144, in request
for attempt in retrying:
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\tenacity_init_.py", line 347, in iter
do = self.iter(retry_state=retry_state)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\tenacity_init_.py", line 314, in iter
return fut.result()
^^^^^^^^^^^^
File "C:\Users\ThinkPad\AppData\Local\Programs\Python\Python311\Lib\concurrent\futures_base.py", line 449, in result
return self.__get_result()
^^^^^^^^^^^^^^^^^^^
File "C:\Users\ThinkPad\AppData\Local\Programs\Python\Python311\Lib\concurrent\futures_base.py", line 401, in __get_result
raise self._exception
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\resources\resource.py", line 146, in request
return self._request(
^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\resources\resource.py", line 340, in _request
resp = self._backend.request(
^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\backends\bce.py", line 71, in request
access_token = self._auth_manager.get_auth_token()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\auth.py", line 113, in get_auth_token
self._token = self._init_auth_token()
^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\auth.py", line 137, in _init_auth_token
token = self._update_cache(init=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\auth.py", line 144, in _update_cache
token, upserted = self._cache.upsert_auth_token(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\jupyter\ERNIE-SDK\py311\Lib\site-packages\erniebot\auth.py", line 87, in upsert_auth_token
raise errors.TokenUpdateFailedError from e
erniebot.errors.TokenUpdateFailedError

智能体需要多次执法FC,而在文心返回结果中只有一个FC及其相关参数

智能体已经判断出需要执行两个FC:get_current_temperature,get_current_swing.(这需要我调用'get_current_temperature'和'get_current_swing'工具)
但在返回结果中只有一个FC:
name': 'get_current_temperature', 'arguments': '{"location":"深圳","unit":"摄氏度"}
第二个需要执行的FC没有返回结果,应该如何处理?
如下:
env3.10) [root@localhost Langchain-Chatchat-2.6]# /home/env3.10/bin/python3.10 /home/env3.10/Langchain-Chatchat-2.6/erniebot/agent_tool.py
{'name': 'get_current_temperature', 'thoughts': "用户想要知道深圳市今天的天气情况,以及是否适合进行户外活动。这需要我调用'get_current_temperature'和'get_current_swing'工具。任务拆解:[sub-task1: 使用[get_current_temperature]获取深圳市今天的温度,sub-task2: 使用[get_current_swing]获取深圳市今天的风力]。接下来需要调用[get_current_temperature]工具来获取深圳市今天的温度信息。", 'arguments': '{"location":"深圳","unit":"摄氏度"}'}
2024-03-13 14:39:45,271 - _client.py[line:1013] - INFO: HTTP Request: GET http://10.74.1.13:8020/get_current_temperature1?city=%E5%8C%97%E4%BA%AC&unit=%E6%91%84%E6%B0%8F%E5%BA%A6 "HTTP/1.1 200 OK"
根据您提供的信息,深圳市今天的温度为20摄氏度。这个温度对于户外活动来说是比较适宜的,但具体是否适合还需要考虑其他因素,如风力、降水等。如果您需要更详细的信息,建议查询当地的天气预报或咨询相关专业人士。希望这个回答能对您有所帮助。

星河社区的token(令牌)采用智能体包中的ERNIEBot访问时报[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')(在Aistudio中调用是正常的)

星河社区的token(令牌)采用智能体包中的(from erniebot_agent.chat_models import ERNIEBot)ERNIEBot访问时报[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')错误。而采用erniebot包时正常。
代码:
os.environ["EB_AGENT_LOGGING_LEVEL"] = "INFO" # 这个是日志包
os.environ["EB_AGENT_ACCESS_TOKEN"] = "********" # 这是星河社区的token(令牌)输入你自己的token
async def func():
ai_message = await model.chat(messages=messages)
print(ai_message.content)

asyncio.run(func())
错误:
/home/ernie/bin/python /home/ernie/erniebot/2.py
Traceback (most recent call last):
File "/home/ernie/lib/python3.10/site-packages/aiohttp/connector.py", line 992, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs)
File "/home/zhougx/python3.10/lib/python3.10/asyncio/base_events.py", line 1089, in create_connection
transport, protocol = await self._create_connection_transport(
File "/home/zhougx/python3.10/lib/python3.10/asyncio/base_events.py", line 1119, in _create_connection_transport
await waiter
File "/home/zhougx/python3.10/lib/python3.10/asyncio/sslproto.py", line 534, in data_received
ssldata, appdata = self._sslpipe.feed_ssldata(data)
File "/home/zhougx/python3.10/lib/python3.10/asyncio/sslproto.py", line 188, in feed_ssldata
self._sslobj.do_handshake()
File "/home/zhougx/python3.10/lib/python3.10/ssl.py", line 975, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)

调用文本转图像的demo出错

请教下,这个报错是啥原因?erniebot最新版本以及早点的版本都试过,一样的报错
python 版本:3.9.7,windows下。
示例程序:
`import erniebot

erniebot.api_type = "yinian"
erniebot.access_token = "***************"

response = erniebot.Image.create(model="ernie-vilg-v2", prompt="请帮我画一只可爱的大猫咪", width=512, height=512, version="v2", image_num=1)

print(response)

img_url = response["data"]["sub_task_result_list"][0]["final_image_list"][0]["img_url"]
print(img_url)
print(response)`

运行时报错:
Exception has occurred: HTTPRequestError
Unexpected content type: 'text/html; charset=utf-8'
Response:
code: 200
body: '<title>热门问题-技术问答-百度开发者中心-汇聚开放、助力、共赢</title><link rel="preload" href="https://bce.bdstatic.com/developer-server/online/_next/static/css/7ea58671f4422d96f12a.css" ...

请求对agents的文档和使用说明进行补全

根据代码可以观察到erniebot-agent/src/erniebot_agent/agents/agent.py已经支持了system的参数,因此Agent[class]具有角色扮演的基础功能。

希望可以补全该模块的文档,并将角色扮演作为预制方法或样例。

请求完成上述需求。

可以在XAgent中调用ernie-bot-4吗?

如题,我知道是可以的,但是遇到一些问题,报错:KeyError: 'Could not automatically map ernie-bot-4 to a tokeniser. Please use tiktoken.get_encoding to explicitly get the tokeniser you expect.
需要提供模型的分词器给XAgent以支持Context管理功能,但是我不知道该怎么做,不太懂代码。
XAgent中的utils.py代码部分有:
from enum import Enum, unique
import abc
from colorama import Fore, Style
import json
import requests
from dataclasses import dataclass, field
from typing import List, Dict
import tiktoken
from XAgent.config import CONFIG

encoding = tiktoken.encoding_for_model(CONFIG.default_completion_kwargs['model'])

def get_token_nums(text:str)->int:
return len(encoding.encode(text))

def clip_text(text:str,max_tokens:int=None,clip_end=False)->str|int:
encoded = encoding.encode(text)
decoded = encoding.decode(encoded[:max_tokens] if clip_end else encoded[-max_tokens:])
if len(decoded) != len(text):
decoded = decoded + 'wrapped' if clip_end else 'wrapped' + decoded
return decoded, len(encoded)

@unique
class LLMStatusCode(Enum):
SUCCESS = 0
ERROR = 1

@unique
class ToolCallStatusCode(Enum):
TOOL_CALL_FAILED = -1
TOOL_CALL_SUCCESS = 0
FORMAT_ERROR = 1
HALLUCINATE_NAME = 2
OTHER_ERROR = 3
TIMEOUT_ERROR = 4
TIME_LIMIT_EXCEEDED = 5
SERVER_ERROR = 6
是需要克隆ernie-bot-sdk?还是需要下载paddlepaddle,还是paddleNLP。我以为仅仅需要API就可以的。。。。

自定义 Remote Tool,FastAPI 的web 服务

官方提供的代码:
image
服务可以起来,信息如下:
INFO: Started server process [66580]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8020 (Press CTRL+C to quit)
INFO: 127.0.0.1:49190 - "GET /.well-known/openapi.yaml HTTP/1.1" 200 OK
INFO: 10.10.58.119:36570 - "GET /.well-known/openapi.yaml HTTP/1.1" 200 OK

但是通过官方提供这段代码调用,失败了:
image
失败信息如下:
toolkit = RemoteToolkit.from_url("http://127.0.0.1:8020") # 必须存在:http://xxx.com/.well-known/openapi.yaml
File "/home/envs/Paddle/lib/python3.8/site-packages/erniebot_agent/tools/remote_toolkit.py", line 295, in from_url
toolkit = RemoteToolkit.from_openapi_file(
File "/home/envs/Paddle/lib/python3.8/site-packages/erniebot_agent/tools/remote_toolkit.py", line 229, in from_openapi_file
return cls.from_openapi_dict(
File "/home/envs/Paddle/lib/python3.8/site-packages/erniebot_agent/tools/remote_toolkit.py", line 175, in from_openapi_dict
info = EndpointInfo(**openapi_dict["info"])
TypeError: init() missing 1 required positional argument: 'description'

faiss升级faiss.swigfaiss.IndexFlatIP改为faiss.IndexFlatIP

文件erniebot/examples/quick_start/gradio_demo.py

运行报错:module 'faiss' has no attribute 'swigfaiss'

解决方法:因faiss升级,将原代码中的“faiss.swigfaiss.IndexFlatIP“修改为“faiss.IndexFlatIP“

位置:

query: str, origin_chunk: List[str], index_ip: faiss.swigfaiss.IndexFlatIP, top_k: int = 5

index_ip (faiss.swigfaiss.IndexFlatIP): Vector DB index。

RemoteToolkit.from_url("http://127.0.0.1:8020")读取openapi.yaml成功,但解析时报错。

通过FastAPI定义了接口,发布了.well-known/openapi.yaml。其中
"openapi": "3.1.0",
"info": {
"title": "FastAPI",
"version": "0.1.0"
},
......
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail"
}
},
"type": "object",
"title": "HTTPValidationError"
},

但通过RemoteToolkit.from_url("http://127.0.0.1:8020") 时报以下错误:

Traceback (most recent call last):
File "/home/ernie/erniebot/4.py", line 114, in
toolkit = RemoteToolkit.from_url("http://127.0.0.1:8020") # 必须存在:http://xxx.com/.well-known/openapi.yaml
File "/home/ernie/lib/python3.10/site-packages/erniebot_agent/tools/remote_toolkit.py", line 305, in from_url
toolkit = RemoteToolkit.from_openapi_dict(
File "/home/ernie/lib/python3.10/site-packages/erniebot_agent/tools/remote_toolkit.py", line 185, in from_openapi_dict
parameter_view = ToolParameterView.from_openapi_dict(schema)
File "/home/ernie/lib/python3.10/site-packages/erniebot_agent/tools/schema.py", line 252, in from_openapi_dict
field_type = python_type_from_json_type(field_dict)
File "/home/ernie/lib/python3.10/site-packages/erniebot_agent/tools/schema.py", line 108, in python_type_from_json_type
assert "type" in json_type_dict["items"], " field must be defined when 'type'=array"
AssertionError: field must be defined when 'type'=array

function call出了正确结果了,但是最后一步模型回答的还是错误的答案。

按照官方的erniebot-agent/cookbook/local_tool.ipynb,改了一个天气查询的demo,明明function call出了正确的结果,但是最后一步模型回答的还是错误的答案。

from __future__ import annotations
import os
os.environ["EB_AGENT_LOGGING_LEVEL"] = "DEBUG"
os.environ['EB_AGENT_ACCESS_TOKEN'] = 'xxx'

import asyncio

from typing import Any, Dict, Type, List
from pydantic import Field
from erniebot_agent.tools.base import Tool
from erniebot_agent.tools.schema import ToolParameterView
from erniebot_agent.agents.function_agent import FunctionAgent
from erniebot_agent.chat_models import ERNIEBot
from erniebot_agent.memory import WholeMemory

class WeatherInput(ToolParameterView):
    location: str = Field(description="要查询天气的地点")

class WeatherOutput(ToolParameterView):
    result: str = Field(description="查询天气的结果")

class WeatherTool(Tool):
    description: str = "查询某地天气,返回结果"
    input_type: Type[ToolParameterView] = WeatherInput
    ouptut_type: Type[ToolParameterView] = WeatherOutput

    def __init__(self) -> None:
        super().__init__()

    async def __call__(self, location: str) -> Dict[str, Any]:
        return location + '多云,25-30度'
    
agent = FunctionAgent(ERNIEBot("ernie-3.5"), tools=[WeatherTool()], memory=WholeMemory())
result =  asyncio.run(agent.run("今天北京天气怎么样?"))
print(result)

结果:
image

APIError: 访问过于频繁,请稍候再试

调用 ErnieEmbeddings,提示 “APIError: 访问过于频繁,请稍候再试” ,不会解决!!!

---------------------------------------------------------------------------
APIError                                  Traceback (most recent call last)
Cell In[11], line 12
      9 docs = text_splitter.split_documents(documents)
     10 # print(len(docs))
     11 # print(docs[0])
---> 12 db = FAISS.from_documents(docs, embeddings)
     13 db.save_local(faiss_name)

File /opt/conda/envs/python35-paddle120-env/lib/python3.10/site-packages/langchain_core/vectorstores.py:510, in VectorStore.from_documents(cls, documents, embedding, **kwargs)
    508 texts = [d.page_content for d in documents]
    509 metadatas = [d.metadata for d in documents]
--> 510 return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs)

File /opt/conda/envs/python35-paddle120-env/lib/python3.10/site-packages/langchain/vectorstores/faiss.py:911, in FAISS.from_texts(cls, texts, embedding, metadatas, ids, **kwargs)
    884 @classmethod
    885 def from_texts(
    886     cls,
   (...)
    891     **kwargs: Any,
    892 ) -> FAISS:
    893     """Construct FAISS wrapper from raw documents.
    894 
    895     This is a user friendly interface that:
   (...)
    909             faiss = FAISS.from_texts(texts, embeddings)
    910     """
--> 911     embeddings = embedding.embed_documents(texts)
    912     return cls.__from(
    913         texts,
    914         embeddings,
   (...)
    918         **kwargs,
    919     )

File ~/ERNIE-Bot-SDK/erniebot-agent/erniebot_agent/extensions/langchain/embeddings/ernie.py:68, in ErnieEmbeddings.embed_documents(self, texts)
     66 lst = []
     67 for chunk in text_in_chunks:
---> 68     resp = self.client.create(_config_=self._get_auth_config(), input=chunk, model=self.model)
     69     lst.extend([res["embedding"] for res in resp["data"]])
     70 return lst

File ~/ERNIE-Bot-SDK/erniebot/resources/abc/creatable.py:33, in Creatable.create(cls, **kwargs)
     31 resource = cls.new_object(**config)
     32 create_kwargs = kwargs
---> 33 return resource.create_resource(**create_kwargs)

File ~/ERNIE-Bot-SDK/erniebot/resources/abc/creatable.py:46, in Creatable.create_resource(self, **create_kwargs)
     44 def create_resource(self, **create_kwargs: Any) -> Union[EBResponse, Iterator[EBResponse]]:
     45     path, params, headers, files, stream, request_timeout = self._prepare_create(create_kwargs)
---> 46     resp = self.request(
     47         method="POST",
     48         path=path,
     49         stream=stream,
     50         params=params,
     51         headers=headers,
     52         files=files,
     53         request_timeout=request_timeout,
     54     )
     55     # See https://github.com/python/mypy/issues/1533
     56     resp = self._postprocess_create(resp)  # type: ignore

File ~/ERNIE-Bot-SDK/erniebot/resources/resource.py:142, in EBResource.request(self, method, path, stream, params, headers, files, request_timeout)
    129 @final
    130 def request(
    131     self,
   (...)
    139     request_timeout: Optional[float] = None,
    140 ) -> Union[EBResponse, Iterator[EBResponse]]:
    141     if self.timeout is None:
--> 142         return self._request(
    143             method=method,
    144             path=path,
    145             stream=stream,
    146             params=params,
    147             headers=headers,
    148             files=files,
    149             request_timeout=request_timeout,
    150         )
    151     else:
    152         st_time = time.time()

File ~/ERNIE-Bot-SDK/erniebot/resources/resource.py:363, in EBResource._request(self, method, path, stream, params, headers, files, request_timeout)
    352 @final
    353 def _request(
    354     self,
   (...)
    361     request_timeout: Optional[float],
    362 ) -> Union[EBResponse, Iterator[EBResponse]]:
--> 363     resp = self._backend.request(
    364         method,
    365         path,
    366         stream,
    367         params=params,
    368         headers=headers,
    369         files=files,
    370         request_timeout=request_timeout,
    371     )
    372     if stream:
    373         if not isinstance(resp, Iterator):

File ~/ERNIE-Bot-SDK/erniebot/backends/aistudio.py:82, in AIStudioBackend.request(self, method, path, stream, params, headers, files, request_timeout)
     74 url, headers, data = self._client.prepare_request(
     75     method,
     76     url,
   (...)
     79     files=files,
     80 )
     81 headers = self._add_aistudio_fields_to_headers(headers)
---> 82 return self._client.send_request(
     83     method,
     84     url,
     85     stream,
     86     data=data,
     87     headers=headers,
     88     files=files,
     89     request_timeout=request_timeout,
     90     base_url=self.base_url,
     91 )

File ~/ERNIE-Bot-SDK/erniebot/http_client.py:145, in EBClient.send_request(self, method, url, stream, data, headers, files, request_timeout, base_url)
    124 def send_request(
    125     self,
    126     method: str,
   (...)
    133     base_url: Optional[str] = None,
    134 ) -> Union[EBResponse, Iterator[EBResponse]]:
    135     result = self.send_request_raw(
    136         method.lower(),
    137         url,
   (...)
    143         request_timeout=request_timeout,
    144     )
--> 145     resp, got_stream = self._interpret_response(result, stream)
    146     if stream != got_stream:
    147         logger.warning("Unexpected response: %s", resp)

File ~/ERNIE-Bot-SDK/erniebot/http_client.py:339, in EBClient._interpret_response(self, result, stream)
    333     return (
    334         self._interpret_stream_response(result.iter_lines(), result.status_code, result.headers),
    335         True,
    336     )
    337 else:
    338     return (
--> 339         self._interpret_response_line(
    340             result.content.decode("utf-8"),
    341             result.status_code,
    342             result.headers,
    343             stream=False,
    344         ),
    345         False,
    346     )

File ~/ERNIE-Bot-SDK/erniebot/http_client.py:442, in EBClient._interpret_response_line(self, rbody, rcode, rheaders, stream)
    434     raise errors.HTTPRequestError(
    435         f"Status code is not {http.HTTPStatus.OK}.",
    436         rcode=resp.rcode,
    437         rbody=str(resp.rbody),
    438         rheaders=resp.rheaders,
    439     )
    441 if self._resp_handler is not None:
--> 442     resp = self._resp_handler(resp)
    443 return resp

File ~/ERNIE-Bot-SDK/erniebot/backends/aistudio.py:59, in AIStudioBackend.handle_response(self, resp)
     57         raise errors.TryAgain(emsg, ecode=ecode)
     58     else:
---> 59         raise errors.APIError(emsg, ecode=ecode)
     60 else:
     61     return EBResponse(resp.rcode, resp.result, resp.rheaders)

erniebot config cause pytest KeyError: '__wrapped__'

运行 pytest doctest 时,erniebot config 模块会导致下面的报错。

../../.pyenv/versions/3.9.11/lib/python3.9/doctest.py:939: in find
    self._find(tests, obj, name, module, source_lines, globs, {})
../../.pyenv/versions/3.9.11/envs/easyai/lib/python3.9/site-packages/_pytest/doctest.py:536: in _find
    super()._find(  # type:ignore[misc]
../../.pyenv/versions/3.9.11/lib/python3.9/doctest.py:998: in _find
    if ((inspect.isroutine(inspect.unwrap(val))
../../.pyenv/versions/3.9.11/envs/easyai/lib/python3.9/site-packages/_pytest/doctest.py:478: in _mock_aware_unwrap
    return real_unwrap(func, stop=_is_mocked)
../../.pyenv/versions/3.9.11/lib/python3.9/inspect.py:521: in unwrap
    while _is_wrapper(func):
../../.pyenv/versions/3.9.11/lib/python3.9/inspect.py:515: in _is_wrapper
    return hasattr(f, '__wrapped__') and not stop(f)
../../.pyenv/versions/3.9.11/envs/easyai/lib/python3.9/site-packages/erniebot/__init__.py:45: in __getattr__
    return GlobalConfig().get_value(name)
../../.pyenv/versions/3.9.11/envs/easyai/lib/python3.9/site-packages/erniebot/config.py:42: in get_value
    cfg = self._cfg_dict[key]
E   KeyError: '__wrapped__'
============================================================== warnings summary ===============================================================
../../.pyenv/versions/3.9.11/envs/easyai/lib/python3.9/site-packages/_pytest/doctest.py:482
  /Users/kk/.pyenv/versions/3.9.11/envs/easyai/lib/python3.9/site-packages/_pytest/doctest.py:482: PytestWarning: Got KeyError('__wrapped__') when unwrapping <module 'erniebot' from '/Users/kk/.pyenv/versions/3.9.11/envs/easyai/lib/python3.9/site-packages/erniebot/__init__.py'>.  This is usually caused by a violation of Python's object protocol; see e.g. https://github.com/pytest-dev/pytest/issues/5080
    warnings.warn(

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html

config.py 模块 __getattr__ 函数需要将 KeyError 转成 AttributeError 再抛出,才能正确处理key不存在的情况。修复如下:

def __getattr__(name):
    try:
        return GlobalConfig().get_value(name)
    except KeyError as ex:
        raise AttributeError(name) from ex

兼容openai的api格式

现如今,有很多应用框架都是基于openai的api格式开发的,能否提供一种方式,让它彻底兼容openai.api的格式?

请问支持tool_calls吗?

  • 版本 0.4.0

我看文档的Function Calling只有functions参数,请问支持tools参数吗?因为我想实现一句话中可以同时识别多个意图。
例如请打开灯,然后开始煮米饭,这里面有两个意图。

如果用functions,只返回一个json,而不是list。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.