Я разрабатываю сценарий с использованием CrewAI и LangChain для моделирования интервью, в котором мои агенты генерируют и оценивают вопросы на основе ответов пользователей. Однако у меня возникли проблемы с правильной обработкой пользовательского ввода, и скрипт не работает должным образом. Фрагмент кода:
< pre class="lang-py Prettyprint-override">
import os
from crewai import Agent, Task, Crew, Process
from langchain_google_genai import ChatGoogleGenerativeAI
from dotenv import load_dotenv
load_dotenv()
gemini_llm = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0)
# Define agents
question_generator = Agent(
role='Question Generator Agent',
goal='Generate initial and follow-up questions based on user responses and behavioral analysis.',
verbose=True,
memory=True,
backstory=(
"Expert in behavioral analysis and interview techniques, always ready with probing and engaging questions."
),
llm=gemini_llm,
)
evaluator = Agent(
role='Evaluator Agent',
goal='Evaluate the user’s responses for relevance and sufficiency.',
verbose=True,
memory=True,
backstory=(
"Experienced evaluator with a keen eye for detail, ensuring responses meet the required criteria."
),
llm=gemini_llm
)
# Define tasks
initial_question_task = Task(
description="Generate an initial question for the user based on behavioral analysis.",
expected_output='A single question for the user to respond to.',
agent=question_generator,
)
evaluate_response_task = Task(
description="Evaluate the user's response for relevance and sufficiency.",
expected_output='Feedback on whether the response is satisfactory or if a follow-up question is needed.',
agent=evaluator,
)
follow_up_question_task = Task(
description="Generate a follow-up question based on the user's previous response and the evaluator's feedback.",
expected_output='A follow-up question that probes deeper into the user\'s previous answer.',
agent=question_generator,
)
# Define the crew and process
crew = Crew(
agents=[question_generator, evaluator],
tasks=[initial_question_task, evaluate_response_task, follow_up_question_task],
process=Process.sequential
)
# Function to run the interview process
def run_interview():
for question_number in range(10):
print(f"\nQuestion {question_number + 1}:")
# Generate the initial question
crew.process = Process.sequential
result = crew.kickoff(inputs={'task_name': 'initial_question_task'})
initial_question = result['output']
print(initial_question)
user_response = input("Your response: ")
# Evaluate the response
crew.process = Process.sequential
result = crew.kickoff(inputs={'task_name': 'evaluate_response_task', 'response': user_response})
evaluator_feedback = result['output']
if "satisfactory" in evaluator_feedback:
print("Response is satisfactory.")
continue
# Handle follow-up questions
for follow_up_number in range(2):
crew.process = Process.sequential
result = crew.kickoff(inputs={'task_name': 'follow_up_question_task', 'previous_response': user_response})
follow_up_question = result['output']
print(f"Follow-up question {follow_up_number + 1}: {follow_up_question}")
user_response = input("Your response: ")
crew.process = Process.sequential
result = crew.kickoff(inputs={'task_name': 'evaluate_response_task', 'response': user_response})
evaluator_feedback = result['output']
if "satisfactory" in evaluator_feedback:
print("Response is satisfactory.")
break
else:
print("Response is not satisfactory. Generating another follow-up question...")
# Start the interview process
run_interview()
Возникла проблема:
Сценарий не может должным образом обрабатывать вводимые пользователем данные во время моделирования собеседования. В частности, после создания первоначальных вопросов и получения ответов пользователей он неправильно оценивает ответы или генерирует дополнительные вопросы на основе отзывов оценщика. Вместо этого он выдает ошибки или выдает неправильные выходные данные. Ожидаемый результат:
Я ожидаю, что сценарий будет плавно генерировать вопросы. , оценивать ответы и последовательно отвечать на дополнительные вопросы на основе отзывов оценщика. Что я пробовал:
Обеспечение правильной настройки агентов и задач CrewAI.
Проверка входных параметров и ожидаемых результатов для каждой задачи.
Отладка потенциальных проблем с обработкой пользовательского ввода и потоком выполнения задач.
Я разрабатываю сценарий с использованием CrewAI и LangChain для моделирования интервью, в котором мои агенты генерируют и оценивают вопросы на основе ответов пользователей. Однако у меня возникли проблемы с правильной обработкой пользовательского ввода, и скрипт не работает должным образом. [b]Фрагмент кода:[/b] < pre class="lang-py Prettyprint-override">[code]import os from crewai import Agent, Task, Crew, Process from langchain_google_genai import ChatGoogleGenerativeAI from dotenv import load_dotenv
# Define agents question_generator = Agent( role='Question Generator Agent', goal='Generate initial and follow-up questions based on user responses and behavioral analysis.', verbose=True, memory=True, backstory=( "Expert in behavioral analysis and interview techniques, always ready with probing and engaging questions." ), llm=gemini_llm, )
evaluator = Agent( role='Evaluator Agent', goal='Evaluate the user’s responses for relevance and sufficiency.', verbose=True, memory=True, backstory=( "Experienced evaluator with a keen eye for detail, ensuring responses meet the required criteria." ), llm=gemini_llm )
# Define tasks initial_question_task = Task( description="Generate an initial question for the user based on behavioral analysis.", expected_output='A single question for the user to respond to.', agent=question_generator, )
evaluate_response_task = Task( description="Evaluate the user's response for relevance and sufficiency.", expected_output='Feedback on whether the response is satisfactory or if a follow-up question is needed.', agent=evaluator, )
follow_up_question_task = Task( description="Generate a follow-up question based on the user's previous response and the evaluator's feedback.", expected_output='A follow-up question that probes deeper into the user\'s previous answer.', agent=question_generator, )
# Define the crew and process crew = Crew( agents=[question_generator, evaluator], tasks=[initial_question_task, evaluate_response_task, follow_up_question_task], process=Process.sequential )
# Function to run the interview process def run_interview(): for question_number in range(10): print(f"\nQuestion {question_number + 1}:")
# Generate the initial question crew.process = Process.sequential result = crew.kickoff(inputs={'task_name': 'initial_question_task'}) initial_question = result['output'] print(initial_question)
user_response = input("Your response: ")
# Evaluate the response crew.process = Process.sequential result = crew.kickoff(inputs={'task_name': 'evaluate_response_task', 'response': user_response}) evaluator_feedback = result['output']
if "satisfactory" in evaluator_feedback: print("Response is satisfactory.") continue
# Handle follow-up questions for follow_up_number in range(2): crew.process = Process.sequential result = crew.kickoff(inputs={'task_name': 'follow_up_question_task', 'previous_response': user_response}) follow_up_question = result['output']
if "satisfactory" in evaluator_feedback: print("Response is satisfactory.") break else: print("Response is not satisfactory. Generating another follow-up question...")
# Start the interview process run_interview() [/code] [b]Возникла проблема:[/b] Сценарий не может должным образом обрабатывать вводимые пользователем данные во время моделирования собеседования. В частности, после создания первоначальных вопросов и получения ответов пользователей он неправильно оценивает ответы или генерирует дополнительные вопросы на основе отзывов оценщика. Вместо этого он выдает ошибки или выдает неправильные выходные данные. [b]Ожидаемый результат:[/b] Я ожидаю, что сценарий будет плавно генерировать вопросы. , оценивать ответы и последовательно отвечать на дополнительные вопросы на основе отзывов оценщика. [b]Что я пробовал:[/b] [list] [*]Обеспечение правильной настройки агентов и задач CrewAI. [*]Проверка входных параметров и ожидаемых результатов для каждой задачи. [*]Отладка потенциальных проблем с обработкой пользовательского ввода и потоком выполнения задач. [/list]
Я разрабатываю сценарий с использованием CrewAI и LangChain для моделирования интервью, в котором мои агенты генерируют и оценивают вопросы на основе ответов пользователей. Однако у меня возникли проблемы с правильной обработкой пользовательского...
Я столкнулся с ошибкой AttributeError при попытке использовать LangChain Google GenerativeAI в среде CrewAI. Ошибка возникает при выполнении метода Kickoff() экземпляра Crew. Конкретное сообщение об ошибке указывает на модуль langchain_google_genai,...
Вот мой код:
import os
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool
from langchain_community.tools import DuckDuckGoSearchResults
from langchain.agents import Tool
os.environ = 'I deleted it'
os.environ =...
У меня есть проект для моего университета, который предполагает разработку системы управления бронированием спортивных объектов. Система должна обеспечивать регистрацию пользователей, создание, отмену бронирования, регистрацию объекта и другие...
Сейчас я изучаю C# ASP.NET Core, это мой проект, над которым я работаю ->
У меня проблема с файлом ShoppingCartService.cs! Когда программы переходят к методу public async Task AddToCart(int bookId), он успешно добавляет товар в корзину, но когда он...