generate_question_answers.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import argparse
  4. import asyncio
  5. import json
  6. from config import load_config
  7. from generator_utils import generate_question_batches, parse_qa_to_json
  8. from itertools import chain
  9. import logging
  10. import aiofiles # Ensure aiofiles is installed for async file operations
  11. from abc import ABC, abstractmethod
  12. from octoai.client import Client
  13. from functools import partial
  14. from openai import OpenAI
  15. # Configure logging to include the timestamp, log level, and message
  16. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  17. # Manage rate limits with throttling
  18. rate_limit_threshold = 2000
  19. allowed_concurrent_requests = int(rate_limit_threshold * 0.75)
  20. request_limiter = asyncio.Semaphore(allowed_concurrent_requests)
  21. class ChatService(ABC):
  22. @abstractmethod
  23. async def execute_chat_request_async(self, api_context: dict, chat_request):
  24. pass
  25. # Please implement your own chat service class here.
  26. # The class should inherit from the ChatService class and implement the execute_chat_request_async method.
  27. # The following are two example chat service classes that you can use as a reference.
  28. class OctoAIChatService(ChatService):
  29. async def execute_chat_request_async(self, api_context: dict, chat_request):
  30. async with request_limiter:
  31. try:
  32. event_loop = asyncio.get_running_loop()
  33. client = Client(api_context['api_key'])
  34. api_chat_call = partial(
  35. client.chat.completions.create,
  36. model=api_context['model'],
  37. messages=chat_request,
  38. temperature=0.0
  39. )
  40. response = await event_loop.run_in_executor(None, api_chat_call)
  41. assistant_response = next((choice.message.content for choice in response.choices if choice.message.role == 'assistant'), "")
  42. assistant_response_json = parse_qa_to_json(assistant_response)
  43. return assistant_response_json
  44. except Exception as error:
  45. print(f"Error during chat request execution: {error}")
  46. return ""
  47. # Use the local vllm openai compatible server for generating question/answer pairs to make API call syntax consistent
  48. # please read for more detail:https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html.
  49. class VllmChatService(ChatService):
  50. async def execute_chat_request_async(self, api_context: dict, chat_request):
  51. async with request_limiter:
  52. try:
  53. event_loop = asyncio.get_running_loop()
  54. client = OpenAI(api_key="EMPTY", base_url="http://localhost:"+ api_context['end_point']+"/v1")
  55. api_chat_call = partial(
  56. client.chat.completions.create,
  57. model=api_context['model'],
  58. messages=chat_request,
  59. temperature=0.0
  60. )
  61. response = await event_loop.run_in_executor(None, api_chat_call)
  62. assistant_response = next((choice.message.content for choice in response.choices if choice.message.role == 'assistant'), "")
  63. assistant_response_json = parse_qa_to_json(assistant_response)
  64. return assistant_response_json
  65. except Exception as error:
  66. print(f"Error during chat request execution: {error}")
  67. return ""
  68. async def main(context):
  69. if context["endpoint"]:
  70. logging.info(f" Use local vllm service at port '{context["endpoint"]}'.")
  71. chat_service = VllmChatService()
  72. else:
  73. chat_service = OctoAIChatService()
  74. try:
  75. logging.info("Starting to generate question/answer pairs.")
  76. data = await generate_question_batches(chat_service, context)
  77. if not data:
  78. logging.warning("No data generated. Please check the input context or model configuration.")
  79. return
  80. flattened_list = list(chain.from_iterable(data))
  81. logging.info(f"Successfully generated {len(flattened_list)} question/answer pairs.")
  82. # Use asynchronous file operation for writing to the file
  83. async with aiofiles.open("data.json", "w") as output_file:
  84. await output_file.write(json.dumps(flattened_list, indent=4))
  85. logging.info("Data successfully written to 'data.json'. Process completed.")
  86. except Exception as e:
  87. logging.error(f"An unexpected error occurred during the process: {e}")
  88. def parse_arguments():
  89. # Define command line arguments for the script
  90. parser = argparse.ArgumentParser(
  91. description="Generate question/answer pairs from documentation."
  92. )
  93. parser.add_argument(
  94. "-t", "--total_questions",
  95. type=int,
  96. default=10,
  97. help="Specify the number of question/answer pairs to generate."
  98. )
  99. parser.add_argument(
  100. "-m", "--model",
  101. choices=["meta-llama-3-70b-instruct","meta-llama-3-8b-instruct","llama-2-70b-chat-fp16", "llama-2-13b-chat-fp16"],
  102. default="meta-llama-3-70b-instruct",
  103. help="Select the model to use for generation."
  104. )
  105. parser.add_argument(
  106. "-c", "--config_path",
  107. default="config.yaml",
  108. help="Set the configuration file path that has system prompt along with language, dataset path and number of questions."
  109. )
  110. parser.add_argument(
  111. "-v", "--vllm_endpoint",
  112. default=None,
  113. help="If a port is specified, then use local vllm endpoint for generating question/answer pairs."
  114. return parser.parse_args()
  115. if __name__ == "__main__":
  116. logging.info("Initializing the process and loading configuration...")
  117. args = parse_arguments()
  118. context = load_config(args.config_path)
  119. context["total_questions"] = args.total_questions
  120. context["model"] = args.model
  121. context["endpoint"] = args.vllm_endpoint
  122. logging.info(f"Configuration loaded. Generating {args.total_questions} question/answer pairs using model '{args.model}'.")
  123. asyncio.run(main(context))