Не удалось проанализировать выходные данные LLM в langchain, когда я запрашиваю у агента определенную структуру JSON.Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Не удалось проанализировать выходные данные LLM в langchain, когда я запрашиваю у агента определенную структуру JSON.

Сообщение Anonymous »

Я пытаюсь интегрировать API поиска Google в свой созданный агент, где агенту необходимо создать определенную структуру json для данного абзаца. В данном параграфе будут задачи, которые выполнил инженер. Таким образом, агент должен иметь возможность идентифицировать задачи и проблемы, с которыми инженер столкнулся в конкретный день. Мой агент отображается в следующем блоке кода

Код: Выделить всё

agent = initialize_agent(tools=[google_search_tool],
agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,
llm=llm,
memory=conversational_memory,
max_iterations=5,
early_stopping_method='generate',
verbose=True,
agent_kwargs={
"system_message": CUSTOM_TIMESHEET_SYSTEM_PROMPT.strip(),
},
handle_parsing_errors=False
)
Как только я передаю сообщение агенту, агент идентифицирует все задачи, но выдает исключение с помощью созданного JSON. Ошибка — следующий блок.

Код: Выделить всё

ile "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain\agents\conversational_chat\output_parser.py", line 50, in parse
raise OutputParserException(f"Could not parse LLM output: {text}") from e
langchain.schema.output_parser.OutputParserException: Could not parse LLM output: ```json
{
"tasks": [
{
"id": 1,
"task": "Completed the implementation of the user authentication feature",
"duration": "8 hrs"
},
{
"id": 2,
"task": "Wrote tests for the user authentication feature",
"duration": null
},
{
"id": 3,
"task": "Plan to start working on the user profile feature",
"duration": null
},
{
"id": 4,
"task": "Creating the database schema for the user profile feature",
"duration": "4 hrs"
},
{
"id": 5,
"task": "Start with the backend implementation for the user profile feature",
"duration": "4 hrs"
},
{
"id": 6,
"task": "Complete the backend implementation for the user profile feature",
"duration": "8 hrs"
}
],
"problems": []
}
И это системное сообщение, которое я передал своему агенту.

Код: Выделить всё

CUSTOM_TIMESHEET_SYSTEM_PROMPT = """
Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with you to breakdown tasks and the issues,
that were encountered through out the day. Assistant will break down the tasks and problems that were encountered by you.
Overall, Assistant is a powerful system that can help you to break down tasks and identify the problems that were encountered through given content.

TOOLS
------
Assistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:

> Google Search: Search Google for most recent data, latest data, any question you don't know the answer such as current date, time, weather, president, etc

RESPONSE FORMAT INSTRUCTIONS
----------------------------
Please provide a structured list or breakdown of the individual work actions/tasks and problems faced mentioned within the paragraph.
Ensure each task is clearly separated and identified with the time spent on each task. Provide the identified tasks as a JSON array.
Ensure that the tasks are clearly separated. Make sure to extract the time from hours.
If the time is provided through a different metric, convert it to hours. One day means 8 hours, and half a day means 4 hours.
One morning, afternoon, and evening will be equal to 4 hrs. Make sure to add hrs as the metric to the value.
If the duration is not identified, make sure to keep duration null in the JSON. The identified problems should be identified as another JSON array.
Id can be an incremental id.  recommendedLinks should be solutions for the identified problems from YouTube.
When responding to me, please output a response in this format:

Option 1:
Use this if a problem is identified to recommend links from a tool.
Markdown code snippet formatted in the following schema:
```json
{{
"action": any, # The action should be the google search
"action_input": string # The identified problem
}}

Option #2:
Use this if you want to respond directly to the human. MARKDOWN code snippet formatted in the following schema:
```json
{{
"action": any,
"action_input": string # You should put what you want to return to use here
}}

Make sure to return the constructed JSON as a string
USER'S INPUT
--------------------
Here is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):
Я просто ожидаю вернуть это упомянутое в качестве вывода без каких-либо исключений. Любая идея, как решить эту проблему. Просто обратите внимание, что я передал handle_parsing_errors=True, но это привело к возникновению цикла, который приведет к ошибке со стороны gpt. Как только я передал handle_parsing_errors="Проверьте свои выходные данные и убедитесь, что они соответствуют!" В результате появится только абзац, похожий на `"На основании вашего последнего комментария вы успешно завершили реализацию функции аутентификации пользователя и написали тесты для него. Вы планируете работать над функцией профиля пользователя, начиная с создания схемы базы данных, а затем реализации серверной части. Вы планируете завершить реализацию внутренней части к завтрашнему полудню, и в настоящее время вы не предвидите никаких блокировщиков, если таковые возникнут. , вы планируете сообщить об этом по каналу связи команды и соответствующим образом обновить предполагаемый график."

Подробнее здесь: https://stackoverflow.com/questions/771 ... -structure
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»