llama-stack 0.0.42__py3-none-any.whl → 0.3.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (738) hide show
  1. llama_stack/__init__.py +5 -0
  2. llama_stack/apis/agents/__init__.py +1 -1
  3. llama_stack/apis/agents/agents.py +700 -281
  4. llama_stack/apis/agents/openai_responses.py +1311 -0
  5. llama_stack/{providers/adapters/memory/sample/config.py → apis/batches/__init__.py} +2 -5
  6. llama_stack/apis/batches/batches.py +100 -0
  7. llama_stack/apis/benchmarks/__init__.py +7 -0
  8. llama_stack/apis/benchmarks/benchmarks.py +108 -0
  9. llama_stack/apis/common/content_types.py +143 -0
  10. llama_stack/apis/common/errors.py +103 -0
  11. llama_stack/apis/common/job_types.py +38 -0
  12. llama_stack/apis/common/responses.py +36 -0
  13. llama_stack/apis/common/training_types.py +36 -5
  14. llama_stack/apis/common/type_system.py +158 -0
  15. llama_stack/apis/conversations/__init__.py +31 -0
  16. llama_stack/apis/conversations/conversations.py +286 -0
  17. llama_stack/apis/datasetio/__init__.py +7 -0
  18. llama_stack/apis/datasetio/datasetio.py +59 -0
  19. llama_stack/apis/datasets/__init__.py +7 -0
  20. llama_stack/apis/datasets/datasets.py +251 -0
  21. llama_stack/apis/datatypes.py +160 -0
  22. llama_stack/apis/eval/__init__.py +7 -0
  23. llama_stack/apis/eval/eval.py +169 -0
  24. llama_stack/apis/files/__init__.py +7 -0
  25. llama_stack/apis/files/files.py +199 -0
  26. llama_stack/apis/inference/__init__.py +1 -1
  27. llama_stack/apis/inference/inference.py +1169 -113
  28. llama_stack/apis/inspect/__init__.py +1 -1
  29. llama_stack/apis/inspect/inspect.py +69 -16
  30. llama_stack/apis/models/__init__.py +1 -1
  31. llama_stack/apis/models/models.py +148 -21
  32. llama_stack/apis/post_training/__init__.py +1 -1
  33. llama_stack/apis/post_training/post_training.py +265 -120
  34. llama_stack/{providers/adapters/agents/sample/config.py → apis/prompts/__init__.py} +2 -5
  35. llama_stack/apis/prompts/prompts.py +204 -0
  36. llama_stack/apis/providers/__init__.py +7 -0
  37. llama_stack/apis/providers/providers.py +69 -0
  38. llama_stack/apis/resource.py +37 -0
  39. llama_stack/apis/safety/__init__.py +1 -1
  40. llama_stack/apis/safety/safety.py +95 -12
  41. llama_stack/apis/scoring/__init__.py +7 -0
  42. llama_stack/apis/scoring/scoring.py +93 -0
  43. llama_stack/apis/scoring_functions/__init__.py +7 -0
  44. llama_stack/apis/scoring_functions/scoring_functions.py +208 -0
  45. llama_stack/apis/shields/__init__.py +1 -1
  46. llama_stack/apis/shields/shields.py +76 -33
  47. llama_stack/apis/synthetic_data_generation/__init__.py +1 -1
  48. llama_stack/apis/synthetic_data_generation/synthetic_data_generation.py +40 -17
  49. llama_stack/apis/telemetry/__init__.py +1 -1
  50. llama_stack/apis/telemetry/telemetry.py +322 -31
  51. llama_stack/apis/{dataset → tools}/__init__.py +2 -1
  52. llama_stack/apis/tools/rag_tool.py +218 -0
  53. llama_stack/apis/tools/tools.py +221 -0
  54. llama_stack/apis/vector_io/__init__.py +7 -0
  55. llama_stack/apis/vector_io/vector_io.py +960 -0
  56. llama_stack/apis/vector_stores/__init__.py +7 -0
  57. llama_stack/apis/vector_stores/vector_stores.py +51 -0
  58. llama_stack/apis/version.py +9 -0
  59. llama_stack/cli/llama.py +13 -5
  60. llama_stack/cli/stack/_list_deps.py +182 -0
  61. llama_stack/cli/stack/list_apis.py +1 -1
  62. llama_stack/cli/stack/list_deps.py +55 -0
  63. llama_stack/cli/stack/list_providers.py +24 -10
  64. llama_stack/cli/stack/list_stacks.py +56 -0
  65. llama_stack/cli/stack/remove.py +115 -0
  66. llama_stack/cli/stack/run.py +169 -56
  67. llama_stack/cli/stack/stack.py +18 -4
  68. llama_stack/cli/stack/utils.py +151 -0
  69. llama_stack/cli/table.py +23 -61
  70. llama_stack/cli/utils.py +29 -0
  71. llama_stack/core/access_control/access_control.py +131 -0
  72. llama_stack/core/access_control/conditions.py +129 -0
  73. llama_stack/core/access_control/datatypes.py +107 -0
  74. llama_stack/core/build.py +164 -0
  75. llama_stack/core/client.py +205 -0
  76. llama_stack/core/common.sh +37 -0
  77. llama_stack/{distribution → core}/configure.py +74 -55
  78. llama_stack/core/conversations/conversations.py +309 -0
  79. llama_stack/core/datatypes.py +625 -0
  80. llama_stack/core/distribution.py +276 -0
  81. llama_stack/core/external.py +54 -0
  82. llama_stack/core/id_generation.py +42 -0
  83. llama_stack/core/inspect.py +86 -0
  84. llama_stack/core/library_client.py +539 -0
  85. llama_stack/core/prompts/prompts.py +234 -0
  86. llama_stack/core/providers.py +137 -0
  87. llama_stack/core/request_headers.py +115 -0
  88. llama_stack/core/resolver.py +506 -0
  89. llama_stack/core/routers/__init__.py +101 -0
  90. llama_stack/core/routers/datasets.py +73 -0
  91. llama_stack/core/routers/eval_scoring.py +155 -0
  92. llama_stack/core/routers/inference.py +645 -0
  93. llama_stack/core/routers/safety.py +85 -0
  94. llama_stack/core/routers/tool_runtime.py +91 -0
  95. llama_stack/core/routers/vector_io.py +442 -0
  96. llama_stack/core/routing_tables/benchmarks.py +62 -0
  97. llama_stack/core/routing_tables/common.py +254 -0
  98. llama_stack/core/routing_tables/datasets.py +91 -0
  99. llama_stack/core/routing_tables/models.py +163 -0
  100. llama_stack/core/routing_tables/scoring_functions.py +66 -0
  101. llama_stack/core/routing_tables/shields.py +61 -0
  102. llama_stack/core/routing_tables/toolgroups.py +129 -0
  103. llama_stack/core/routing_tables/vector_stores.py +292 -0
  104. llama_stack/core/server/auth.py +187 -0
  105. llama_stack/core/server/auth_providers.py +494 -0
  106. llama_stack/core/server/quota.py +110 -0
  107. llama_stack/core/server/routes.py +141 -0
  108. llama_stack/core/server/server.py +542 -0
  109. llama_stack/core/server/tracing.py +80 -0
  110. llama_stack/core/stack.py +546 -0
  111. llama_stack/core/start_stack.sh +117 -0
  112. llama_stack/core/storage/datatypes.py +283 -0
  113. llama_stack/{cli/model → core/store}/__init__.py +1 -1
  114. llama_stack/core/store/registry.py +199 -0
  115. llama_stack/core/testing_context.py +49 -0
  116. llama_stack/core/ui/app.py +55 -0
  117. llama_stack/core/ui/modules/api.py +32 -0
  118. llama_stack/core/ui/modules/utils.py +42 -0
  119. llama_stack/core/ui/page/distribution/datasets.py +18 -0
  120. llama_stack/core/ui/page/distribution/eval_tasks.py +20 -0
  121. llama_stack/core/ui/page/distribution/models.py +18 -0
  122. llama_stack/core/ui/page/distribution/providers.py +27 -0
  123. llama_stack/core/ui/page/distribution/resources.py +48 -0
  124. llama_stack/core/ui/page/distribution/scoring_functions.py +18 -0
  125. llama_stack/core/ui/page/distribution/shields.py +19 -0
  126. llama_stack/core/ui/page/evaluations/app_eval.py +143 -0
  127. llama_stack/core/ui/page/evaluations/native_eval.py +253 -0
  128. llama_stack/core/ui/page/playground/chat.py +130 -0
  129. llama_stack/core/ui/page/playground/tools.py +352 -0
  130. llama_stack/core/utils/config.py +30 -0
  131. llama_stack/{distribution → core}/utils/config_dirs.py +3 -6
  132. llama_stack/core/utils/config_resolution.py +125 -0
  133. llama_stack/core/utils/context.py +84 -0
  134. llama_stack/core/utils/exec.py +96 -0
  135. llama_stack/{providers/impls/meta_reference/codeshield/config.py → core/utils/image_types.py} +4 -3
  136. llama_stack/{distribution → core}/utils/model_utils.py +2 -2
  137. llama_stack/{distribution → core}/utils/prompt_for_config.py +30 -63
  138. llama_stack/{apis/batch_inference → distributions/dell}/__init__.py +1 -1
  139. llama_stack/distributions/dell/build.yaml +33 -0
  140. llama_stack/distributions/dell/dell.py +158 -0
  141. llama_stack/distributions/dell/run-with-safety.yaml +141 -0
  142. llama_stack/distributions/dell/run.yaml +132 -0
  143. llama_stack/distributions/meta-reference-gpu/__init__.py +7 -0
  144. llama_stack/distributions/meta-reference-gpu/build.yaml +32 -0
  145. llama_stack/distributions/meta-reference-gpu/meta_reference.py +163 -0
  146. llama_stack/distributions/meta-reference-gpu/run-with-safety.yaml +154 -0
  147. llama_stack/distributions/meta-reference-gpu/run.yaml +139 -0
  148. llama_stack/{apis/evals → distributions/nvidia}/__init__.py +1 -1
  149. llama_stack/distributions/nvidia/build.yaml +29 -0
  150. llama_stack/distributions/nvidia/nvidia.py +154 -0
  151. llama_stack/distributions/nvidia/run-with-safety.yaml +137 -0
  152. llama_stack/distributions/nvidia/run.yaml +116 -0
  153. llama_stack/distributions/open-benchmark/__init__.py +7 -0
  154. llama_stack/distributions/open-benchmark/build.yaml +36 -0
  155. llama_stack/distributions/open-benchmark/open_benchmark.py +303 -0
  156. llama_stack/distributions/open-benchmark/run.yaml +252 -0
  157. llama_stack/distributions/postgres-demo/__init__.py +7 -0
  158. llama_stack/distributions/postgres-demo/build.yaml +23 -0
  159. llama_stack/distributions/postgres-demo/postgres_demo.py +125 -0
  160. llama_stack/distributions/postgres-demo/run.yaml +115 -0
  161. llama_stack/{apis/memory → distributions/starter}/__init__.py +1 -1
  162. llama_stack/distributions/starter/build.yaml +61 -0
  163. llama_stack/distributions/starter/run-with-postgres-store.yaml +285 -0
  164. llama_stack/distributions/starter/run.yaml +276 -0
  165. llama_stack/distributions/starter/starter.py +345 -0
  166. llama_stack/distributions/starter-gpu/__init__.py +7 -0
  167. llama_stack/distributions/starter-gpu/build.yaml +61 -0
  168. llama_stack/distributions/starter-gpu/run-with-postgres-store.yaml +288 -0
  169. llama_stack/distributions/starter-gpu/run.yaml +279 -0
  170. llama_stack/distributions/starter-gpu/starter_gpu.py +20 -0
  171. llama_stack/distributions/template.py +456 -0
  172. llama_stack/distributions/watsonx/__init__.py +7 -0
  173. llama_stack/distributions/watsonx/build.yaml +33 -0
  174. llama_stack/distributions/watsonx/run.yaml +133 -0
  175. llama_stack/distributions/watsonx/watsonx.py +95 -0
  176. llama_stack/env.py +24 -0
  177. llama_stack/log.py +314 -0
  178. llama_stack/models/llama/checkpoint.py +164 -0
  179. llama_stack/models/llama/datatypes.py +164 -0
  180. llama_stack/models/llama/hadamard_utils.py +86 -0
  181. llama_stack/models/llama/llama3/args.py +74 -0
  182. llama_stack/models/llama/llama3/chat_format.py +286 -0
  183. llama_stack/models/llama/llama3/generation.py +376 -0
  184. llama_stack/models/llama/llama3/interface.py +255 -0
  185. llama_stack/models/llama/llama3/model.py +304 -0
  186. llama_stack/models/llama/llama3/multimodal/__init__.py +12 -0
  187. llama_stack/models/llama/llama3/multimodal/encoder_utils.py +180 -0
  188. llama_stack/models/llama/llama3/multimodal/image_transform.py +409 -0
  189. llama_stack/models/llama/llama3/multimodal/model.py +1430 -0
  190. llama_stack/models/llama/llama3/multimodal/utils.py +26 -0
  191. llama_stack/models/llama/llama3/prompt_templates/__init__.py +22 -0
  192. llama_stack/models/llama/llama3/prompt_templates/base.py +39 -0
  193. llama_stack/models/llama/llama3/prompt_templates/system_prompts.py +319 -0
  194. llama_stack/models/llama/llama3/prompt_templates/tool_response.py +62 -0
  195. llama_stack/models/llama/llama3/quantization/loader.py +316 -0
  196. llama_stack/models/llama/llama3/template_data.py +116 -0
  197. llama_stack/models/llama/llama3/tokenizer.model +128000 -0
  198. llama_stack/models/llama/llama3/tokenizer.py +198 -0
  199. llama_stack/models/llama/llama3/tool_utils.py +266 -0
  200. llama_stack/models/llama/llama3_1/__init__.py +12 -0
  201. llama_stack/models/llama/llama3_1/prompt_format.md +358 -0
  202. llama_stack/models/llama/llama3_1/prompts.py +258 -0
  203. llama_stack/models/llama/llama3_2/prompts_text.py +229 -0
  204. llama_stack/models/llama/llama3_2/prompts_vision.py +126 -0
  205. llama_stack/models/llama/llama3_2/text_prompt_format.md +286 -0
  206. llama_stack/models/llama/llama3_2/vision_prompt_format.md +141 -0
  207. llama_stack/models/llama/llama3_3/prompts.py +259 -0
  208. llama_stack/models/llama/llama4/args.py +107 -0
  209. llama_stack/models/llama/llama4/chat_format.py +317 -0
  210. llama_stack/models/llama/llama4/datatypes.py +56 -0
  211. llama_stack/models/llama/llama4/ffn.py +58 -0
  212. llama_stack/models/llama/llama4/generation.py +313 -0
  213. llama_stack/models/llama/llama4/model.py +437 -0
  214. llama_stack/models/llama/llama4/moe.py +214 -0
  215. llama_stack/models/llama/llama4/preprocess.py +435 -0
  216. llama_stack/models/llama/llama4/prompt_format.md +304 -0
  217. llama_stack/models/llama/llama4/prompt_templates/system_prompts.py +136 -0
  218. llama_stack/models/llama/llama4/prompts.py +279 -0
  219. llama_stack/models/llama/llama4/quantization/__init__.py +5 -0
  220. llama_stack/models/llama/llama4/quantization/loader.py +226 -0
  221. llama_stack/models/llama/llama4/tokenizer.model +200000 -0
  222. llama_stack/models/llama/llama4/tokenizer.py +263 -0
  223. llama_stack/models/llama/llama4/vision/__init__.py +5 -0
  224. llama_stack/models/llama/llama4/vision/embedding.py +210 -0
  225. llama_stack/models/llama/llama4/vision/encoder.py +412 -0
  226. llama_stack/models/llama/prompt_format.py +191 -0
  227. llama_stack/models/llama/quantize_impls.py +316 -0
  228. llama_stack/models/llama/sku_list.py +1029 -0
  229. llama_stack/models/llama/sku_types.py +233 -0
  230. llama_stack/models/llama/tokenizer_utils.py +40 -0
  231. llama_stack/providers/datatypes.py +136 -107
  232. llama_stack/providers/inline/__init__.py +5 -0
  233. llama_stack/providers/inline/agents/__init__.py +5 -0
  234. llama_stack/providers/{impls/meta_reference/agents → inline/agents/meta_reference}/__init__.py +12 -5
  235. llama_stack/providers/inline/agents/meta_reference/agent_instance.py +1024 -0
  236. llama_stack/providers/inline/agents/meta_reference/agents.py +383 -0
  237. llama_stack/providers/inline/agents/meta_reference/config.py +37 -0
  238. llama_stack/providers/inline/agents/meta_reference/persistence.py +228 -0
  239. llama_stack/providers/inline/agents/meta_reference/responses/__init__.py +5 -0
  240. llama_stack/providers/inline/agents/meta_reference/responses/openai_responses.py +423 -0
  241. llama_stack/providers/inline/agents/meta_reference/responses/streaming.py +1226 -0
  242. llama_stack/providers/inline/agents/meta_reference/responses/tool_executor.py +449 -0
  243. llama_stack/providers/inline/agents/meta_reference/responses/types.py +194 -0
  244. llama_stack/providers/inline/agents/meta_reference/responses/utils.py +365 -0
  245. llama_stack/providers/inline/agents/meta_reference/safety.py +52 -0
  246. llama_stack/providers/inline/batches/__init__.py +5 -0
  247. llama_stack/providers/inline/batches/reference/__init__.py +36 -0
  248. llama_stack/providers/inline/batches/reference/batches.py +679 -0
  249. llama_stack/providers/inline/batches/reference/config.py +40 -0
  250. llama_stack/providers/inline/datasetio/__init__.py +5 -0
  251. llama_stack/providers/inline/datasetio/localfs/__init__.py +20 -0
  252. llama_stack/providers/inline/datasetio/localfs/config.py +23 -0
  253. llama_stack/providers/inline/datasetio/localfs/datasetio.py +113 -0
  254. llama_stack/providers/inline/eval/__init__.py +5 -0
  255. llama_stack/providers/inline/eval/meta_reference/__init__.py +28 -0
  256. llama_stack/providers/inline/eval/meta_reference/config.py +23 -0
  257. llama_stack/providers/inline/eval/meta_reference/eval.py +259 -0
  258. llama_stack/providers/inline/files/localfs/__init__.py +20 -0
  259. llama_stack/providers/inline/files/localfs/config.py +31 -0
  260. llama_stack/providers/inline/files/localfs/files.py +219 -0
  261. llama_stack/providers/inline/inference/__init__.py +5 -0
  262. llama_stack/providers/{impls/meta_reference/inference → inline/inference/meta_reference}/__init__.py +4 -4
  263. llama_stack/providers/inline/inference/meta_reference/common.py +24 -0
  264. llama_stack/providers/inline/inference/meta_reference/config.py +68 -0
  265. llama_stack/providers/inline/inference/meta_reference/generators.py +211 -0
  266. llama_stack/providers/inline/inference/meta_reference/inference.py +158 -0
  267. llama_stack/providers/inline/inference/meta_reference/model_parallel.py +96 -0
  268. llama_stack/providers/{impls/meta_reference/inference → inline/inference/meta_reference}/parallel_utils.py +56 -73
  269. llama_stack/providers/inline/inference/sentence_transformers/__init__.py +22 -0
  270. llama_stack/providers/{impls/meta_reference/agents → inline/inference/sentence_transformers}/config.py +6 -4
  271. llama_stack/providers/inline/inference/sentence_transformers/sentence_transformers.py +83 -0
  272. llama_stack/providers/inline/post_training/__init__.py +5 -0
  273. llama_stack/providers/inline/post_training/common/__init__.py +5 -0
  274. llama_stack/providers/inline/post_training/common/utils.py +35 -0
  275. llama_stack/providers/inline/post_training/common/validator.py +36 -0
  276. llama_stack/providers/inline/post_training/huggingface/__init__.py +27 -0
  277. llama_stack/providers/inline/post_training/huggingface/config.py +83 -0
  278. llama_stack/providers/inline/post_training/huggingface/post_training.py +208 -0
  279. llama_stack/providers/inline/post_training/huggingface/recipes/__init__.py +5 -0
  280. llama_stack/providers/inline/post_training/huggingface/recipes/finetune_single_device.py +519 -0
  281. llama_stack/providers/inline/post_training/huggingface/recipes/finetune_single_device_dpo.py +485 -0
  282. llama_stack/providers/inline/post_training/huggingface/utils.py +269 -0
  283. llama_stack/providers/inline/post_training/torchtune/__init__.py +27 -0
  284. llama_stack/providers/inline/post_training/torchtune/common/__init__.py +5 -0
  285. llama_stack/providers/inline/post_training/torchtune/common/checkpointer.py +240 -0
  286. llama_stack/providers/inline/post_training/torchtune/common/utils.py +99 -0
  287. llama_stack/providers/inline/post_training/torchtune/config.py +20 -0
  288. llama_stack/providers/inline/post_training/torchtune/datasets/__init__.py +5 -0
  289. llama_stack/providers/inline/post_training/torchtune/datasets/format_adapter.py +57 -0
  290. llama_stack/providers/inline/post_training/torchtune/datasets/sft.py +78 -0
  291. llama_stack/providers/inline/post_training/torchtune/post_training.py +178 -0
  292. llama_stack/providers/inline/post_training/torchtune/recipes/__init__.py +5 -0
  293. llama_stack/providers/inline/post_training/torchtune/recipes/lora_finetuning_single_device.py +588 -0
  294. llama_stack/providers/inline/safety/__init__.py +5 -0
  295. llama_stack/providers/{impls/meta_reference/codeshield → inline/safety/code_scanner}/__init__.py +4 -2
  296. llama_stack/providers/inline/safety/code_scanner/code_scanner.py +128 -0
  297. llama_stack/providers/{impls/meta_reference/memory → inline/safety/code_scanner}/config.py +5 -3
  298. llama_stack/providers/inline/safety/llama_guard/__init__.py +19 -0
  299. llama_stack/providers/inline/safety/llama_guard/config.py +19 -0
  300. llama_stack/providers/inline/safety/llama_guard/llama_guard.py +489 -0
  301. llama_stack/providers/{adapters/memory/sample → inline/safety/prompt_guard}/__init__.py +4 -4
  302. llama_stack/providers/inline/safety/prompt_guard/config.py +32 -0
  303. llama_stack/providers/inline/safety/prompt_guard/prompt_guard.py +131 -0
  304. llama_stack/providers/inline/scoring/__init__.py +5 -0
  305. llama_stack/providers/inline/scoring/basic/__init__.py +25 -0
  306. llama_stack/providers/{adapters/memory/weaviate → inline/scoring/basic}/config.py +5 -7
  307. llama_stack/providers/inline/scoring/basic/scoring.py +126 -0
  308. llama_stack/providers/inline/scoring/basic/scoring_fn/__init__.py +5 -0
  309. llama_stack/providers/inline/scoring/basic/scoring_fn/docvqa_scoring_fn.py +240 -0
  310. llama_stack/providers/inline/scoring/basic/scoring_fn/equality_scoring_fn.py +41 -0
  311. llama_stack/providers/inline/scoring/basic/scoring_fn/fn_defs/__init__.py +5 -0
  312. llama_stack/providers/inline/scoring/basic/scoring_fn/fn_defs/docvqa.py +21 -0
  313. llama_stack/providers/inline/scoring/basic/scoring_fn/fn_defs/equality.py +21 -0
  314. llama_stack/providers/inline/scoring/basic/scoring_fn/fn_defs/ifeval.py +23 -0
  315. llama_stack/providers/inline/scoring/basic/scoring_fn/fn_defs/regex_parser_math_response.py +27 -0
  316. llama_stack/providers/inline/scoring/basic/scoring_fn/fn_defs/regex_parser_multiple_choice_answer.py +71 -0
  317. llama_stack/providers/inline/scoring/basic/scoring_fn/fn_defs/subset_of.py +21 -0
  318. llama_stack/providers/inline/scoring/basic/scoring_fn/ifeval_scoring_fn.py +80 -0
  319. llama_stack/providers/inline/scoring/basic/scoring_fn/regex_parser_math_response_scoring_fn.py +66 -0
  320. llama_stack/providers/inline/scoring/basic/scoring_fn/regex_parser_scoring_fn.py +58 -0
  321. llama_stack/providers/inline/scoring/basic/scoring_fn/subset_of_scoring_fn.py +38 -0
  322. llama_stack/providers/inline/scoring/basic/utils/__init__.py +5 -0
  323. llama_stack/providers/inline/scoring/basic/utils/ifeval_utils.py +3319 -0
  324. llama_stack/providers/inline/scoring/basic/utils/math_utils.py +330 -0
  325. llama_stack/providers/inline/scoring/braintrust/__init__.py +27 -0
  326. llama_stack/providers/inline/scoring/braintrust/braintrust.py +230 -0
  327. llama_stack/providers/inline/scoring/braintrust/config.py +21 -0
  328. llama_stack/providers/inline/scoring/braintrust/scoring_fn/__init__.py +5 -0
  329. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/__init__.py +5 -0
  330. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/answer_correctness.py +24 -0
  331. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/answer_relevancy.py +24 -0
  332. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/answer_similarity.py +24 -0
  333. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/context_entity_recall.py +24 -0
  334. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/context_precision.py +24 -0
  335. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/context_recall.py +24 -0
  336. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/context_relevancy.py +23 -0
  337. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/factuality.py +24 -0
  338. llama_stack/providers/inline/scoring/braintrust/scoring_fn/fn_defs/faithfulness.py +24 -0
  339. llama_stack/providers/inline/scoring/llm_as_judge/__init__.py +21 -0
  340. llama_stack/providers/inline/scoring/llm_as_judge/config.py +14 -0
  341. llama_stack/providers/inline/scoring/llm_as_judge/scoring.py +113 -0
  342. llama_stack/providers/inline/scoring/llm_as_judge/scoring_fn/__init__.py +5 -0
  343. llama_stack/providers/inline/scoring/llm_as_judge/scoring_fn/fn_defs/__init__.py +5 -0
  344. llama_stack/providers/inline/scoring/llm_as_judge/scoring_fn/fn_defs/llm_as_judge_405b_simpleqa.py +96 -0
  345. llama_stack/providers/inline/scoring/llm_as_judge/scoring_fn/fn_defs/llm_as_judge_base.py +20 -0
  346. llama_stack/providers/inline/scoring/llm_as_judge/scoring_fn/llm_as_judge_scoring_fn.py +81 -0
  347. llama_stack/providers/inline/telemetry/__init__.py +5 -0
  348. llama_stack/providers/inline/telemetry/meta_reference/__init__.py +21 -0
  349. llama_stack/providers/inline/telemetry/meta_reference/config.py +47 -0
  350. llama_stack/providers/inline/telemetry/meta_reference/telemetry.py +252 -0
  351. llama_stack/providers/inline/tool_runtime/__init__.py +5 -0
  352. llama_stack/providers/inline/tool_runtime/rag/__init__.py +19 -0
  353. llama_stack/providers/{impls/meta_reference/telemetry → inline/tool_runtime/rag}/config.py +5 -3
  354. llama_stack/providers/inline/tool_runtime/rag/context_retriever.py +77 -0
  355. llama_stack/providers/inline/tool_runtime/rag/memory.py +332 -0
  356. llama_stack/providers/inline/vector_io/__init__.py +5 -0
  357. llama_stack/providers/inline/vector_io/chroma/__init__.py +19 -0
  358. llama_stack/providers/inline/vector_io/chroma/config.py +30 -0
  359. llama_stack/providers/inline/vector_io/faiss/__init__.py +21 -0
  360. llama_stack/providers/inline/vector_io/faiss/config.py +26 -0
  361. llama_stack/providers/inline/vector_io/faiss/faiss.py +293 -0
  362. llama_stack/providers/inline/vector_io/milvus/__init__.py +19 -0
  363. llama_stack/providers/inline/vector_io/milvus/config.py +29 -0
  364. llama_stack/providers/inline/vector_io/qdrant/__init__.py +20 -0
  365. llama_stack/providers/inline/vector_io/qdrant/config.py +29 -0
  366. llama_stack/providers/inline/vector_io/sqlite_vec/__init__.py +20 -0
  367. llama_stack/providers/inline/vector_io/sqlite_vec/config.py +26 -0
  368. llama_stack/providers/inline/vector_io/sqlite_vec/sqlite_vec.py +483 -0
  369. llama_stack/providers/registry/agents.py +16 -18
  370. llama_stack/providers/registry/batches.py +26 -0
  371. llama_stack/providers/registry/datasetio.py +49 -0
  372. llama_stack/providers/registry/eval.py +46 -0
  373. llama_stack/providers/registry/files.py +31 -0
  374. llama_stack/providers/registry/inference.py +273 -118
  375. llama_stack/providers/registry/post_training.py +69 -0
  376. llama_stack/providers/registry/safety.py +46 -41
  377. llama_stack/providers/registry/scoring.py +51 -0
  378. llama_stack/providers/registry/tool_runtime.py +87 -0
  379. llama_stack/providers/registry/vector_io.py +828 -0
  380. llama_stack/providers/remote/__init__.py +5 -0
  381. llama_stack/providers/remote/agents/__init__.py +5 -0
  382. llama_stack/providers/remote/datasetio/__init__.py +5 -0
  383. llama_stack/providers/{adapters/memory/chroma → remote/datasetio/huggingface}/__init__.py +7 -4
  384. llama_stack/providers/remote/datasetio/huggingface/config.py +23 -0
  385. llama_stack/providers/remote/datasetio/huggingface/huggingface.py +99 -0
  386. llama_stack/providers/remote/datasetio/nvidia/__init__.py +23 -0
  387. llama_stack/providers/remote/datasetio/nvidia/config.py +61 -0
  388. llama_stack/providers/remote/datasetio/nvidia/datasetio.py +116 -0
  389. llama_stack/providers/remote/eval/__init__.py +5 -0
  390. llama_stack/providers/remote/eval/nvidia/__init__.py +31 -0
  391. llama_stack/providers/remote/eval/nvidia/config.py +29 -0
  392. llama_stack/providers/remote/eval/nvidia/eval.py +162 -0
  393. llama_stack/providers/remote/files/s3/__init__.py +19 -0
  394. llama_stack/providers/remote/files/s3/config.py +42 -0
  395. llama_stack/providers/remote/files/s3/files.py +313 -0
  396. llama_stack/providers/remote/inference/__init__.py +5 -0
  397. llama_stack/providers/{adapters/safety/sample → remote/inference/anthropic}/__init__.py +4 -6
  398. llama_stack/providers/remote/inference/anthropic/anthropic.py +36 -0
  399. llama_stack/providers/remote/inference/anthropic/config.py +28 -0
  400. llama_stack/providers/{impls/meta_reference/telemetry → remote/inference/azure}/__init__.py +4 -4
  401. llama_stack/providers/remote/inference/azure/azure.py +25 -0
  402. llama_stack/providers/remote/inference/azure/config.py +61 -0
  403. llama_stack/providers/{adapters → remote}/inference/bedrock/__init__.py +18 -17
  404. llama_stack/providers/remote/inference/bedrock/bedrock.py +142 -0
  405. llama_stack/providers/{adapters/inference/sample → remote/inference/bedrock}/config.py +3 -4
  406. llama_stack/providers/remote/inference/bedrock/models.py +29 -0
  407. llama_stack/providers/remote/inference/cerebras/__init__.py +19 -0
  408. llama_stack/providers/remote/inference/cerebras/cerebras.py +28 -0
  409. llama_stack/providers/remote/inference/cerebras/config.py +30 -0
  410. llama_stack/providers/{adapters → remote}/inference/databricks/__init__.py +4 -5
  411. llama_stack/providers/remote/inference/databricks/config.py +37 -0
  412. llama_stack/providers/remote/inference/databricks/databricks.py +44 -0
  413. llama_stack/providers/{adapters → remote}/inference/fireworks/__init__.py +8 -4
  414. llama_stack/providers/remote/inference/fireworks/config.py +27 -0
  415. llama_stack/providers/remote/inference/fireworks/fireworks.py +27 -0
  416. llama_stack/providers/{adapters/memory/pgvector → remote/inference/gemini}/__init__.py +4 -4
  417. llama_stack/providers/remote/inference/gemini/config.py +28 -0
  418. llama_stack/providers/remote/inference/gemini/gemini.py +82 -0
  419. llama_stack/providers/remote/inference/groq/__init__.py +15 -0
  420. llama_stack/providers/remote/inference/groq/config.py +34 -0
  421. llama_stack/providers/remote/inference/groq/groq.py +18 -0
  422. llama_stack/providers/remote/inference/llama_openai_compat/__init__.py +15 -0
  423. llama_stack/providers/remote/inference/llama_openai_compat/config.py +34 -0
  424. llama_stack/providers/remote/inference/llama_openai_compat/llama.py +46 -0
  425. llama_stack/providers/remote/inference/nvidia/__init__.py +23 -0
  426. llama_stack/providers/remote/inference/nvidia/config.py +64 -0
  427. llama_stack/providers/remote/inference/nvidia/nvidia.py +61 -0
  428. llama_stack/providers/{adapters/safety/sample/config.py → remote/inference/nvidia/utils.py} +3 -4
  429. llama_stack/providers/{impls/vllm → remote/inference/ollama}/__init__.py +4 -6
  430. llama_stack/providers/remote/inference/ollama/config.py +25 -0
  431. llama_stack/providers/remote/inference/ollama/ollama.py +102 -0
  432. llama_stack/providers/{adapters/telemetry/opentelemetry → remote/inference/openai}/__init__.py +4 -4
  433. llama_stack/providers/remote/inference/openai/config.py +39 -0
  434. llama_stack/providers/remote/inference/openai/openai.py +38 -0
  435. llama_stack/providers/remote/inference/passthrough/__init__.py +23 -0
  436. llama_stack/providers/remote/inference/passthrough/config.py +34 -0
  437. llama_stack/providers/remote/inference/passthrough/passthrough.py +122 -0
  438. llama_stack/providers/remote/inference/runpod/__init__.py +16 -0
  439. llama_stack/providers/remote/inference/runpod/config.py +32 -0
  440. llama_stack/providers/remote/inference/runpod/runpod.py +42 -0
  441. llama_stack/providers/remote/inference/sambanova/__init__.py +16 -0
  442. llama_stack/providers/remote/inference/sambanova/config.py +34 -0
  443. llama_stack/providers/remote/inference/sambanova/sambanova.py +28 -0
  444. llama_stack/providers/{adapters → remote}/inference/tgi/__init__.py +3 -4
  445. llama_stack/providers/remote/inference/tgi/config.py +76 -0
  446. llama_stack/providers/remote/inference/tgi/tgi.py +85 -0
  447. llama_stack/providers/{adapters → remote}/inference/together/__init__.py +8 -4
  448. llama_stack/providers/remote/inference/together/config.py +27 -0
  449. llama_stack/providers/remote/inference/together/together.py +102 -0
  450. llama_stack/providers/remote/inference/vertexai/__init__.py +15 -0
  451. llama_stack/providers/remote/inference/vertexai/config.py +48 -0
  452. llama_stack/providers/remote/inference/vertexai/vertexai.py +54 -0
  453. llama_stack/providers/remote/inference/vllm/__init__.py +22 -0
  454. llama_stack/providers/remote/inference/vllm/config.py +59 -0
  455. llama_stack/providers/remote/inference/vllm/vllm.py +111 -0
  456. llama_stack/providers/remote/inference/watsonx/__init__.py +15 -0
  457. llama_stack/providers/remote/inference/watsonx/config.py +45 -0
  458. llama_stack/providers/remote/inference/watsonx/watsonx.py +336 -0
  459. llama_stack/providers/remote/post_training/__init__.py +5 -0
  460. llama_stack/providers/remote/post_training/nvidia/__init__.py +23 -0
  461. llama_stack/providers/remote/post_training/nvidia/config.py +113 -0
  462. llama_stack/providers/remote/post_training/nvidia/models.py +27 -0
  463. llama_stack/providers/remote/post_training/nvidia/post_training.py +430 -0
  464. llama_stack/providers/remote/post_training/nvidia/utils.py +63 -0
  465. llama_stack/providers/remote/safety/__init__.py +5 -0
  466. llama_stack/providers/remote/safety/bedrock/bedrock.py +111 -0
  467. llama_stack/providers/remote/safety/bedrock/config.py +14 -0
  468. llama_stack/providers/{adapters/inference/sample → remote/safety/nvidia}/__init__.py +5 -4
  469. llama_stack/providers/remote/safety/nvidia/config.py +40 -0
  470. llama_stack/providers/remote/safety/nvidia/nvidia.py +161 -0
  471. llama_stack/providers/{adapters/agents/sample → remote/safety/sambanova}/__init__.py +5 -4
  472. llama_stack/providers/remote/safety/sambanova/config.py +37 -0
  473. llama_stack/providers/remote/safety/sambanova/sambanova.py +98 -0
  474. llama_stack/providers/remote/tool_runtime/__init__.py +5 -0
  475. llama_stack/providers/remote/tool_runtime/bing_search/__init__.py +21 -0
  476. llama_stack/providers/remote/tool_runtime/bing_search/bing_search.py +112 -0
  477. llama_stack/providers/remote/tool_runtime/bing_search/config.py +22 -0
  478. llama_stack/providers/remote/tool_runtime/brave_search/__init__.py +20 -0
  479. llama_stack/providers/remote/tool_runtime/brave_search/brave_search.py +148 -0
  480. llama_stack/providers/remote/tool_runtime/brave_search/config.py +27 -0
  481. llama_stack/providers/remote/tool_runtime/model_context_protocol/__init__.py +15 -0
  482. llama_stack/providers/remote/tool_runtime/model_context_protocol/config.py +20 -0
  483. llama_stack/providers/remote/tool_runtime/model_context_protocol/model_context_protocol.py +73 -0
  484. llama_stack/providers/remote/tool_runtime/tavily_search/__init__.py +20 -0
  485. llama_stack/providers/remote/tool_runtime/tavily_search/config.py +27 -0
  486. llama_stack/providers/remote/tool_runtime/tavily_search/tavily_search.py +84 -0
  487. llama_stack/providers/remote/tool_runtime/wolfram_alpha/__init__.py +22 -0
  488. llama_stack/providers/remote/tool_runtime/wolfram_alpha/config.py +21 -0
  489. llama_stack/providers/remote/tool_runtime/wolfram_alpha/wolfram_alpha.py +140 -0
  490. llama_stack/providers/remote/vector_io/__init__.py +5 -0
  491. llama_stack/providers/remote/vector_io/chroma/__init__.py +17 -0
  492. llama_stack/providers/remote/vector_io/chroma/chroma.py +215 -0
  493. llama_stack/providers/remote/vector_io/chroma/config.py +28 -0
  494. llama_stack/providers/remote/vector_io/milvus/__init__.py +18 -0
  495. llama_stack/providers/remote/vector_io/milvus/config.py +35 -0
  496. llama_stack/providers/remote/vector_io/milvus/milvus.py +375 -0
  497. llama_stack/providers/remote/vector_io/pgvector/__init__.py +17 -0
  498. llama_stack/providers/remote/vector_io/pgvector/config.py +47 -0
  499. llama_stack/providers/remote/vector_io/pgvector/pgvector.py +460 -0
  500. llama_stack/providers/remote/vector_io/qdrant/__init__.py +17 -0
  501. llama_stack/providers/remote/vector_io/qdrant/config.py +37 -0
  502. llama_stack/providers/remote/vector_io/qdrant/qdrant.py +265 -0
  503. llama_stack/providers/remote/vector_io/weaviate/__init__.py +17 -0
  504. llama_stack/providers/remote/vector_io/weaviate/config.py +32 -0
  505. llama_stack/providers/remote/vector_io/weaviate/weaviate.py +393 -0
  506. llama_stack/providers/utils/bedrock/__init__.py +5 -0
  507. llama_stack/providers/utils/bedrock/client.py +74 -0
  508. llama_stack/providers/utils/bedrock/config.py +64 -0
  509. llama_stack/providers/utils/bedrock/refreshable_boto_session.py +112 -0
  510. llama_stack/providers/utils/common/__init__.py +5 -0
  511. llama_stack/providers/utils/common/data_schema_validator.py +103 -0
  512. llama_stack/providers/utils/datasetio/__init__.py +5 -0
  513. llama_stack/providers/utils/datasetio/url_utils.py +47 -0
  514. llama_stack/providers/utils/files/__init__.py +5 -0
  515. llama_stack/providers/utils/files/form_data.py +69 -0
  516. llama_stack/providers/utils/inference/__init__.py +8 -7
  517. llama_stack/providers/utils/inference/embedding_mixin.py +101 -0
  518. llama_stack/providers/utils/inference/inference_store.py +264 -0
  519. llama_stack/providers/utils/inference/litellm_openai_mixin.py +336 -0
  520. llama_stack/providers/utils/inference/model_registry.py +173 -23
  521. llama_stack/providers/utils/inference/openai_compat.py +1261 -49
  522. llama_stack/providers/utils/inference/openai_mixin.py +506 -0
  523. llama_stack/providers/utils/inference/prompt_adapter.py +365 -67
  524. llama_stack/providers/utils/kvstore/api.py +6 -6
  525. llama_stack/providers/utils/kvstore/config.py +28 -48
  526. llama_stack/providers/utils/kvstore/kvstore.py +61 -15
  527. llama_stack/providers/utils/kvstore/mongodb/__init__.py +9 -0
  528. llama_stack/providers/utils/kvstore/mongodb/mongodb.py +82 -0
  529. llama_stack/providers/utils/kvstore/postgres/__init__.py +7 -0
  530. llama_stack/providers/utils/kvstore/postgres/postgres.py +114 -0
  531. llama_stack/providers/utils/kvstore/redis/redis.py +33 -9
  532. llama_stack/providers/utils/kvstore/sqlite/config.py +2 -1
  533. llama_stack/providers/utils/kvstore/sqlite/sqlite.py +123 -22
  534. llama_stack/providers/utils/memory/file_utils.py +1 -1
  535. llama_stack/providers/utils/memory/openai_vector_store_mixin.py +1304 -0
  536. llama_stack/providers/utils/memory/vector_store.py +220 -82
  537. llama_stack/providers/utils/pagination.py +43 -0
  538. llama_stack/providers/utils/responses/__init__.py +5 -0
  539. llama_stack/providers/utils/responses/responses_store.py +292 -0
  540. llama_stack/providers/utils/scheduler.py +270 -0
  541. llama_stack/providers/utils/scoring/__init__.py +5 -0
  542. llama_stack/providers/utils/scoring/aggregation_utils.py +75 -0
  543. llama_stack/providers/utils/scoring/base_scoring_fn.py +114 -0
  544. llama_stack/providers/utils/scoring/basic_scoring_utils.py +26 -0
  545. llama_stack/providers/utils/sqlstore/__init__.py +5 -0
  546. llama_stack/providers/utils/sqlstore/api.py +128 -0
  547. llama_stack/providers/utils/sqlstore/authorized_sqlstore.py +319 -0
  548. llama_stack/providers/utils/sqlstore/sqlalchemy_sqlstore.py +343 -0
  549. llama_stack/providers/utils/sqlstore/sqlstore.py +70 -0
  550. llama_stack/providers/utils/telemetry/trace_protocol.py +142 -0
  551. llama_stack/providers/utils/telemetry/tracing.py +192 -53
  552. llama_stack/providers/utils/tools/__init__.py +5 -0
  553. llama_stack/providers/utils/tools/mcp.py +148 -0
  554. llama_stack/providers/utils/tools/ttl_dict.py +70 -0
  555. llama_stack/providers/utils/vector_io/__init__.py +5 -0
  556. llama_stack/providers/utils/vector_io/vector_utils.py +156 -0
  557. llama_stack/schema_utils.py +118 -0
  558. llama_stack/strong_typing/__init__.py +19 -0
  559. llama_stack/strong_typing/auxiliary.py +228 -0
  560. llama_stack/strong_typing/classdef.py +440 -0
  561. llama_stack/strong_typing/core.py +46 -0
  562. llama_stack/strong_typing/deserializer.py +877 -0
  563. llama_stack/strong_typing/docstring.py +409 -0
  564. llama_stack/strong_typing/exception.py +23 -0
  565. llama_stack/strong_typing/inspection.py +1085 -0
  566. llama_stack/strong_typing/mapping.py +40 -0
  567. llama_stack/strong_typing/name.py +182 -0
  568. llama_stack/strong_typing/py.typed +0 -0
  569. llama_stack/strong_typing/schema.py +792 -0
  570. llama_stack/strong_typing/serialization.py +97 -0
  571. llama_stack/strong_typing/serializer.py +500 -0
  572. llama_stack/strong_typing/slots.py +27 -0
  573. llama_stack/strong_typing/topological.py +89 -0
  574. llama_stack/testing/__init__.py +5 -0
  575. llama_stack/testing/api_recorder.py +956 -0
  576. llama_stack/ui/node_modules/flatted/python/flatted.py +149 -0
  577. llama_stack-0.3.4.dist-info/METADATA +261 -0
  578. llama_stack-0.3.4.dist-info/RECORD +625 -0
  579. {llama_stack-0.0.42.dist-info → llama_stack-0.3.4.dist-info}/WHEEL +1 -1
  580. llama_stack/apis/agents/client.py +0 -292
  581. llama_stack/apis/agents/event_logger.py +0 -184
  582. llama_stack/apis/batch_inference/batch_inference.py +0 -72
  583. llama_stack/apis/common/deployment_types.py +0 -31
  584. llama_stack/apis/dataset/dataset.py +0 -63
  585. llama_stack/apis/evals/evals.py +0 -122
  586. llama_stack/apis/inference/client.py +0 -197
  587. llama_stack/apis/inspect/client.py +0 -82
  588. llama_stack/apis/memory/client.py +0 -155
  589. llama_stack/apis/memory/memory.py +0 -65
  590. llama_stack/apis/memory_banks/__init__.py +0 -7
  591. llama_stack/apis/memory_banks/client.py +0 -101
  592. llama_stack/apis/memory_banks/memory_banks.py +0 -78
  593. llama_stack/apis/models/client.py +0 -83
  594. llama_stack/apis/reward_scoring/__init__.py +0 -7
  595. llama_stack/apis/reward_scoring/reward_scoring.py +0 -55
  596. llama_stack/apis/safety/client.py +0 -105
  597. llama_stack/apis/shields/client.py +0 -79
  598. llama_stack/cli/download.py +0 -340
  599. llama_stack/cli/model/describe.py +0 -82
  600. llama_stack/cli/model/download.py +0 -24
  601. llama_stack/cli/model/list.py +0 -62
  602. llama_stack/cli/model/model.py +0 -34
  603. llama_stack/cli/model/prompt_format.py +0 -112
  604. llama_stack/cli/model/safety_models.py +0 -52
  605. llama_stack/cli/stack/build.py +0 -299
  606. llama_stack/cli/stack/configure.py +0 -178
  607. llama_stack/distribution/build.py +0 -123
  608. llama_stack/distribution/build_conda_env.sh +0 -136
  609. llama_stack/distribution/build_container.sh +0 -142
  610. llama_stack/distribution/common.sh +0 -40
  611. llama_stack/distribution/configure_container.sh +0 -47
  612. llama_stack/distribution/datatypes.py +0 -139
  613. llama_stack/distribution/distribution.py +0 -58
  614. llama_stack/distribution/inspect.py +0 -67
  615. llama_stack/distribution/request_headers.py +0 -57
  616. llama_stack/distribution/resolver.py +0 -323
  617. llama_stack/distribution/routers/__init__.py +0 -48
  618. llama_stack/distribution/routers/routers.py +0 -158
  619. llama_stack/distribution/routers/routing_tables.py +0 -173
  620. llama_stack/distribution/server/endpoints.py +0 -48
  621. llama_stack/distribution/server/server.py +0 -343
  622. llama_stack/distribution/start_conda_env.sh +0 -42
  623. llama_stack/distribution/start_container.sh +0 -64
  624. llama_stack/distribution/templates/local-bedrock-conda-example-build.yaml +0 -10
  625. llama_stack/distribution/templates/local-build.yaml +0 -10
  626. llama_stack/distribution/templates/local-databricks-build.yaml +0 -10
  627. llama_stack/distribution/templates/local-fireworks-build.yaml +0 -10
  628. llama_stack/distribution/templates/local-hf-endpoint-build.yaml +0 -10
  629. llama_stack/distribution/templates/local-hf-serverless-build.yaml +0 -10
  630. llama_stack/distribution/templates/local-ollama-build.yaml +0 -10
  631. llama_stack/distribution/templates/local-tgi-build.yaml +0 -10
  632. llama_stack/distribution/templates/local-together-build.yaml +0 -10
  633. llama_stack/distribution/templates/local-vllm-build.yaml +0 -10
  634. llama_stack/distribution/utils/exec.py +0 -105
  635. llama_stack/providers/adapters/agents/sample/sample.py +0 -18
  636. llama_stack/providers/adapters/inference/bedrock/bedrock.py +0 -451
  637. llama_stack/providers/adapters/inference/bedrock/config.py +0 -55
  638. llama_stack/providers/adapters/inference/databricks/config.py +0 -21
  639. llama_stack/providers/adapters/inference/databricks/databricks.py +0 -125
  640. llama_stack/providers/adapters/inference/fireworks/config.py +0 -20
  641. llama_stack/providers/adapters/inference/fireworks/fireworks.py +0 -130
  642. llama_stack/providers/adapters/inference/ollama/__init__.py +0 -19
  643. llama_stack/providers/adapters/inference/ollama/ollama.py +0 -175
  644. llama_stack/providers/adapters/inference/sample/sample.py +0 -23
  645. llama_stack/providers/adapters/inference/tgi/config.py +0 -43
  646. llama_stack/providers/adapters/inference/tgi/tgi.py +0 -200
  647. llama_stack/providers/adapters/inference/together/config.py +0 -22
  648. llama_stack/providers/adapters/inference/together/together.py +0 -143
  649. llama_stack/providers/adapters/memory/chroma/chroma.py +0 -157
  650. llama_stack/providers/adapters/memory/pgvector/config.py +0 -17
  651. llama_stack/providers/adapters/memory/pgvector/pgvector.py +0 -211
  652. llama_stack/providers/adapters/memory/sample/sample.py +0 -23
  653. llama_stack/providers/adapters/memory/weaviate/__init__.py +0 -15
  654. llama_stack/providers/adapters/memory/weaviate/weaviate.py +0 -190
  655. llama_stack/providers/adapters/safety/bedrock/bedrock.py +0 -113
  656. llama_stack/providers/adapters/safety/bedrock/config.py +0 -16
  657. llama_stack/providers/adapters/safety/sample/sample.py +0 -23
  658. llama_stack/providers/adapters/safety/together/__init__.py +0 -18
  659. llama_stack/providers/adapters/safety/together/config.py +0 -26
  660. llama_stack/providers/adapters/safety/together/together.py +0 -101
  661. llama_stack/providers/adapters/telemetry/opentelemetry/config.py +0 -12
  662. llama_stack/providers/adapters/telemetry/opentelemetry/opentelemetry.py +0 -201
  663. llama_stack/providers/adapters/telemetry/sample/__init__.py +0 -17
  664. llama_stack/providers/adapters/telemetry/sample/config.py +0 -12
  665. llama_stack/providers/adapters/telemetry/sample/sample.py +0 -18
  666. llama_stack/providers/impls/meta_reference/agents/agent_instance.py +0 -844
  667. llama_stack/providers/impls/meta_reference/agents/agents.py +0 -161
  668. llama_stack/providers/impls/meta_reference/agents/persistence.py +0 -84
  669. llama_stack/providers/impls/meta_reference/agents/rag/context_retriever.py +0 -74
  670. llama_stack/providers/impls/meta_reference/agents/safety.py +0 -57
  671. llama_stack/providers/impls/meta_reference/agents/tests/code_execution.py +0 -93
  672. llama_stack/providers/impls/meta_reference/agents/tests/test_chat_agent.py +0 -305
  673. llama_stack/providers/impls/meta_reference/agents/tools/base.py +0 -20
  674. llama_stack/providers/impls/meta_reference/agents/tools/builtin.py +0 -375
  675. llama_stack/providers/impls/meta_reference/agents/tools/ipython_tool/code_env_prefix.py +0 -133
  676. llama_stack/providers/impls/meta_reference/agents/tools/ipython_tool/code_execution.py +0 -256
  677. llama_stack/providers/impls/meta_reference/agents/tools/ipython_tool/matplotlib_custom_backend.py +0 -87
  678. llama_stack/providers/impls/meta_reference/agents/tools/ipython_tool/utils.py +0 -21
  679. llama_stack/providers/impls/meta_reference/agents/tools/safety.py +0 -43
  680. llama_stack/providers/impls/meta_reference/codeshield/code_scanner.py +0 -58
  681. llama_stack/providers/impls/meta_reference/inference/config.py +0 -45
  682. llama_stack/providers/impls/meta_reference/inference/generation.py +0 -376
  683. llama_stack/providers/impls/meta_reference/inference/inference.py +0 -280
  684. llama_stack/providers/impls/meta_reference/inference/model_parallel.py +0 -99
  685. llama_stack/providers/impls/meta_reference/inference/quantization/fp8_impls.py +0 -184
  686. llama_stack/providers/impls/meta_reference/inference/quantization/fp8_txest_disabled.py +0 -76
  687. llama_stack/providers/impls/meta_reference/inference/quantization/loader.py +0 -97
  688. llama_stack/providers/impls/meta_reference/inference/quantization/scripts/quantize_checkpoint.py +0 -161
  689. llama_stack/providers/impls/meta_reference/memory/__init__.py +0 -19
  690. llama_stack/providers/impls/meta_reference/memory/faiss.py +0 -113
  691. llama_stack/providers/impls/meta_reference/safety/__init__.py +0 -17
  692. llama_stack/providers/impls/meta_reference/safety/base.py +0 -57
  693. llama_stack/providers/impls/meta_reference/safety/config.py +0 -48
  694. llama_stack/providers/impls/meta_reference/safety/llama_guard.py +0 -268
  695. llama_stack/providers/impls/meta_reference/safety/prompt_guard.py +0 -145
  696. llama_stack/providers/impls/meta_reference/safety/safety.py +0 -112
  697. llama_stack/providers/impls/meta_reference/telemetry/console.py +0 -89
  698. llama_stack/providers/impls/vllm/config.py +0 -35
  699. llama_stack/providers/impls/vllm/vllm.py +0 -241
  700. llama_stack/providers/registry/memory.py +0 -78
  701. llama_stack/providers/registry/telemetry.py +0 -44
  702. llama_stack/providers/tests/agents/test_agents.py +0 -210
  703. llama_stack/providers/tests/inference/test_inference.py +0 -257
  704. llama_stack/providers/tests/inference/test_prompt_adapter.py +0 -126
  705. llama_stack/providers/tests/memory/test_memory.py +0 -136
  706. llama_stack/providers/tests/resolver.py +0 -100
  707. llama_stack/providers/tests/safety/test_safety.py +0 -77
  708. llama_stack-0.0.42.dist-info/METADATA +0 -137
  709. llama_stack-0.0.42.dist-info/RECORD +0 -256
  710. /llama_stack/{distribution → core}/__init__.py +0 -0
  711. /llama_stack/{distribution/server → core/access_control}/__init__.py +0 -0
  712. /llama_stack/{distribution/utils → core/conversations}/__init__.py +0 -0
  713. /llama_stack/{providers/adapters → core/prompts}/__init__.py +0 -0
  714. /llama_stack/{providers/adapters/agents → core/routing_tables}/__init__.py +0 -0
  715. /llama_stack/{providers/adapters/inference → core/server}/__init__.py +0 -0
  716. /llama_stack/{providers/adapters/memory → core/storage}/__init__.py +0 -0
  717. /llama_stack/{providers/adapters/safety → core/ui}/__init__.py +0 -0
  718. /llama_stack/{providers/adapters/telemetry → core/ui/modules}/__init__.py +0 -0
  719. /llama_stack/{providers/impls → core/ui/page}/__init__.py +0 -0
  720. /llama_stack/{providers/impls/meta_reference → core/ui/page/distribution}/__init__.py +0 -0
  721. /llama_stack/{providers/impls/meta_reference/agents/rag → core/ui/page/evaluations}/__init__.py +0 -0
  722. /llama_stack/{providers/impls/meta_reference/agents/tests → core/ui/page/playground}/__init__.py +0 -0
  723. /llama_stack/{providers/impls/meta_reference/agents/tools → core/utils}/__init__.py +0 -0
  724. /llama_stack/{distribution → core}/utils/dynamic.py +0 -0
  725. /llama_stack/{distribution → core}/utils/serialize.py +0 -0
  726. /llama_stack/{providers/impls/meta_reference/agents/tools/ipython_tool → distributions}/__init__.py +0 -0
  727. /llama_stack/{providers/impls/meta_reference/inference/quantization → models}/__init__.py +0 -0
  728. /llama_stack/{providers/impls/meta_reference/inference/quantization/scripts → models/llama}/__init__.py +0 -0
  729. /llama_stack/{providers/tests → models/llama/llama3}/__init__.py +0 -0
  730. /llama_stack/{providers/tests/agents → models/llama/llama3/quantization}/__init__.py +0 -0
  731. /llama_stack/{providers/tests/inference → models/llama/llama3_2}/__init__.py +0 -0
  732. /llama_stack/{providers/tests/memory → models/llama/llama3_3}/__init__.py +0 -0
  733. /llama_stack/{providers/tests/safety → models/llama/llama4}/__init__.py +0 -0
  734. /llama_stack/{scripts → models/llama/llama4/prompt_templates}/__init__.py +0 -0
  735. /llama_stack/providers/{adapters → remote}/safety/bedrock/__init__.py +0 -0
  736. {llama_stack-0.0.42.dist-info → llama_stack-0.3.4.dist-info}/entry_points.txt +0 -0
  737. {llama_stack-0.0.42.dist-info → llama_stack-0.3.4.dist-info/licenses}/LICENSE +0 -0
  738. {llama_stack-0.0.42.dist-info → llama_stack-0.3.4.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,3319 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the terms described in the LICENSE file in
5
+ # the root directory of this source tree.
6
+
7
+ import collections
8
+ import functools
9
+ import json
10
+ import random
11
+ import re
12
+ import string
13
+ from collections.abc import Iterable, Sequence
14
+ from types import MappingProxyType
15
+
16
+ import emoji
17
+ import langdetect
18
+ import nltk
19
+ from pythainlp.tokenize import sent_tokenize as sent_tokenize_thai
20
+ from pythainlp.tokenize import word_tokenize as word_tokenize_thai
21
+
22
+ from llama_stack.log import get_logger
23
+
24
+ logger = get_logger(name=__name__, category="scoring")
25
+
26
+ WORD_LIST = [
27
+ "western",
28
+ "sentence",
29
+ "signal",
30
+ "dump",
31
+ "spot",
32
+ "opposite",
33
+ "bottom",
34
+ "potato",
35
+ "administration",
36
+ "working",
37
+ "welcome",
38
+ "morning",
39
+ "good",
40
+ "agency",
41
+ "primary",
42
+ "wish",
43
+ "responsibility",
44
+ "press",
45
+ "problem",
46
+ "president",
47
+ "steal",
48
+ "brush",
49
+ "read",
50
+ "type",
51
+ "beat",
52
+ "trainer",
53
+ "growth",
54
+ "lock",
55
+ "bone",
56
+ "case",
57
+ "equal",
58
+ "comfortable",
59
+ "region",
60
+ "replacement",
61
+ "performance",
62
+ "mate",
63
+ "walk",
64
+ "medicine",
65
+ "film",
66
+ "thing",
67
+ "rock",
68
+ "tap",
69
+ "total",
70
+ "competition",
71
+ "ease",
72
+ "south",
73
+ "establishment",
74
+ "gather",
75
+ "parking",
76
+ "world",
77
+ "plenty",
78
+ "breath",
79
+ "claim",
80
+ "alcohol",
81
+ "trade",
82
+ "dear",
83
+ "highlight",
84
+ "street",
85
+ "matter",
86
+ "decision",
87
+ "mess",
88
+ "agreement",
89
+ "studio",
90
+ "coach",
91
+ "assist",
92
+ "brain",
93
+ "wing",
94
+ "style",
95
+ "private",
96
+ "top",
97
+ "brown",
98
+ "leg",
99
+ "buy",
100
+ "procedure",
101
+ "method",
102
+ "speed",
103
+ "high",
104
+ "company",
105
+ "valuable",
106
+ "pie",
107
+ "analyst",
108
+ "session",
109
+ "pattern",
110
+ "district",
111
+ "pleasure",
112
+ "dinner",
113
+ "swimming",
114
+ "joke",
115
+ "order",
116
+ "plate",
117
+ "department",
118
+ "motor",
119
+ "cell",
120
+ "spend",
121
+ "cabinet",
122
+ "difference",
123
+ "power",
124
+ "examination",
125
+ "engine",
126
+ "horse",
127
+ "dimension",
128
+ "pay",
129
+ "toe",
130
+ "curve",
131
+ "literature",
132
+ "bother",
133
+ "fire",
134
+ "possibility",
135
+ "debate",
136
+ "activity",
137
+ "passage",
138
+ "hello",
139
+ "cycle",
140
+ "background",
141
+ "quiet",
142
+ "author",
143
+ "effect",
144
+ "actor",
145
+ "page",
146
+ "bicycle",
147
+ "error",
148
+ "throat",
149
+ "attack",
150
+ "character",
151
+ "phone",
152
+ "tea",
153
+ "increase",
154
+ "outcome",
155
+ "file",
156
+ "specific",
157
+ "inspector",
158
+ "internal",
159
+ "potential",
160
+ "staff",
161
+ "building",
162
+ "employer",
163
+ "shoe",
164
+ "hand",
165
+ "direction",
166
+ "garden",
167
+ "purchase",
168
+ "interview",
169
+ "study",
170
+ "recognition",
171
+ "member",
172
+ "spiritual",
173
+ "oven",
174
+ "sandwich",
175
+ "weird",
176
+ "passenger",
177
+ "particular",
178
+ "response",
179
+ "reaction",
180
+ "size",
181
+ "variation",
182
+ "a",
183
+ "cancel",
184
+ "candy",
185
+ "exit",
186
+ "guest",
187
+ "condition",
188
+ "fly",
189
+ "price",
190
+ "weakness",
191
+ "convert",
192
+ "hotel",
193
+ "great",
194
+ "mouth",
195
+ "mind",
196
+ "song",
197
+ "sugar",
198
+ "suspect",
199
+ "telephone",
200
+ "ear",
201
+ "roof",
202
+ "paint",
203
+ "refrigerator",
204
+ "organization",
205
+ "jury",
206
+ "reward",
207
+ "engineering",
208
+ "day",
209
+ "possession",
210
+ "crew",
211
+ "bar",
212
+ "road",
213
+ "description",
214
+ "celebration",
215
+ "score",
216
+ "mark",
217
+ "letter",
218
+ "shower",
219
+ "suggestion",
220
+ "sir",
221
+ "luck",
222
+ "national",
223
+ "progress",
224
+ "hall",
225
+ "stroke",
226
+ "theory",
227
+ "offer",
228
+ "story",
229
+ "tax",
230
+ "definition",
231
+ "history",
232
+ "ride",
233
+ "medium",
234
+ "opening",
235
+ "glass",
236
+ "elevator",
237
+ "stomach",
238
+ "question",
239
+ "ability",
240
+ "leading",
241
+ "village",
242
+ "computer",
243
+ "city",
244
+ "grand",
245
+ "confidence",
246
+ "candle",
247
+ "priest",
248
+ "recommendation",
249
+ "point",
250
+ "necessary",
251
+ "body",
252
+ "desk",
253
+ "secret",
254
+ "horror",
255
+ "noise",
256
+ "culture",
257
+ "warning",
258
+ "water",
259
+ "round",
260
+ "diet",
261
+ "flower",
262
+ "bus",
263
+ "tough",
264
+ "permission",
265
+ "week",
266
+ "prompt",
267
+ "connection",
268
+ "abuse",
269
+ "height",
270
+ "save",
271
+ "corner",
272
+ "border",
273
+ "stress",
274
+ "drive",
275
+ "stop",
276
+ "rip",
277
+ "meal",
278
+ "listen",
279
+ "confusion",
280
+ "girlfriend",
281
+ "living",
282
+ "relation",
283
+ "significance",
284
+ "plan",
285
+ "creative",
286
+ "atmosphere",
287
+ "blame",
288
+ "invite",
289
+ "housing",
290
+ "paper",
291
+ "drink",
292
+ "roll",
293
+ "silver",
294
+ "drunk",
295
+ "age",
296
+ "damage",
297
+ "smoke",
298
+ "environment",
299
+ "pack",
300
+ "savings",
301
+ "influence",
302
+ "tourist",
303
+ "rain",
304
+ "post",
305
+ "sign",
306
+ "grandmother",
307
+ "run",
308
+ "profit",
309
+ "push",
310
+ "clerk",
311
+ "final",
312
+ "wine",
313
+ "swim",
314
+ "pause",
315
+ "stuff",
316
+ "singer",
317
+ "funeral",
318
+ "average",
319
+ "source",
320
+ "scene",
321
+ "tradition",
322
+ "personal",
323
+ "snow",
324
+ "nobody",
325
+ "distance",
326
+ "sort",
327
+ "sensitive",
328
+ "animal",
329
+ "major",
330
+ "negotiation",
331
+ "click",
332
+ "mood",
333
+ "period",
334
+ "arrival",
335
+ "expression",
336
+ "holiday",
337
+ "repeat",
338
+ "dust",
339
+ "closet",
340
+ "gold",
341
+ "bad",
342
+ "sail",
343
+ "combination",
344
+ "clothes",
345
+ "emphasis",
346
+ "duty",
347
+ "black",
348
+ "step",
349
+ "school",
350
+ "jump",
351
+ "document",
352
+ "professional",
353
+ "lip",
354
+ "chemical",
355
+ "front",
356
+ "wake",
357
+ "while",
358
+ "inside",
359
+ "watch",
360
+ "row",
361
+ "subject",
362
+ "penalty",
363
+ "balance",
364
+ "possible",
365
+ "adult",
366
+ "aside",
367
+ "sample",
368
+ "appeal",
369
+ "wedding",
370
+ "depth",
371
+ "king",
372
+ "award",
373
+ "wife",
374
+ "blow",
375
+ "site",
376
+ "camp",
377
+ "music",
378
+ "safe",
379
+ "gift",
380
+ "fault",
381
+ "guess",
382
+ "act",
383
+ "shame",
384
+ "drama",
385
+ "capital",
386
+ "exam",
387
+ "stupid",
388
+ "record",
389
+ "sound",
390
+ "swing",
391
+ "novel",
392
+ "minimum",
393
+ "ratio",
394
+ "machine",
395
+ "shape",
396
+ "lead",
397
+ "operation",
398
+ "salary",
399
+ "cloud",
400
+ "affair",
401
+ "hit",
402
+ "chapter",
403
+ "stage",
404
+ "quantity",
405
+ "access",
406
+ "army",
407
+ "chain",
408
+ "traffic",
409
+ "kick",
410
+ "analysis",
411
+ "airport",
412
+ "time",
413
+ "vacation",
414
+ "philosophy",
415
+ "ball",
416
+ "chest",
417
+ "thanks",
418
+ "place",
419
+ "mountain",
420
+ "advertising",
421
+ "red",
422
+ "past",
423
+ "rent",
424
+ "return",
425
+ "tour",
426
+ "house",
427
+ "construction",
428
+ "net",
429
+ "native",
430
+ "war",
431
+ "figure",
432
+ "fee",
433
+ "spray",
434
+ "user",
435
+ "dirt",
436
+ "shot",
437
+ "task",
438
+ "stick",
439
+ "friend",
440
+ "software",
441
+ "promotion",
442
+ "interaction",
443
+ "surround",
444
+ "block",
445
+ "purpose",
446
+ "practice",
447
+ "conflict",
448
+ "routine",
449
+ "requirement",
450
+ "bonus",
451
+ "hole",
452
+ "state",
453
+ "junior",
454
+ "sweet",
455
+ "catch",
456
+ "tear",
457
+ "fold",
458
+ "wall",
459
+ "editor",
460
+ "life",
461
+ "position",
462
+ "pound",
463
+ "respect",
464
+ "bathroom",
465
+ "coat",
466
+ "script",
467
+ "job",
468
+ "teach",
469
+ "birth",
470
+ "view",
471
+ "resolve",
472
+ "theme",
473
+ "employee",
474
+ "doubt",
475
+ "market",
476
+ "education",
477
+ "serve",
478
+ "recover",
479
+ "tone",
480
+ "harm",
481
+ "miss",
482
+ "union",
483
+ "understanding",
484
+ "cow",
485
+ "river",
486
+ "association",
487
+ "concept",
488
+ "training",
489
+ "recipe",
490
+ "relationship",
491
+ "reserve",
492
+ "depression",
493
+ "proof",
494
+ "hair",
495
+ "revenue",
496
+ "independent",
497
+ "lift",
498
+ "assignment",
499
+ "temporary",
500
+ "amount",
501
+ "loss",
502
+ "edge",
503
+ "track",
504
+ "check",
505
+ "rope",
506
+ "estimate",
507
+ "pollution",
508
+ "stable",
509
+ "message",
510
+ "delivery",
511
+ "perspective",
512
+ "mirror",
513
+ "assistant",
514
+ "representative",
515
+ "witness",
516
+ "nature",
517
+ "judge",
518
+ "fruit",
519
+ "tip",
520
+ "devil",
521
+ "town",
522
+ "emergency",
523
+ "upper",
524
+ "drop",
525
+ "stay",
526
+ "human",
527
+ "neck",
528
+ "speaker",
529
+ "network",
530
+ "sing",
531
+ "resist",
532
+ "league",
533
+ "trip",
534
+ "signature",
535
+ "lawyer",
536
+ "importance",
537
+ "gas",
538
+ "choice",
539
+ "engineer",
540
+ "success",
541
+ "part",
542
+ "external",
543
+ "worker",
544
+ "simple",
545
+ "quarter",
546
+ "student",
547
+ "heart",
548
+ "pass",
549
+ "spite",
550
+ "shift",
551
+ "rough",
552
+ "lady",
553
+ "grass",
554
+ "community",
555
+ "garage",
556
+ "youth",
557
+ "standard",
558
+ "skirt",
559
+ "promise",
560
+ "blind",
561
+ "television",
562
+ "disease",
563
+ "commission",
564
+ "positive",
565
+ "energy",
566
+ "calm",
567
+ "presence",
568
+ "tune",
569
+ "basis",
570
+ "preference",
571
+ "head",
572
+ "common",
573
+ "cut",
574
+ "somewhere",
575
+ "presentation",
576
+ "current",
577
+ "thought",
578
+ "revolution",
579
+ "effort",
580
+ "master",
581
+ "implement",
582
+ "republic",
583
+ "floor",
584
+ "principle",
585
+ "stranger",
586
+ "shoulder",
587
+ "grade",
588
+ "button",
589
+ "tennis",
590
+ "police",
591
+ "collection",
592
+ "account",
593
+ "register",
594
+ "glove",
595
+ "divide",
596
+ "professor",
597
+ "chair",
598
+ "priority",
599
+ "combine",
600
+ "peace",
601
+ "extension",
602
+ "maybe",
603
+ "evening",
604
+ "frame",
605
+ "sister",
606
+ "wave",
607
+ "code",
608
+ "application",
609
+ "mouse",
610
+ "match",
611
+ "counter",
612
+ "bottle",
613
+ "half",
614
+ "cheek",
615
+ "resolution",
616
+ "back",
617
+ "knowledge",
618
+ "make",
619
+ "discussion",
620
+ "screw",
621
+ "length",
622
+ "accident",
623
+ "battle",
624
+ "dress",
625
+ "knee",
626
+ "log",
627
+ "package",
628
+ "it",
629
+ "turn",
630
+ "hearing",
631
+ "newspaper",
632
+ "layer",
633
+ "wealth",
634
+ "profile",
635
+ "imagination",
636
+ "answer",
637
+ "weekend",
638
+ "teacher",
639
+ "appearance",
640
+ "meet",
641
+ "bike",
642
+ "rise",
643
+ "belt",
644
+ "crash",
645
+ "bowl",
646
+ "equivalent",
647
+ "support",
648
+ "image",
649
+ "poem",
650
+ "risk",
651
+ "excitement",
652
+ "remote",
653
+ "secretary",
654
+ "public",
655
+ "produce",
656
+ "plane",
657
+ "display",
658
+ "money",
659
+ "sand",
660
+ "situation",
661
+ "punch",
662
+ "customer",
663
+ "title",
664
+ "shake",
665
+ "mortgage",
666
+ "option",
667
+ "number",
668
+ "pop",
669
+ "window",
670
+ "extent",
671
+ "nothing",
672
+ "experience",
673
+ "opinion",
674
+ "departure",
675
+ "dance",
676
+ "indication",
677
+ "boy",
678
+ "material",
679
+ "band",
680
+ "leader",
681
+ "sun",
682
+ "beautiful",
683
+ "muscle",
684
+ "farmer",
685
+ "variety",
686
+ "fat",
687
+ "handle",
688
+ "director",
689
+ "opportunity",
690
+ "calendar",
691
+ "outside",
692
+ "pace",
693
+ "bath",
694
+ "fish",
695
+ "consequence",
696
+ "put",
697
+ "owner",
698
+ "go",
699
+ "doctor",
700
+ "information",
701
+ "share",
702
+ "hurt",
703
+ "protection",
704
+ "career",
705
+ "finance",
706
+ "force",
707
+ "golf",
708
+ "garbage",
709
+ "aspect",
710
+ "kid",
711
+ "food",
712
+ "boot",
713
+ "milk",
714
+ "respond",
715
+ "objective",
716
+ "reality",
717
+ "raw",
718
+ "ring",
719
+ "mall",
720
+ "one",
721
+ "impact",
722
+ "area",
723
+ "news",
724
+ "international",
725
+ "series",
726
+ "impress",
727
+ "mother",
728
+ "shelter",
729
+ "strike",
730
+ "loan",
731
+ "month",
732
+ "seat",
733
+ "anything",
734
+ "entertainment",
735
+ "familiar",
736
+ "clue",
737
+ "year",
738
+ "glad",
739
+ "supermarket",
740
+ "natural",
741
+ "god",
742
+ "cost",
743
+ "conversation",
744
+ "tie",
745
+ "ruin",
746
+ "comfort",
747
+ "earth",
748
+ "storm",
749
+ "percentage",
750
+ "assistance",
751
+ "budget",
752
+ "strength",
753
+ "beginning",
754
+ "sleep",
755
+ "other",
756
+ "young",
757
+ "unit",
758
+ "fill",
759
+ "store",
760
+ "desire",
761
+ "hide",
762
+ "value",
763
+ "cup",
764
+ "maintenance",
765
+ "nurse",
766
+ "function",
767
+ "tower",
768
+ "role",
769
+ "class",
770
+ "camera",
771
+ "database",
772
+ "panic",
773
+ "nation",
774
+ "basket",
775
+ "ice",
776
+ "art",
777
+ "spirit",
778
+ "chart",
779
+ "exchange",
780
+ "feedback",
781
+ "statement",
782
+ "reputation",
783
+ "search",
784
+ "hunt",
785
+ "exercise",
786
+ "nasty",
787
+ "notice",
788
+ "male",
789
+ "yard",
790
+ "annual",
791
+ "collar",
792
+ "date",
793
+ "platform",
794
+ "plant",
795
+ "fortune",
796
+ "passion",
797
+ "friendship",
798
+ "spread",
799
+ "cancer",
800
+ "ticket",
801
+ "attitude",
802
+ "island",
803
+ "active",
804
+ "object",
805
+ "service",
806
+ "buyer",
807
+ "bite",
808
+ "card",
809
+ "face",
810
+ "steak",
811
+ "proposal",
812
+ "patient",
813
+ "heat",
814
+ "rule",
815
+ "resident",
816
+ "broad",
817
+ "politics",
818
+ "west",
819
+ "knife",
820
+ "expert",
821
+ "girl",
822
+ "design",
823
+ "salt",
824
+ "baseball",
825
+ "grab",
826
+ "inspection",
827
+ "cousin",
828
+ "couple",
829
+ "magazine",
830
+ "cook",
831
+ "dependent",
832
+ "security",
833
+ "chicken",
834
+ "version",
835
+ "currency",
836
+ "ladder",
837
+ "scheme",
838
+ "kitchen",
839
+ "employment",
840
+ "local",
841
+ "attention",
842
+ "manager",
843
+ "fact",
844
+ "cover",
845
+ "sad",
846
+ "guard",
847
+ "relative",
848
+ "county",
849
+ "rate",
850
+ "lunch",
851
+ "program",
852
+ "initiative",
853
+ "gear",
854
+ "bridge",
855
+ "breast",
856
+ "talk",
857
+ "dish",
858
+ "guarantee",
859
+ "beer",
860
+ "vehicle",
861
+ "reception",
862
+ "woman",
863
+ "substance",
864
+ "copy",
865
+ "lecture",
866
+ "advantage",
867
+ "park",
868
+ "cold",
869
+ "death",
870
+ "mix",
871
+ "hold",
872
+ "scale",
873
+ "tomorrow",
874
+ "blood",
875
+ "request",
876
+ "green",
877
+ "cookie",
878
+ "church",
879
+ "strip",
880
+ "forever",
881
+ "beyond",
882
+ "debt",
883
+ "tackle",
884
+ "wash",
885
+ "following",
886
+ "feel",
887
+ "maximum",
888
+ "sector",
889
+ "sea",
890
+ "property",
891
+ "economics",
892
+ "menu",
893
+ "bench",
894
+ "try",
895
+ "language",
896
+ "start",
897
+ "call",
898
+ "solid",
899
+ "address",
900
+ "income",
901
+ "foot",
902
+ "senior",
903
+ "honey",
904
+ "few",
905
+ "mixture",
906
+ "cash",
907
+ "grocery",
908
+ "link",
909
+ "map",
910
+ "form",
911
+ "factor",
912
+ "pot",
913
+ "model",
914
+ "writer",
915
+ "farm",
916
+ "winter",
917
+ "skill",
918
+ "anywhere",
919
+ "birthday",
920
+ "policy",
921
+ "release",
922
+ "husband",
923
+ "lab",
924
+ "hurry",
925
+ "mail",
926
+ "equipment",
927
+ "sink",
928
+ "pair",
929
+ "driver",
930
+ "consideration",
931
+ "leather",
932
+ "skin",
933
+ "blue",
934
+ "boat",
935
+ "sale",
936
+ "brick",
937
+ "two",
938
+ "feed",
939
+ "square",
940
+ "dot",
941
+ "rush",
942
+ "dream",
943
+ "location",
944
+ "afternoon",
945
+ "manufacturer",
946
+ "control",
947
+ "occasion",
948
+ "trouble",
949
+ "introduction",
950
+ "advice",
951
+ "bet",
952
+ "eat",
953
+ "kill",
954
+ "category",
955
+ "manner",
956
+ "office",
957
+ "estate",
958
+ "pride",
959
+ "awareness",
960
+ "slip",
961
+ "crack",
962
+ "client",
963
+ "nail",
964
+ "shoot",
965
+ "membership",
966
+ "soft",
967
+ "anybody",
968
+ "web",
969
+ "official",
970
+ "individual",
971
+ "pizza",
972
+ "interest",
973
+ "bag",
974
+ "spell",
975
+ "profession",
976
+ "queen",
977
+ "deal",
978
+ "resource",
979
+ "ship",
980
+ "guy",
981
+ "chocolate",
982
+ "joint",
983
+ "formal",
984
+ "upstairs",
985
+ "car",
986
+ "resort",
987
+ "abroad",
988
+ "dealer",
989
+ "associate",
990
+ "finger",
991
+ "surgery",
992
+ "comment",
993
+ "team",
994
+ "detail",
995
+ "crazy",
996
+ "path",
997
+ "tale",
998
+ "initial",
999
+ "arm",
1000
+ "radio",
1001
+ "demand",
1002
+ "single",
1003
+ "draw",
1004
+ "yellow",
1005
+ "contest",
1006
+ "piece",
1007
+ "quote",
1008
+ "pull",
1009
+ "commercial",
1010
+ "shirt",
1011
+ "contribution",
1012
+ "cream",
1013
+ "channel",
1014
+ "suit",
1015
+ "discipline",
1016
+ "instruction",
1017
+ "concert",
1018
+ "speech",
1019
+ "low",
1020
+ "effective",
1021
+ "hang",
1022
+ "scratch",
1023
+ "industry",
1024
+ "breakfast",
1025
+ "lay",
1026
+ "join",
1027
+ "metal",
1028
+ "bedroom",
1029
+ "minute",
1030
+ "product",
1031
+ "rest",
1032
+ "temperature",
1033
+ "many",
1034
+ "give",
1035
+ "argument",
1036
+ "print",
1037
+ "purple",
1038
+ "laugh",
1039
+ "health",
1040
+ "credit",
1041
+ "investment",
1042
+ "sell",
1043
+ "setting",
1044
+ "lesson",
1045
+ "egg",
1046
+ "middle",
1047
+ "marriage",
1048
+ "level",
1049
+ "evidence",
1050
+ "phrase",
1051
+ "love",
1052
+ "self",
1053
+ "benefit",
1054
+ "guidance",
1055
+ "affect",
1056
+ "you",
1057
+ "dad",
1058
+ "anxiety",
1059
+ "special",
1060
+ "boyfriend",
1061
+ "test",
1062
+ "blank",
1063
+ "payment",
1064
+ "soup",
1065
+ "obligation",
1066
+ "reply",
1067
+ "smile",
1068
+ "deep",
1069
+ "complaint",
1070
+ "addition",
1071
+ "review",
1072
+ "box",
1073
+ "towel",
1074
+ "minor",
1075
+ "fun",
1076
+ "soil",
1077
+ "issue",
1078
+ "cigarette",
1079
+ "internet",
1080
+ "gain",
1081
+ "tell",
1082
+ "entry",
1083
+ "spare",
1084
+ "incident",
1085
+ "family",
1086
+ "refuse",
1087
+ "branch",
1088
+ "can",
1089
+ "pen",
1090
+ "grandfather",
1091
+ "constant",
1092
+ "tank",
1093
+ "uncle",
1094
+ "climate",
1095
+ "ground",
1096
+ "volume",
1097
+ "communication",
1098
+ "kind",
1099
+ "poet",
1100
+ "child",
1101
+ "screen",
1102
+ "mine",
1103
+ "quit",
1104
+ "gene",
1105
+ "lack",
1106
+ "charity",
1107
+ "memory",
1108
+ "tooth",
1109
+ "fear",
1110
+ "mention",
1111
+ "marketing",
1112
+ "reveal",
1113
+ "reason",
1114
+ "court",
1115
+ "season",
1116
+ "freedom",
1117
+ "land",
1118
+ "sport",
1119
+ "audience",
1120
+ "classroom",
1121
+ "law",
1122
+ "hook",
1123
+ "win",
1124
+ "carry",
1125
+ "eye",
1126
+ "smell",
1127
+ "distribution",
1128
+ "research",
1129
+ "country",
1130
+ "dare",
1131
+ "hope",
1132
+ "whereas",
1133
+ "stretch",
1134
+ "library",
1135
+ "if",
1136
+ "delay",
1137
+ "college",
1138
+ "plastic",
1139
+ "book",
1140
+ "present",
1141
+ "use",
1142
+ "worry",
1143
+ "champion",
1144
+ "goal",
1145
+ "economy",
1146
+ "march",
1147
+ "election",
1148
+ "reflection",
1149
+ "midnight",
1150
+ "slide",
1151
+ "inflation",
1152
+ "action",
1153
+ "challenge",
1154
+ "guitar",
1155
+ "coast",
1156
+ "apple",
1157
+ "campaign",
1158
+ "field",
1159
+ "jacket",
1160
+ "sense",
1161
+ "way",
1162
+ "visual",
1163
+ "remove",
1164
+ "weather",
1165
+ "trash",
1166
+ "cable",
1167
+ "regret",
1168
+ "buddy",
1169
+ "beach",
1170
+ "historian",
1171
+ "courage",
1172
+ "sympathy",
1173
+ "truck",
1174
+ "tension",
1175
+ "permit",
1176
+ "nose",
1177
+ "bed",
1178
+ "son",
1179
+ "person",
1180
+ "base",
1181
+ "meat",
1182
+ "usual",
1183
+ "air",
1184
+ "meeting",
1185
+ "worth",
1186
+ "game",
1187
+ "independence",
1188
+ "physical",
1189
+ "brief",
1190
+ "play",
1191
+ "raise",
1192
+ "board",
1193
+ "she",
1194
+ "key",
1195
+ "writing",
1196
+ "pick",
1197
+ "command",
1198
+ "party",
1199
+ "yesterday",
1200
+ "spring",
1201
+ "candidate",
1202
+ "physics",
1203
+ "university",
1204
+ "concern",
1205
+ "development",
1206
+ "change",
1207
+ "string",
1208
+ "target",
1209
+ "instance",
1210
+ "room",
1211
+ "bitter",
1212
+ "bird",
1213
+ "football",
1214
+ "normal",
1215
+ "split",
1216
+ "impression",
1217
+ "wood",
1218
+ "long",
1219
+ "meaning",
1220
+ "stock",
1221
+ "cap",
1222
+ "leadership",
1223
+ "media",
1224
+ "ambition",
1225
+ "fishing",
1226
+ "essay",
1227
+ "salad",
1228
+ "repair",
1229
+ "today",
1230
+ "designer",
1231
+ "night",
1232
+ "bank",
1233
+ "drawing",
1234
+ "inevitable",
1235
+ "phase",
1236
+ "vast",
1237
+ "chip",
1238
+ "anger",
1239
+ "switch",
1240
+ "cry",
1241
+ "twist",
1242
+ "personality",
1243
+ "attempt",
1244
+ "storage",
1245
+ "being",
1246
+ "preparation",
1247
+ "bat",
1248
+ "selection",
1249
+ "white",
1250
+ "technology",
1251
+ "contract",
1252
+ "side",
1253
+ "section",
1254
+ "station",
1255
+ "till",
1256
+ "structure",
1257
+ "tongue",
1258
+ "taste",
1259
+ "truth",
1260
+ "difficulty",
1261
+ "group",
1262
+ "limit",
1263
+ "main",
1264
+ "move",
1265
+ "feeling",
1266
+ "light",
1267
+ "example",
1268
+ "mission",
1269
+ "might",
1270
+ "wait",
1271
+ "wheel",
1272
+ "shop",
1273
+ "host",
1274
+ "classic",
1275
+ "alternative",
1276
+ "cause",
1277
+ "agent",
1278
+ "consist",
1279
+ "table",
1280
+ "airline",
1281
+ "text",
1282
+ "pool",
1283
+ "craft",
1284
+ "range",
1285
+ "fuel",
1286
+ "tool",
1287
+ "partner",
1288
+ "load",
1289
+ "entrance",
1290
+ "deposit",
1291
+ "hate",
1292
+ "article",
1293
+ "video",
1294
+ "summer",
1295
+ "feature",
1296
+ "extreme",
1297
+ "mobile",
1298
+ "hospital",
1299
+ "flight",
1300
+ "fall",
1301
+ "pension",
1302
+ "piano",
1303
+ "fail",
1304
+ "result",
1305
+ "rub",
1306
+ "gap",
1307
+ "system",
1308
+ "report",
1309
+ "suck",
1310
+ "ordinary",
1311
+ "wind",
1312
+ "nerve",
1313
+ "ask",
1314
+ "shine",
1315
+ "note",
1316
+ "line",
1317
+ "mom",
1318
+ "perception",
1319
+ "brother",
1320
+ "reference",
1321
+ "bend",
1322
+ "charge",
1323
+ "treat",
1324
+ "trick",
1325
+ "term",
1326
+ "homework",
1327
+ "bake",
1328
+ "bid",
1329
+ "status",
1330
+ "project",
1331
+ "strategy",
1332
+ "orange",
1333
+ "let",
1334
+ "enthusiasm",
1335
+ "parent",
1336
+ "concentrate",
1337
+ "device",
1338
+ "travel",
1339
+ "poetry",
1340
+ "business",
1341
+ "society",
1342
+ "kiss",
1343
+ "end",
1344
+ "vegetable",
1345
+ "employ",
1346
+ "schedule",
1347
+ "hour",
1348
+ "brave",
1349
+ "focus",
1350
+ "process",
1351
+ "movie",
1352
+ "illegal",
1353
+ "general",
1354
+ "coffee",
1355
+ "ad",
1356
+ "highway",
1357
+ "chemistry",
1358
+ "psychology",
1359
+ "hire",
1360
+ "bell",
1361
+ "conference",
1362
+ "relief",
1363
+ "show",
1364
+ "neat",
1365
+ "funny",
1366
+ "weight",
1367
+ "quality",
1368
+ "club",
1369
+ "daughter",
1370
+ "zone",
1371
+ "touch",
1372
+ "tonight",
1373
+ "shock",
1374
+ "burn",
1375
+ "excuse",
1376
+ "name",
1377
+ "survey",
1378
+ "landscape",
1379
+ "advance",
1380
+ "satisfaction",
1381
+ "bread",
1382
+ "disaster",
1383
+ "item",
1384
+ "hat",
1385
+ "prior",
1386
+ "shopping",
1387
+ "visit",
1388
+ "east",
1389
+ "photo",
1390
+ "home",
1391
+ "idea",
1392
+ "father",
1393
+ "comparison",
1394
+ "cat",
1395
+ "pipe",
1396
+ "winner",
1397
+ "count",
1398
+ "lake",
1399
+ "fight",
1400
+ "prize",
1401
+ "foundation",
1402
+ "dog",
1403
+ "keep",
1404
+ "ideal",
1405
+ "fan",
1406
+ "struggle",
1407
+ "peak",
1408
+ "safety",
1409
+ "solution",
1410
+ "hell",
1411
+ "conclusion",
1412
+ "population",
1413
+ "strain",
1414
+ "alarm",
1415
+ "measurement",
1416
+ "second",
1417
+ "train",
1418
+ "race",
1419
+ "due",
1420
+ "insurance",
1421
+ "boss",
1422
+ "tree",
1423
+ "monitor",
1424
+ "sick",
1425
+ "course",
1426
+ "drag",
1427
+ "appointment",
1428
+ "slice",
1429
+ "still",
1430
+ "care",
1431
+ "patience",
1432
+ "rich",
1433
+ "escape",
1434
+ "emotion",
1435
+ "royal",
1436
+ "female",
1437
+ "childhood",
1438
+ "government",
1439
+ "picture",
1440
+ "will",
1441
+ "sock",
1442
+ "big",
1443
+ "gate",
1444
+ "oil",
1445
+ "cross",
1446
+ "pin",
1447
+ "improvement",
1448
+ "championship",
1449
+ "silly",
1450
+ "help",
1451
+ "sky",
1452
+ "pitch",
1453
+ "man",
1454
+ "diamond",
1455
+ "most",
1456
+ "transition",
1457
+ "work",
1458
+ "science",
1459
+ "committee",
1460
+ "moment",
1461
+ "fix",
1462
+ "teaching",
1463
+ "dig",
1464
+ "specialist",
1465
+ "complex",
1466
+ "guide",
1467
+ "people",
1468
+ "dead",
1469
+ "voice",
1470
+ "original",
1471
+ "break",
1472
+ "topic",
1473
+ "data",
1474
+ "degree",
1475
+ "reading",
1476
+ "recording",
1477
+ "bunch",
1478
+ "reach",
1479
+ "judgment",
1480
+ "lie",
1481
+ "regular",
1482
+ "set",
1483
+ "painting",
1484
+ "mode",
1485
+ "list",
1486
+ "player",
1487
+ "bear",
1488
+ "north",
1489
+ "wonder",
1490
+ "carpet",
1491
+ "heavy",
1492
+ "officer",
1493
+ "negative",
1494
+ "clock",
1495
+ "unique",
1496
+ "baby",
1497
+ "pain",
1498
+ "assumption",
1499
+ "disk",
1500
+ "iron",
1501
+ "bill",
1502
+ "drawer",
1503
+ "look",
1504
+ "double",
1505
+ "mistake",
1506
+ "finish",
1507
+ "future",
1508
+ "brilliant",
1509
+ "contact",
1510
+ "math",
1511
+ "rice",
1512
+ "leave",
1513
+ "restaurant",
1514
+ "discount",
1515
+ "sex",
1516
+ "virus",
1517
+ "bit",
1518
+ "trust",
1519
+ "event",
1520
+ "wear",
1521
+ "juice",
1522
+ "failure",
1523
+ "bug",
1524
+ "context",
1525
+ "mud",
1526
+ "whole",
1527
+ "wrap",
1528
+ "intention",
1529
+ "draft",
1530
+ "pressure",
1531
+ "cake",
1532
+ "dark",
1533
+ "explanation",
1534
+ "space",
1535
+ "angle",
1536
+ "word",
1537
+ "efficiency",
1538
+ "management",
1539
+ "habit",
1540
+ "star",
1541
+ "chance",
1542
+ "finding",
1543
+ "transportation",
1544
+ "stand",
1545
+ "criticism",
1546
+ "flow",
1547
+ "door",
1548
+ "injury",
1549
+ "insect",
1550
+ "surprise",
1551
+ "apartment",
1552
+ ] # pylint: disable=line-too-long
1553
+
1554
+ # ISO 639-1 codes to language names.
1555
+ LANGUAGE_CODES = MappingProxyType(
1556
+ {
1557
+ "en": "English",
1558
+ "es": "Spanish",
1559
+ "pt": "Portuguese",
1560
+ "ar": "Arabic",
1561
+ "hi": "Hindi",
1562
+ "fr": "French",
1563
+ "ru": "Russian",
1564
+ "de": "German",
1565
+ "ja": "Japanese",
1566
+ "it": "Italian",
1567
+ "bn": "Bengali",
1568
+ "uk": "Ukrainian",
1569
+ "th": "Thai",
1570
+ "ur": "Urdu",
1571
+ "ta": "Tamil",
1572
+ "te": "Telugu",
1573
+ "bg": "Bulgarian",
1574
+ "ko": "Korean",
1575
+ "pl": "Polish",
1576
+ "he": "Hebrew",
1577
+ "fa": "Persian",
1578
+ "vi": "Vietnamese",
1579
+ "ne": "Nepali",
1580
+ "sw": "Swahili",
1581
+ "kn": "Kannada",
1582
+ "mr": "Marathi",
1583
+ "gu": "Gujarati",
1584
+ "pa": "Punjabi",
1585
+ "ml": "Malayalam",
1586
+ "fi": "Finnish",
1587
+ }
1588
+ )
1589
+
1590
+ # Chinese characters
1591
+ _CHINESE_CHARS_PATTERN = r"[\u4E00-\u9FFF\u3400-\u4DBF]"
1592
+ # Japanese Hiragana & Katakana
1593
+ _JAPANESE_CHARS_PATTERN = r"[\u3040-\u309f\u30a0-\u30ff]"
1594
+ # Korean (Hangul Syllables)
1595
+ _KOREAN_CHARS_PATTERN = r"[\uAC00-\uD7AF]"
1596
+ _ALPHABETS = "([A-Za-z])"
1597
+ _PREFIXES = "(Mr|St|Mrs|Ms|Dr)[.]"
1598
+ _SUFFIXES = "(Inc|Ltd|Jr|Sr|Co)"
1599
+ _STARTERS = (
1600
+ r"(Mr|Mrs|Ms|Dr|Prof|Capt|Cpt|Lt|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
1601
+ )
1602
+ _ACRONYMS = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
1603
+ _WEBSITES = "[.](com|net|org|io|gov|edu|me)"
1604
+ _DIGITS = "([0-9])"
1605
+ _MULTIPLE_DOTS = r"\.{2,}"
1606
+
1607
+
1608
+ # Util functions
1609
+ def split_into_sentences(text):
1610
+ """Split the text into sentences.
1611
+
1612
+ Args:
1613
+ text: A string that consists of more than or equal to one sentences.
1614
+
1615
+ Returns:
1616
+ A list of strings where each string is a sentence.
1617
+ """
1618
+ text = " " + text + " "
1619
+ text = text.replace("\n", " ")
1620
+ text = re.sub(_PREFIXES, "\\1<prd>", text)
1621
+ text = re.sub(_WEBSITES, "<prd>\\1", text)
1622
+ text = re.sub(_DIGITS + "[.]" + _DIGITS, "\\1<prd>\\2", text)
1623
+ text = re.sub(
1624
+ _MULTIPLE_DOTS,
1625
+ lambda match: "<prd>" * len(match.group(0)) + "<stop>",
1626
+ text,
1627
+ )
1628
+ if "Ph.D" in text:
1629
+ text = text.replace("Ph.D.", "Ph<prd>D<prd>")
1630
+ text = re.sub(r"\s" + _ALPHABETS + "[.] ", " \\1<prd> ", text)
1631
+ text = re.sub(_ACRONYMS + " " + _STARTERS, "\\1<stop> \\2", text)
1632
+ text = re.sub(
1633
+ _ALPHABETS + "[.]" + _ALPHABETS + "[.]" + _ALPHABETS + "[.]",
1634
+ "\\1<prd>\\2<prd>\\3<prd>",
1635
+ text,
1636
+ )
1637
+ text = re.sub(_ALPHABETS + "[.]" + _ALPHABETS + "[.]", "\\1<prd>\\2<prd>", text)
1638
+ text = re.sub(" " + _SUFFIXES + "[.] " + _STARTERS, " \\1<stop> \\2", text)
1639
+ text = re.sub(" " + _SUFFIXES + "[.]", " \\1<prd>", text)
1640
+ text = re.sub(" " + _ALPHABETS + "[.]", " \\1<prd>", text)
1641
+ if "”" in text:
1642
+ text = text.replace(".”", "”.")
1643
+ if '"' in text:
1644
+ text = text.replace('."', '".')
1645
+ if "!" in text:
1646
+ text = text.replace('!"', '"!')
1647
+ if "?" in text:
1648
+ text = text.replace('?"', '"?')
1649
+ text = text.replace(".", ".<stop>")
1650
+ text = text.replace("?", "?<stop>")
1651
+ text = text.replace("!", "!<stop>")
1652
+ text = text.replace("<prd>", ".")
1653
+ sentences = text.split("<stop>")
1654
+ sentences = [s.strip() for s in sentences]
1655
+ if sentences and not sentences[-1]:
1656
+ sentences = sentences[:-1]
1657
+ return sentences
1658
+
1659
+
1660
+ def count_words(text):
1661
+ """Counts the number of words."""
1662
+ tokenizer = nltk.tokenize.RegexpTokenizer(r"\w+")
1663
+ tokens = tokenizer.tokenize(text)
1664
+ num_words = len(tokens)
1665
+ return num_words
1666
+
1667
+
1668
+ def split_chinese_japanese_hindi(lines: str) -> Iterable[str]:
1669
+ """
1670
+ Split Chinese and Japanese text into sentences.
1671
+ From https://stackoverflow.com/questions/27441191/splitting-chinese-document-into-sentences
1672
+ Special question/exclamation marks were added upon inspection of our raw data,
1673
+ Also supports multiple lines.
1674
+ The separator for hindi is '।'
1675
+ """
1676
+ for line in lines.splitlines():
1677
+ yield from re.findall(
1678
+ r"[^!?。\.\!\?\!\?\.\n।]+[!?。\.\!\?\!\?\.\n।]?",
1679
+ line.strip(),
1680
+ flags=re.U,
1681
+ )
1682
+
1683
+
1684
+ def count_words_cjk(text: str) -> int:
1685
+ """Counts the number of words for Chinese and Japanese and Korean.
1686
+ Can be extended to additional languages.
1687
+ Source: https://stackoverflow.com/questions/49164507/how-to-count-the-number-of-chinese-korean-and-english-words withadditional modifications
1688
+ Example:
1689
+ >In: count_words_cjk('こんにちは、ジェイソンさん、Jason? Nice to meet you☺ ❤')
1690
+ >Out: 19
1691
+ """
1692
+ # Non alpha numeric patterns in latin and asian languages.
1693
+ non_alphanumeric_patterns = (
1694
+ r"[\\.\!\?\.\/_,\{\}<>:;$%^&*(+\"\'+——!,。?、`~@#¥……():;《)《》“”()\[\]«»〔〕\-「」]+"
1695
+ )
1696
+ text = re.sub(non_alphanumeric_patterns, "", text)
1697
+
1698
+ emoji_cnt = emoji.emoji_count(text) # count emojis
1699
+ text = emoji.replace_emoji(text, "") # remove emojis
1700
+
1701
+ foreign_chars_patterns = "|".join([_CHINESE_CHARS_PATTERN, _JAPANESE_CHARS_PATTERN, _KOREAN_CHARS_PATTERN])
1702
+ asian_chars = re.findall(foreign_chars_patterns, text)
1703
+ asian_chars_cnt = len(asian_chars)
1704
+ non_asian_chars = re.sub(foreign_chars_patterns, " ", text)
1705
+ non_asian_words_cnt = len(non_asian_chars.split())
1706
+
1707
+ return non_asian_words_cnt + asian_chars_cnt + emoji_cnt
1708
+
1709
+
1710
+ @functools.cache
1711
+ def _get_sentence_tokenizer():
1712
+ return nltk.data.load("nltk:tokenizers/punkt/english.pickle")
1713
+
1714
+
1715
+ def count_sentences(text):
1716
+ """Count the number of sentences."""
1717
+ tokenizer = _get_sentence_tokenizer()
1718
+ tokenized_sentences = tokenizer.tokenize(text)
1719
+ return len(tokenized_sentences)
1720
+
1721
+
1722
+ def get_langid(text: str, lid_path: str | None = None) -> str:
1723
+ line_langs: list[str] = []
1724
+ lines = [line.strip() for line in text.split("\n") if len(line.strip()) >= 4]
1725
+
1726
+ for line in lines:
1727
+ try:
1728
+ line_langs.append(langdetect.detect(line))
1729
+ except langdetect.LangDetectException as e:
1730
+ logger.info("Unable to detect language for text %s due to %s", line, e) # refex: disable=pytotw.037
1731
+
1732
+ if len(line_langs) == 0:
1733
+ return "en"
1734
+ # select the text language to be the most commonly predicted language of the lines.
1735
+ return collections.Counter(line_langs).most_common(1)[0][0]
1736
+
1737
+
1738
+ def generate_keywords(num_keywords):
1739
+ """Randomly generates a few keywords."""
1740
+ return random.sample(WORD_LIST, k=num_keywords)
1741
+
1742
+
1743
+ """Library of instructions"""
1744
+ _InstructionArgsDtype = dict[str, int | str | Sequence[str]] | None
1745
+
1746
+ _LANGUAGES = LANGUAGE_CODES
1747
+
1748
+ # The relational operation for comparison.
1749
+ _COMPARISON_RELATION = ("less than", "at least")
1750
+
1751
+ # The maximum number of sentences.
1752
+ _MAX_NUM_SENTENCES = 20
1753
+
1754
+ # The number of placeholders.
1755
+ _NUM_PLACEHOLDERS = 4
1756
+
1757
+ # The number of bullet lists.
1758
+ _NUM_BULLETS = 5
1759
+
1760
+ # The options of constrained response.
1761
+ _CONSTRAINED_RESPONSE_OPTIONS = (
1762
+ "My answer is yes.",
1763
+ "My answer is no.",
1764
+ "My answer is maybe.",
1765
+ )
1766
+
1767
+ # The options of starter keywords.
1768
+ _STARTER_OPTIONS = (
1769
+ "I would say",
1770
+ "My answer is",
1771
+ "I believe",
1772
+ "In my opinion",
1773
+ "I think",
1774
+ "I reckon",
1775
+ "I feel",
1776
+ "From my perspective",
1777
+ "As I see it",
1778
+ "According to me",
1779
+ "As far as I'm concerned",
1780
+ "To my understanding",
1781
+ "In my view",
1782
+ "My take on it is",
1783
+ "As per my perception",
1784
+ )
1785
+
1786
+ # The options of ending keywords.
1787
+ # TODO(jeffreyzhou) add more ending options
1788
+ _ENDING_OPTIONS = ("Any other questions?", "Is there anything else I can help with?")
1789
+
1790
+ # The number of highlighted sections.
1791
+ _NUM_HIGHLIGHTED_SECTIONS = 4
1792
+
1793
+ # The section spliter.
1794
+ _SECTION_SPLITER = ("Section", "SECTION")
1795
+
1796
+ # The number of sections.
1797
+ _NUM_SECTIONS = 5
1798
+
1799
+ # The number of paragraphs.
1800
+ _NUM_PARAGRAPHS = 5
1801
+
1802
+ # The postscript marker.
1803
+ _POSTSCRIPT_MARKER = ("P.S.", "P.P.S")
1804
+
1805
+ # The number of keywords.
1806
+ _NUM_KEYWORDS = 2
1807
+
1808
+ # The occurrences of a single keyword.
1809
+ _KEYWORD_FREQUENCY = 3
1810
+
1811
+ # The occurrences of a single letter.
1812
+ _LETTER_FREQUENCY = 10
1813
+
1814
+ # The occurrences of words with all capital letters.
1815
+ _ALL_CAPITAL_WORD_FREQUENCY = 20
1816
+
1817
+ # The number of words in the response.
1818
+ _NUM_WORDS_LOWER_LIMIT = 100
1819
+ _NUM_WORDS_UPPER_LIMIT = 500
1820
+
1821
+
1822
+ class Instruction:
1823
+ """An instruction template."""
1824
+
1825
+ def __init__(self, instruction_id):
1826
+ self.id = instruction_id
1827
+
1828
+ def build_description(self, **kwargs):
1829
+ raise NotImplementedError("`build_description` not implemented.")
1830
+
1831
+ def get_instruction_args(self):
1832
+ raise NotImplementedError("`get_instruction_args` not implemented.")
1833
+
1834
+ def get_instruction_args_keys(self):
1835
+ raise NotImplementedError("`get_instruction_args_keys` not implemented.")
1836
+
1837
+ def check_following(self, value):
1838
+ raise NotImplementedError("`check_following` not implemented.")
1839
+
1840
+
1841
+ class ResponseLanguageChecker(Instruction):
1842
+ """Check the language of the entire response."""
1843
+
1844
+ def build_description(self, *, language=None):
1845
+ """Build the instruction description.
1846
+
1847
+ Args:
1848
+ language: A string representing the expected language of the response. The
1849
+ language has to comply to the 97 types defined in
1850
+ `langid.py` (https://pypi.org/project/langid/1.1.5/), which follows
1851
+ ISO 639-1 codes (https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes);
1852
+ for example, `en` for English, `zh` for Chinese, `fr` for French.
1853
+
1854
+ Returns:
1855
+ A string representing the instruction description.
1856
+ """
1857
+ self._language = language
1858
+ if self._language is None:
1859
+ self._language = random.choice(list(_LANGUAGES.keys()))
1860
+
1861
+ self._description_pattern = (
1862
+ "Your ENTIRE response should be in {language} language, no other " + "language is allowed."
1863
+ )
1864
+ return self._description_pattern.format(language=_LANGUAGES[self._language])
1865
+
1866
+ def get_instruction_args(self):
1867
+ """Returns the keyward args of `build_description`."""
1868
+ return {"language": self._language}
1869
+
1870
+ def get_instruction_args_keys(self):
1871
+ """Returns the args keys of `build_description`."""
1872
+ return ["language"]
1873
+
1874
+ def check_following(self, value):
1875
+ """Check if the language of the entire response follows the instruction.
1876
+
1877
+ Args:
1878
+ value: A string representing the response.
1879
+
1880
+ Returns:
1881
+ True if the language of `value` follows instruction; otherwise False.
1882
+ """
1883
+ assert isinstance(value, str)
1884
+
1885
+ try:
1886
+ return langdetect.detect(value) == self._language
1887
+ except langdetect.LangDetectException as e:
1888
+ # Count as instruction is followed.
1889
+ logger.info("Unable to detect language for text %s due to %s", value, e) # refex: disable=pytotw.037
1890
+ return True
1891
+
1892
+
1893
+ class NumberOfSentences(Instruction):
1894
+ """Check the number of sentences."""
1895
+
1896
+ def build_description(self, *, num_sentences=None, relation=None):
1897
+ """Build the instruction description.
1898
+
1899
+ Args:
1900
+ num_sentences: An integer specifying the number of sentences as a
1901
+ threshold.
1902
+ relation: A string in (`less than`, `at least`), defining the relational
1903
+ operator for comparison.
1904
+ Two relational comparisons are supported for now:
1905
+ if 'less than', the actual number of sentences < the threshold;
1906
+ if 'at least', the actual number of sentences >= the threshold.
1907
+
1908
+ Returns:
1909
+ A string representing the instruction description.
1910
+ """
1911
+ # The number of sentences as a threshold for comparison.
1912
+ self._num_sentences_threshold = num_sentences
1913
+ if self._num_sentences_threshold is None or self._num_sentences_threshold < 0:
1914
+ self._num_sentences_threshold = random.randint(1, _MAX_NUM_SENTENCES)
1915
+
1916
+ if relation is None:
1917
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1918
+ elif relation not in _COMPARISON_RELATION:
1919
+ raise ValueError(
1920
+ f"The supported relation for comparison must be in {_COMPARISON_RELATION}, but {relation} is given."
1921
+ )
1922
+ else:
1923
+ self._comparison_relation = relation
1924
+
1925
+ self._description_pattern = "Your response should contain {relation} {num_sentences} sentences."
1926
+ return self._description_pattern.format(
1927
+ relation=self._comparison_relation,
1928
+ num_sentences=self._num_sentences_threshold,
1929
+ )
1930
+
1931
+ def get_instruction_args(self):
1932
+ """Returns the keyward args of `build_description`."""
1933
+ return {
1934
+ "num_sentences": self._num_sentences_threshold,
1935
+ "relation": self._comparison_relation,
1936
+ }
1937
+
1938
+ def get_instruction_args_keys(self):
1939
+ """Returns the args keys of `build_description`."""
1940
+ return ["num_sentences", "relation"]
1941
+
1942
+ def check_following(self, value):
1943
+ """Check if the number of sentences follows the instruction.
1944
+
1945
+ Args:
1946
+ value: A string representing the response.
1947
+
1948
+ Returns:
1949
+ True if the response follows the instruction.
1950
+
1951
+ Raise:
1952
+ ValueError if the string in `instruction_args` is not in
1953
+ [`less_than`, `at_least`].
1954
+ """
1955
+ lang = get_langid(value)
1956
+ if lang == "th":
1957
+ # Counting Newline also as a new sentence:
1958
+ num_sentences = sum([len(sent_tokenize_thai(line)) for line in value.splitlines()])
1959
+ elif lang in ["zh", "zh-cn", "zh-tw", "ja", "hi"]:
1960
+ num_sentences = len(list(split_chinese_japanese_hindi(value)))
1961
+ else:
1962
+ num_sentences = count_sentences(value)
1963
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1964
+ return num_sentences < self._num_sentences_threshold
1965
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
1966
+ return num_sentences >= self._num_sentences_threshold
1967
+
1968
+
1969
+ class PlaceholderChecker(Instruction):
1970
+ """Check the placeholders in template writing."""
1971
+
1972
+ def build_description(self, *, num_placeholders=None):
1973
+ """Build the instruction description.
1974
+
1975
+ Args:
1976
+ num_placeholders: An integer denoting the minimum number of
1977
+ placeholders required in the response.
1978
+
1979
+ Returns:
1980
+ A string representing the instruction description.
1981
+ """
1982
+ self._num_placeholders = num_placeholders
1983
+ if self._num_placeholders is None or self._num_placeholders < 0:
1984
+ self._num_placeholders = random.randint(1, _NUM_PLACEHOLDERS)
1985
+ self._description_pattern = (
1986
+ "The response must contain at least {num_placeholders} placeholders "
1987
+ + "represented by square brackets, such as [address]."
1988
+ )
1989
+ return self._description_pattern.format(num_placeholders=self._num_placeholders)
1990
+
1991
+ def get_instruction_args(self):
1992
+ """Returns the keyward args of `build_description`."""
1993
+ return {"num_placeholders": self._num_placeholders}
1994
+
1995
+ def get_instruction_args_keys(self):
1996
+ """Returns the args keys of `build_description`."""
1997
+ return ["num_placeholders"]
1998
+
1999
+ def check_following(self, value):
2000
+ """Check if the number of placeholders follows the instruction.
2001
+
2002
+ Args:
2003
+ value: A string representing the response.
2004
+
2005
+ Returns:
2006
+ True if the actual number of placeholders in the response is greater than
2007
+ or equal to `num_placeholders`; otherwise, False.
2008
+ """
2009
+ placeholders = re.findall(r"\[.*?\]", value)
2010
+ num_placeholders = len(placeholders)
2011
+ return num_placeholders >= self._num_placeholders
2012
+
2013
+
2014
+ class BulletListChecker(Instruction):
2015
+ """Checks the bullet list in the prompt."""
2016
+
2017
+ def build_description(self, *, num_bullets=None):
2018
+ """Build the instruction description.
2019
+
2020
+ Args:
2021
+ num_bullets: An integer specifying the exact number of bullet lists
2022
+ that is required to appear in the response.
2023
+
2024
+ Returns:
2025
+ A string representing the instruction description.
2026
+ """
2027
+ self._num_bullets = num_bullets
2028
+ if self._num_bullets is None or self._num_bullets < 0:
2029
+ self._num_bullets = random.randint(1, _NUM_BULLETS)
2030
+ self._description_pattern = (
2031
+ "Your answer must contain exactly {num_bullets} bullet points. "
2032
+ + "Use the markdown bullet points such as:\n"
2033
+ + "* This is point 1. \n"
2034
+ + "* This is point 2"
2035
+ )
2036
+ return self._description_pattern.format(num_bullets=self._num_bullets)
2037
+
2038
+ def get_instruction_args(self):
2039
+ """Returns the keyward args of `build_description`."""
2040
+ return {"num_bullets": self._num_bullets}
2041
+
2042
+ def get_instruction_args_keys(self):
2043
+ """Returns the args keys of `build_description`."""
2044
+ return ["num_bullets"]
2045
+
2046
+ def check_following(self, value):
2047
+ r"""Check if the number of bullet lists meets the requirement.
2048
+
2049
+ Args:
2050
+ value: A string representing the response. The response is expected to
2051
+ contain some bullet lists that start with `\*`.
2052
+
2053
+ Returns:
2054
+ True if the actual number of bullet lists in the response meets the
2055
+ requirement.
2056
+ """
2057
+ bullet_lists = re.findall(r"^\s*\*[^\*].*$", value, flags=re.MULTILINE)
2058
+ bullet_lists_2 = re.findall(r"^\s*-.*$", value, flags=re.MULTILINE)
2059
+ num_bullet_lists = len(bullet_lists) + len(bullet_lists_2)
2060
+ return num_bullet_lists == self._num_bullets
2061
+
2062
+
2063
+ class ConstrainedResponseChecker(Instruction):
2064
+ """Checks the constrained response."""
2065
+
2066
+ def build_description(self):
2067
+ """Build the instruction description."""
2068
+ # A sequence of string(s) representing the options of the expected response.
2069
+ self._constrained_responses = _CONSTRAINED_RESPONSE_OPTIONS
2070
+ self._description_pattern = "Answer with one of the following options: {response_options}"
2071
+ return self._description_pattern.format(response_options=self._constrained_responses)
2072
+
2073
+ def get_instruction_args(self):
2074
+ """Returns the keyward args of `build_description`."""
2075
+ return None
2076
+
2077
+ def get_instruction_args_keys(self):
2078
+ """Returns the args keys of `build_description`."""
2079
+ return []
2080
+
2081
+ def check_following(self, value):
2082
+ """Checks if the response matches the constrained options.
2083
+
2084
+ Args:
2085
+ value: A string representing the response.
2086
+
2087
+ Returns:
2088
+ True if the actual response contains one of the options in the constrained
2089
+ responses; otherwise False.
2090
+ """
2091
+ value = value.strip()
2092
+ for constrained_response in self._constrained_responses:
2093
+ if constrained_response in value:
2094
+ return True
2095
+ return False
2096
+
2097
+
2098
+ class ConstrainedStartChecker(Instruction):
2099
+ """Checks the response start."""
2100
+
2101
+ def build_description(self, *, starter=None):
2102
+ """Build the instruction description.
2103
+
2104
+ Args:
2105
+ starter: A string representing the keyward that the response should start
2106
+ with.
2107
+
2108
+ Returns:
2109
+ A string representing the instruction description.
2110
+ """
2111
+ self._starter = starter.strip() if isinstance(starter, str) else starter
2112
+ if self._starter is None:
2113
+ self._starter = random.choice(_STARTER_OPTIONS)
2114
+ self._description_pattern = (
2115
+ "During the conversation, when it is your turn, " + "please always start with {starter}"
2116
+ )
2117
+ return self._description_pattern.format(starter=self._starter)
2118
+
2119
+ def get_instruction_args(self):
2120
+ """Returns the keyward args of `build_description`."""
2121
+ return {"starter": self._starter}
2122
+
2123
+ def get_instruction_args_keys(self):
2124
+ """Returns the args keys of `build_description`."""
2125
+ return ["starter"]
2126
+
2127
+ def check_following(self, value):
2128
+ """Checks if the response starts with the constrained keyword or phrase.
2129
+
2130
+ Args:
2131
+ value: A string representing the response.
2132
+
2133
+ Returns:
2134
+ True if the response starts with the given phrase or keyword that is
2135
+ contained in `instruction_args`; otherwise, False.
2136
+ """
2137
+ response_pattern = r"^\s*" + self._starter + r".*$"
2138
+ response_with_constrained_start = re.search(response_pattern, value, flags=re.MULTILINE)
2139
+ return True if response_with_constrained_start else False
2140
+
2141
+
2142
+ class HighlightSectionChecker(Instruction):
2143
+ """Checks the highlighted section."""
2144
+
2145
+ def build_description(self, *, num_highlights=None):
2146
+ """Build the instruction description.
2147
+
2148
+ Args:
2149
+ num_highlights: An integer specifying the minimum number of highlighted
2150
+ sections.
2151
+
2152
+ Returns:
2153
+ A string representing the instruction description.
2154
+ """
2155
+ self._num_highlights = num_highlights
2156
+ if self._num_highlights is None or self._num_highlights < 0:
2157
+ self._num_highlights = random.randint(1, _NUM_HIGHLIGHTED_SECTIONS)
2158
+
2159
+ self._description_pattern = (
2160
+ "Highlight at least {num_highlights} sections in your answer with "
2161
+ + "markdown, i.e. *highlighted section*."
2162
+ )
2163
+
2164
+ return self._description_pattern.format(num_highlights=self._num_highlights)
2165
+
2166
+ def get_instruction_args(self):
2167
+ """Returns the keyward args of `build_description`."""
2168
+ return {"num_highlights": self._num_highlights}
2169
+
2170
+ def get_instruction_args_keys(self):
2171
+ """Returns the args keys of `build_description`."""
2172
+ return ["num_highlights"]
2173
+
2174
+ def check_following(self, value):
2175
+ """Checks if the number of highlighted sections meets the requirement.
2176
+
2177
+ Args:
2178
+ value: a string repesenting the response. The response is expected to
2179
+ contain highlighted sections in the format of *highlighted*.
2180
+
2181
+ Returns:
2182
+ True if the actual number of highlighted sections in the format of
2183
+ *highlighed sections* meets the minimum requirement; otherwise False.
2184
+ """
2185
+ num_highlights = 0
2186
+ highlights = re.findall(r"\*[^\n\*]*\*", value)
2187
+ double_highlights = re.findall(r"\*\*[^\n\*]*\*\*", value)
2188
+ for highlight in highlights:
2189
+ if highlight.strip("*").strip():
2190
+ num_highlights += 1
2191
+ for highlight in double_highlights:
2192
+ if highlight.removeprefix("**").removesuffix("**").strip():
2193
+ num_highlights += 1
2194
+
2195
+ return num_highlights >= self._num_highlights
2196
+
2197
+
2198
+ class SectionChecker(Instruction):
2199
+ """Checks the sections."""
2200
+
2201
+ def build_description(self, *, section_spliter=None, num_sections=None):
2202
+ """Build the instruction description.
2203
+
2204
+ Args:
2205
+ section_spliter: A string represents the section spliter keyword that
2206
+ marks a new section, i.e., `Section` or `SECTION`.
2207
+ num_sections: An integer specifying the number of sections.
2208
+
2209
+ Returns:
2210
+ A string representing the instruction description.
2211
+ """
2212
+ self._section_spliter = section_spliter.strip() if isinstance(section_spliter, str) else section_spliter
2213
+ if self._section_spliter is None:
2214
+ self._section_spliter = random.choice(_SECTION_SPLITER)
2215
+
2216
+ self._num_sections = num_sections
2217
+ if self._num_sections is None or self._num_sections < 0:
2218
+ self._num_sections = random.randint(1, _NUM_SECTIONS)
2219
+
2220
+ self._description_pattern = (
2221
+ "Your response must have {num_sections} sections. Mark the beginning "
2222
+ + "of each section with {section_spliter} X, such as:\n"
2223
+ + "{section_spliter} 1\n"
2224
+ + "[content of section 1]\n"
2225
+ + "{section_spliter} 2\n"
2226
+ + "[content of section 2]"
2227
+ )
2228
+
2229
+ return self._description_pattern.format(num_sections=self._num_sections, section_spliter=self._section_spliter)
2230
+
2231
+ def get_instruction_args(self):
2232
+ """Returns the keyward args of `build_description`."""
2233
+ return {
2234
+ "section_spliter": self._section_spliter,
2235
+ "num_sections": self._num_sections,
2236
+ }
2237
+
2238
+ def get_instruction_args_keys(self):
2239
+ """Returns the args keys of `build_description`."""
2240
+ return ["section_spliter", "num_sections"]
2241
+
2242
+ def check_following(self, value):
2243
+ """Checks the response contains multiple sections.
2244
+
2245
+ Args:
2246
+ value: A string representing the response. The response is expected
2247
+ to contain multiple sections (number of sections is greater than 1).
2248
+ A new section starts with `Section 1`, where the number denotes the
2249
+ section index.
2250
+
2251
+ Returns:
2252
+ True if the number of sections in the response is greater than or equal to
2253
+ the minimum number of sections; otherwise, False.
2254
+ """
2255
+ section_splitter_patten = r"\s?" + self._section_spliter + r"\s?\d+\s?"
2256
+ sections = re.split(section_splitter_patten, value)
2257
+ num_sections = len(sections) - 1
2258
+ return num_sections >= self._num_sections
2259
+
2260
+
2261
+ class ParagraphChecker(Instruction):
2262
+ """Checks the paragraphs."""
2263
+
2264
+ def build_description(self, *, num_paragraphs=None):
2265
+ """Build the instruction description.
2266
+
2267
+ Args:
2268
+ num_paragraphs: An integer specifying the number of paragraphs.
2269
+
2270
+ Returns:
2271
+ A string representing the instruction description.
2272
+ """
2273
+ self._num_paragraphs = num_paragraphs
2274
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
2275
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
2276
+
2277
+ self._description_pattern = (
2278
+ "There should be {num_paragraphs} paragraphs. " + "Paragraphs are separated with the markdown divider: ***"
2279
+ )
2280
+
2281
+ return self._description_pattern.format(num_paragraphs=self._num_paragraphs)
2282
+
2283
+ def get_instruction_args(self):
2284
+ """Returns the keyward args of `build_description`."""
2285
+ return {"num_paragraphs": self._num_paragraphs}
2286
+
2287
+ def get_instruction_args_keys(self):
2288
+ """Returns the args keys of `build_description`."""
2289
+ return ["num_paragraphs"]
2290
+
2291
+ def check_following(self, value):
2292
+ """Checks the response contains required number of paragraphs.
2293
+
2294
+ Args:
2295
+ value: A string representing the response. The response may contain
2296
+ paragraphs that are separated by the markdown divider: `***`.
2297
+
2298
+ Returns:
2299
+ True if the actual number of paragraphs is the same as required;
2300
+ otherwise, False.
2301
+ """
2302
+ paragraphs = re.split(r"\s?\*\*\*\s?", value)
2303
+ num_paragraphs = len(paragraphs)
2304
+
2305
+ for index, paragraph in enumerate(paragraphs):
2306
+ if not paragraph.strip():
2307
+ if index == 0 or index == len(paragraphs) - 1:
2308
+ num_paragraphs -= 1
2309
+ else:
2310
+ return False
2311
+
2312
+ return num_paragraphs == self._num_paragraphs
2313
+
2314
+
2315
+ class PostscriptChecker(Instruction):
2316
+ """Checks the postscript."""
2317
+
2318
+ def build_description(self, *, postscript_marker=None):
2319
+ """Build the instruction description.
2320
+
2321
+ Args:
2322
+ postscript_marker: A string containing the keyword that marks the start
2323
+ of the postscript section.
2324
+
2325
+ Returns:
2326
+ A string representing the instruction description.
2327
+ """
2328
+ self._postscript_marker = postscript_marker.strip() if isinstance(postscript_marker, str) else postscript_marker
2329
+ if self._postscript_marker is None:
2330
+ self._postscript_marker = random.choice(_POSTSCRIPT_MARKER)
2331
+
2332
+ self._description_pattern = (
2333
+ "At the end of your response, please explicitly add a postscript " + "starting with {postscript}"
2334
+ )
2335
+
2336
+ return self._description_pattern.format(postscript=self._postscript_marker)
2337
+
2338
+ def get_instruction_args(self):
2339
+ """Returns the keyward args of `build_description`."""
2340
+ return {"postscript_marker": self._postscript_marker}
2341
+
2342
+ def get_instruction_args_keys(self):
2343
+ """Returns the args keys of `build_description`."""
2344
+ return ["postscript_marker"]
2345
+
2346
+ def check_following(self, value):
2347
+ """Checks if the response follows the postscript format.
2348
+
2349
+ Args:
2350
+ value: a string representing the response. The response is expected to
2351
+ contain a postscript section.
2352
+
2353
+ Returns:
2354
+ True if the response contains a postscript section starting with
2355
+ the keyword containing in the `instruction_args`; otherwise False.
2356
+ """
2357
+ value = value.lower()
2358
+ if self._postscript_marker == "P.P.S":
2359
+ postscript_pattern = r"\s*p\.\s?p\.\s?s.*$"
2360
+ elif self._postscript_marker == "P.S.":
2361
+ postscript_pattern = r"\s*p\.\s?s\..*$"
2362
+ else:
2363
+ postscript_pattern = r"\s*" + self._postscript_marker.lower() + r".*$"
2364
+ postscript = re.findall(postscript_pattern, value, flags=re.MULTILINE)
2365
+ return True if postscript else False
2366
+
2367
+
2368
+ class RephraseChecker(Instruction):
2369
+ """Checks the repharse."""
2370
+
2371
+ def build_description(self, *, original_message):
2372
+ """Build the instruction description.
2373
+
2374
+ Args:
2375
+ original_message: A string representing the original message. The
2376
+ rephrased response should only change its words/sentences in between
2377
+ its two asterisks, for example, *change me*. Both original and rephrased
2378
+ messages should contain the changes in the form of *change me*.
2379
+
2380
+ Returns:
2381
+ A string representing the instruction description.
2382
+ """
2383
+ if not self.is_change(original_message):
2384
+ raise ValueError(f"Message {original_message} does not contain changes in the form of *change me*.")
2385
+
2386
+ self._reference_without_change = original_message
2387
+ self._description = (
2388
+ "Rephrasing: Your rephrased response should only"
2389
+ + "change the words/sentences in between two asterisks"
2390
+ + "such as *change me*."
2391
+ )
2392
+ return self._description
2393
+
2394
+ def get_instruction_args(self):
2395
+ """Returns the keyward args of `build_description`."""
2396
+ return {"original_message": self._reference_without_change}
2397
+
2398
+ def get_instruction_args_keys(self):
2399
+ """Returns the args keys of `build_description`."""
2400
+ return ["original_message"]
2401
+
2402
+ def check_following(self, value):
2403
+ r"""Checks if the rephrasing follows the instruction.
2404
+
2405
+ Args:
2406
+ value: A string representing the response, which is expected to rephras
2407
+ the string of `instruction_args`.
2408
+
2409
+ Returns:
2410
+ True if `value` and `instruction_args` only differ by the words/sentences
2411
+ in between two asterisks such as *change me*; otherwise, False.
2412
+ """
2413
+
2414
+ if not self.is_change(value):
2415
+ raise ValueError(f"value {value} does not contain changes in the form of *change me*.")
2416
+
2417
+ response_without_changes = self.strip_changes(value)
2418
+ reference_without_changes = self.strip_changes(self._reference_without_change)
2419
+
2420
+ return response_without_changes == reference_without_changes
2421
+
2422
+ def is_change(self, response):
2423
+ """Check if there is change in the response in the form of *change me*."""
2424
+ return re.search(r"\*.*\*", response)
2425
+
2426
+ def strip_changes(self, response):
2427
+ """Strips off the changes."""
2428
+ return re.sub(r"\*.*\*", "", response)
2429
+
2430
+
2431
+ class KeywordChecker(Instruction):
2432
+ """Check the exisitence of certain keywords."""
2433
+
2434
+ def build_description(self, *, keywords=None):
2435
+ """Build the instruction description.
2436
+
2437
+ Args:
2438
+ keywords: A sequence of strings representing the keywords that are
2439
+ expected in the response.
2440
+
2441
+ Returns:
2442
+ A string representing the instruction description.
2443
+ """
2444
+
2445
+ if not keywords:
2446
+ self._keywords = generate_keywords(num_keywords=_NUM_KEYWORDS)
2447
+ else:
2448
+ self._keywords = keywords
2449
+ self._keywords = sorted(self._keywords)
2450
+
2451
+ self._description_pattern = "Include keywords {keywords} in the response."
2452
+
2453
+ return self._description_pattern.format(keywords=self._keywords)
2454
+
2455
+ def get_instruction_args(self):
2456
+ """Returns the keyward args of `build_description`."""
2457
+ return {"keywords": self._keywords}
2458
+
2459
+ def get_instruction_args_keys(self):
2460
+ """Returns the args keys of `build_description`."""
2461
+ return ["keywords"]
2462
+
2463
+ def check_following(self, value):
2464
+ """Check if the response contain the expected keywords."""
2465
+ for keyword in self._keywords:
2466
+ if not re.search(keyword, value, flags=re.IGNORECASE):
2467
+ return False
2468
+ return True
2469
+
2470
+
2471
+ class KeywordFrequencyChecker(Instruction):
2472
+ """Check the keyword frequency."""
2473
+
2474
+ def build_description(self, *, keyword=None, frequency=None, relation=None):
2475
+ """Build the instruction description.
2476
+
2477
+ Args:
2478
+ keyword: A string representing a keyword that is expected in the response.
2479
+ frequency: An integer specifying the number of times `keyword` is expected
2480
+ to appear in the response.
2481
+ relation: A string in (`less than`, `at least`), defining the relational
2482
+ operator for comparison.
2483
+ Two relational comparisons are supported for now:
2484
+ if 'less than', the actual number of occurrences < frequency;
2485
+ if 'at least', the actual number of occurrences >= frequency.
2486
+
2487
+ Returns:
2488
+ A string representing the instruction description.
2489
+ """
2490
+ if not keyword:
2491
+ self._keyword = generate_keywords(num_keywords=1)[0]
2492
+ else:
2493
+ self._keyword = keyword.strip()
2494
+
2495
+ self._frequency = frequency
2496
+ if self._frequency is None or self._frequency < 0:
2497
+ self._frequency = random.randint(1, _KEYWORD_FREQUENCY)
2498
+
2499
+ if relation is None:
2500
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
2501
+ elif relation not in _COMPARISON_RELATION:
2502
+ raise ValueError(
2503
+ f"The supported relation for comparison must be in {_COMPARISON_RELATION}, but {relation} is given."
2504
+ )
2505
+ else:
2506
+ self._comparison_relation = relation
2507
+
2508
+ self._description_pattern = (
2509
+ "In your response, the word {keyword} should appear {relation} " + "{frequency} times."
2510
+ )
2511
+
2512
+ return self._description_pattern.format(
2513
+ keyword=self._keyword,
2514
+ relation=self._comparison_relation,
2515
+ frequency=self._frequency,
2516
+ )
2517
+
2518
+ def get_instruction_args(self):
2519
+ """Returns the keyward args of `build_description`."""
2520
+ return {
2521
+ "keyword": self._keyword,
2522
+ "frequency": self._frequency,
2523
+ "relation": self._comparison_relation,
2524
+ }
2525
+
2526
+ def get_instruction_args_keys(self):
2527
+ """Returns the args keys of `build_description`."""
2528
+ return ["keyword", "frequency", "relation"]
2529
+
2530
+ def check_following(self, value):
2531
+ """Checks if the response contain the keyword with required frequency."""
2532
+ actual_occurrences = len(re.findall(self._keyword, value, flags=re.IGNORECASE))
2533
+
2534
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
2535
+ return actual_occurrences < self._frequency
2536
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
2537
+ return actual_occurrences >= self._frequency
2538
+
2539
+
2540
+ class NumberOfWords(Instruction):
2541
+ """Checks the number of words."""
2542
+
2543
+ def build_description(self, *, num_words=None, relation=None):
2544
+ """Build the instruction description.
2545
+
2546
+ Args:
2547
+ num_words: An integer specifying the number of words contained in the
2548
+ response.
2549
+ relation: A string in (`less than`, `at least`), defining the relational
2550
+ operator for comparison.
2551
+ Two relational comparisons are supported for now:
2552
+ if 'less than', the actual number of words < num_words;
2553
+ if 'at least', the actual number of words >= num_words.
2554
+
2555
+ Returns:
2556
+ A string representing the instruction description.
2557
+ """
2558
+
2559
+ self._num_words = num_words
2560
+ if self._num_words is None or self._num_words < 0:
2561
+ self._num_words = random.randint(_NUM_WORDS_LOWER_LIMIT, _NUM_WORDS_UPPER_LIMIT)
2562
+
2563
+ if relation is None:
2564
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
2565
+ elif relation not in _COMPARISON_RELATION:
2566
+ raise ValueError(
2567
+ f"The supported relation for comparison must be in {_COMPARISON_RELATION}, but {relation} is given."
2568
+ )
2569
+ else:
2570
+ self._comparison_relation = relation
2571
+
2572
+ self._description_pattern = "Answer with {relation} {num_words} words."
2573
+
2574
+ return self._description_pattern.format(relation=self._comparison_relation, num_words=self._num_words)
2575
+
2576
+ def get_instruction_args(self):
2577
+ """Returns the keyward args of `build_description`."""
2578
+ return {"num_words": self._num_words, "relation": self._comparison_relation}
2579
+
2580
+ def get_instruction_args_keys(self):
2581
+ """Returns the args keys of `build_description`."""
2582
+ return ["num_words", "relation"]
2583
+
2584
+ def check_following(self, value):
2585
+ """Checks if the response contains the expected number of words."""
2586
+ lang = get_langid(value)
2587
+ if lang == "th":
2588
+ num_words = len(word_tokenize_thai(value))
2589
+ elif lang in ["zh", "zh-cn", "zh-tw", "ja", "ko"]:
2590
+ num_words = count_words_cjk(value)
2591
+ else:
2592
+ num_words = count_words(value)
2593
+
2594
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
2595
+ return num_words < self._num_words
2596
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
2597
+ return num_words >= self._num_words
2598
+
2599
+
2600
+ class JsonFormat(Instruction):
2601
+ """Check the Json format."""
2602
+
2603
+ def build_description(self):
2604
+ self._description_pattern = (
2605
+ "Entire output should be wrapped in JSON format. You can use markdown ticks such as ```."
2606
+ )
2607
+ return self._description_pattern
2608
+
2609
+ def get_instruction_args(self):
2610
+ """Returns the keyward args of `build_description`."""
2611
+ return None
2612
+
2613
+ def get_instruction_args_keys(self):
2614
+ """Returns the args keys of `build_description`."""
2615
+ return []
2616
+
2617
+ def check_following(self, value):
2618
+ value = (
2619
+ value.strip()
2620
+ .removeprefix("```json")
2621
+ .removeprefix("```Json")
2622
+ .removeprefix("```JSON")
2623
+ .removeprefix("```")
2624
+ .removesuffix("```")
2625
+ .strip()
2626
+ )
2627
+ try:
2628
+ json.loads(value)
2629
+ except ValueError as _:
2630
+ return False
2631
+ return True
2632
+
2633
+
2634
+ class ParagraphFirstWordCheck(Instruction):
2635
+ """Check the paragraph and the first word of the nth paragraph."""
2636
+
2637
+ def build_description(self, num_paragraphs=None, nth_paragraph=None, first_word=None):
2638
+ r"""Build the instruction description.
2639
+
2640
+ Args:
2641
+ num_paragraphs: An integer indicating the number of paragraphs expected
2642
+ in the response. A paragraph is a subset of the string that is
2643
+ expected to be separated by '\n\n'.
2644
+ nth_paragraph: An integer indicating the paragraph number that we look at.
2645
+ Note that n starts from 1.
2646
+ first_word: A string that represent the first word of the bth paragraph.
2647
+
2648
+ Returns:
2649
+ A string representing the instruction description.
2650
+ """
2651
+ self._num_paragraphs = num_paragraphs
2652
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
2653
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
2654
+
2655
+ self._nth_paragraph = nth_paragraph
2656
+ if self._nth_paragraph is None or self._nth_paragraph <= 0 or self._nth_paragraph > self._num_paragraphs:
2657
+ self._nth_paragraph = random.randint(1, self._num_paragraphs + 1)
2658
+
2659
+ self._first_word = first_word
2660
+ if self._first_word is None:
2661
+ self._first_word = generate_keywords(num_keywords=1)[0]
2662
+ self._first_word = self._first_word.lower()
2663
+
2664
+ self._description_pattern = (
2665
+ "There should be {num_paragraphs} paragraphs. "
2666
+ + "Paragraphs and only paragraphs are separated with each other by two "
2667
+ + "new lines as if it was '\\n\\n' in python. "
2668
+ + "Paragraph {nth_paragraph} must start with word {first_word}."
2669
+ )
2670
+
2671
+ return self._description_pattern.format(
2672
+ num_paragraphs=self._num_paragraphs,
2673
+ nth_paragraph=self._nth_paragraph,
2674
+ first_word=self._first_word,
2675
+ )
2676
+
2677
+ def get_instruction_args(self):
2678
+ """Returns the keyward args of `build_description`."""
2679
+ return {
2680
+ "num_paragraphs": self._num_paragraphs,
2681
+ "nth_paragraph": self._nth_paragraph,
2682
+ "first_word": self._first_word,
2683
+ }
2684
+
2685
+ def get_instruction_args_keys(self):
2686
+ """Returns the args keys of `build_description`."""
2687
+ return ["num_paragraphs", "nth_paragraph", "first_word"]
2688
+
2689
+ def check_following(self, value):
2690
+ """Checks for required number of paragraphs and correct first word.
2691
+
2692
+ Args:
2693
+ value: a string representing the response. The response may contain
2694
+ paragraphs that are separated by two new lines and the first word of
2695
+ the nth paragraph will have to match a specified word.
2696
+
2697
+ Returns:
2698
+ True if the number of paragraphs is the same as required and the first
2699
+ word of the specified paragraph is the same as required. Otherwise, false.
2700
+ """
2701
+
2702
+ paragraphs = re.split(r"\n\n", value)
2703
+ num_paragraphs = len(paragraphs)
2704
+
2705
+ for paragraph in paragraphs:
2706
+ if not paragraph.strip():
2707
+ num_paragraphs -= 1
2708
+
2709
+ # check that index doesn't go out of bounds
2710
+ if self._nth_paragraph <= num_paragraphs:
2711
+ paragraph = paragraphs[self._nth_paragraph - 1].strip()
2712
+ if not paragraph:
2713
+ return False
2714
+ else:
2715
+ return False
2716
+
2717
+ first_word = ""
2718
+ punctuation = {".", ",", "?", "!", "'", '"'}
2719
+
2720
+ # get first word and remove punctuation
2721
+ word = paragraph.split()[0].strip()
2722
+ word = word.lstrip("'")
2723
+ word = word.lstrip('"')
2724
+
2725
+ for letter in word:
2726
+ if letter in punctuation:
2727
+ break
2728
+ first_word += letter.lower()
2729
+
2730
+ return num_paragraphs == self._num_paragraphs and first_word == self._first_word
2731
+
2732
+
2733
+ class KeySentenceChecker(Instruction):
2734
+ """Check the existence of certain key sentences."""
2735
+
2736
+ def build_description(self, key_sentences=None, num_sentences=None):
2737
+ """Build the instruction description.
2738
+
2739
+ Args:
2740
+ key_sentences: A sequences of strings representing the key sentences that
2741
+ are expected in the response.
2742
+ num_sentences: The number of key sentences that are expected to be seen in
2743
+ the response.
2744
+
2745
+ Returns:
2746
+ A string representing the instruction description.
2747
+ """
2748
+
2749
+ if not key_sentences:
2750
+ self._key_sentences = {["For now, this is fine."]}
2751
+ else:
2752
+ self._key_sentences = key_sentences
2753
+
2754
+ if not num_sentences:
2755
+ self._num_sentences = random.randint(1, len(self._key_sentences))
2756
+ else:
2757
+ self._num_sentences = num_sentences
2758
+
2759
+ self._description_pattern = "Include {num_sentences} of the following sentences {key_sentences}"
2760
+
2761
+ return self._description_pattern.format(num_sentences=self._num_sentences, key_sentences=self._key_sentences)
2762
+
2763
+ def get_instruction_args(self):
2764
+ """Returns the keyward args of `build_description`."""
2765
+ return {
2766
+ "num_sentences": self._num_sentences,
2767
+ "key_sentences": list(self._key_sentences),
2768
+ }
2769
+
2770
+ def get_instruction_args_keys(self):
2771
+ """Returns the args keys of `build_description`."""
2772
+ return ["num_sentences", "key_sentences"]
2773
+
2774
+ def check_following(self, value):
2775
+ """Checks if the response contains the expected key sentences."""
2776
+ count = 0
2777
+ sentences = split_into_sentences(value)
2778
+ for sentence in self._key_sentences:
2779
+ if sentence in sentences:
2780
+ count += 1
2781
+
2782
+ return count == self._num_sentences
2783
+
2784
+
2785
+ class ForbiddenWords(Instruction):
2786
+ """Checks that specified words are not used in response."""
2787
+
2788
+ def build_description(self, forbidden_words=None):
2789
+ """Build the instruction description.
2790
+
2791
+ Args:
2792
+ forbidden_words: A sequences of strings respresenting words that are not
2793
+ allowed in the response.
2794
+
2795
+ Returns:
2796
+ A string representing the instruction description.
2797
+ """
2798
+
2799
+ if not forbidden_words:
2800
+ self._forbidden_words = generate_keywords(num_keywords=_NUM_KEYWORDS)
2801
+ else:
2802
+ self._forbidden_words = list(set(forbidden_words))
2803
+ self._forbidden_words = sorted(self._forbidden_words)
2804
+ self._description_pattern = "Do not include keywords {forbidden_words} in the response."
2805
+
2806
+ return self._description_pattern.format(forbidden_words=self._forbidden_words)
2807
+
2808
+ def get_instruction_args(self):
2809
+ """Returns the keyward args of `build_description`."""
2810
+ return {"forbidden_words": self._forbidden_words}
2811
+
2812
+ def get_instruction_args_keys(self):
2813
+ """Returns the args keys of `build_description`."""
2814
+ return ["forbidden_words"]
2815
+
2816
+ def check_following(self, value):
2817
+ """Check if the response does not contain the expected keywords."""
2818
+ for word in self._forbidden_words:
2819
+ if re.search(r"\b" + word + r"\b", value, flags=re.IGNORECASE):
2820
+ return False
2821
+ return True
2822
+
2823
+
2824
+ class RephraseParagraph(Instruction):
2825
+ """Checks that the paragraph is rephrased."""
2826
+
2827
+ def build_description(self, *, original_paragraph, low, high):
2828
+ """Builds the instruction description.
2829
+
2830
+ Args:
2831
+ original_paragraph: A string presenting the original paragraph. The
2832
+ rephrases response should have betweeb low-high words in common.
2833
+ low: An integer presenting the lower bound of similar words.
2834
+ high: An integer representing the upper bound of similar words.
2835
+
2836
+ Returns:
2837
+ A string representing the instruction description.
2838
+ """
2839
+ self._original_paragraph = original_paragraph
2840
+ self._low = low
2841
+ self._high = high
2842
+
2843
+ self._description = (
2844
+ "Rephrase the following paragraph: "
2845
+ + "{original_paragraph}\nYour response should have "
2846
+ + "between {low} and {high} of the same words. "
2847
+ + "Words are the same if and only if all of the "
2848
+ + "letters, ignoring cases, are the same. For "
2849
+ + "example, 'run' is the same as 'Run' but different "
2850
+ + "to 'ran'."
2851
+ )
2852
+
2853
+ return self._description.format(original_paragraph=original_paragraph, low=self._low, high=self._high)
2854
+
2855
+ def get_instruction_args(self):
2856
+ """Returns the keyward args of `build_description`."""
2857
+ return {
2858
+ "original_paragraph": self._original_paragraph,
2859
+ "low": self._low,
2860
+ "high": self._high,
2861
+ }
2862
+
2863
+ def get_instruction_args_keys(self):
2864
+ """Returns the args keys of `build_description`."""
2865
+ return ["original_paragraph", "low", "high"]
2866
+
2867
+ def check_following(self, value):
2868
+ val_words = re.findall(r"\w+", value.lower())
2869
+ original_words = re.findall(r"\w+", self._original_paragraph.lower())
2870
+ similar_words = 0
2871
+
2872
+ dict_val = collections.Counter(val_words)
2873
+ dict_original = collections.Counter(original_words)
2874
+
2875
+ for word in dict_original:
2876
+ similar_words += min(dict_original[word], dict_val[word])
2877
+
2878
+ return similar_words >= self._low and similar_words <= self._high
2879
+
2880
+
2881
+ class TwoResponsesChecker(Instruction):
2882
+ """Check that two responses were given."""
2883
+
2884
+ def build_description(self):
2885
+ """Build the instruction description."""
2886
+ self._description_pattern = (
2887
+ "Give two different responses. Responses and only responses should"
2888
+ " be separated by 6 asterisk symbols: ******."
2889
+ )
2890
+ return self._description_pattern
2891
+
2892
+ def get_instruction_args(self):
2893
+ """Returns the keyward args of `build_description`."""
2894
+ return None
2895
+
2896
+ def get_instruction_args_keys(self):
2897
+ """Returns the args keys of `build_description`."""
2898
+ return []
2899
+
2900
+ def check_following(self, value):
2901
+ """Checks if the response has two different answers.
2902
+
2903
+ Args:
2904
+ value: A string representing the response.
2905
+
2906
+ Returns:
2907
+ True if two responses are detected and false otherwise.
2908
+ """
2909
+ valid_responses = list()
2910
+ responses = value.split("******")
2911
+ for index, response in enumerate(responses):
2912
+ if not response.strip():
2913
+ if index != 0 and index != len(responses) - 1:
2914
+ return False
2915
+ else:
2916
+ valid_responses.append(response)
2917
+ return len(valid_responses) == 2 and valid_responses[0].strip() != valid_responses[1].strip()
2918
+
2919
+
2920
+ class RepeatPromptThenAnswer(Instruction):
2921
+ """Checks that Prompt is first repeated then answered."""
2922
+
2923
+ def build_description(self, *, prompt_to_repeat=None):
2924
+ """Build the instruction description.
2925
+
2926
+ Args:
2927
+ prompt_to_repeat: The prompt that is meant to be repeated.
2928
+
2929
+ Returns:
2930
+ A string representing the instruction description.
2931
+ """
2932
+ if not prompt_to_repeat:
2933
+ raise ValueError("prompt_to_repeat must be set.")
2934
+ else:
2935
+ self._prompt_to_repeat = prompt_to_repeat
2936
+ self._description_pattern = (
2937
+ "First repeat the request word for word without change,"
2938
+ " then give your answer (1. do not say any words or characters"
2939
+ " before repeating the request; 2. the request you need to repeat"
2940
+ " does not include this sentence)"
2941
+ )
2942
+ return self._description_pattern
2943
+
2944
+ def get_instruction_args(self):
2945
+ return {"prompt_to_repeat": self._prompt_to_repeat}
2946
+
2947
+ def get_instruction_args_keys(self):
2948
+ """Returns the args keys of `build_description`."""
2949
+ return ["prompt_to_repeat"]
2950
+
2951
+ def check_following(self, value):
2952
+ if value.strip().lower().startswith(self._prompt_to_repeat.strip().lower()):
2953
+ return True
2954
+ return False
2955
+
2956
+
2957
+ class EndChecker(Instruction):
2958
+ """Checks that the prompt ends with a given phrase."""
2959
+
2960
+ def build_description(self, *, end_phrase=None):
2961
+ """Build the instruction description.
2962
+
2963
+ Args:
2964
+ end_phrase: A string representing the phrase the response should end with.
2965
+
2966
+ Returns:
2967
+ A string representing the instruction description.
2968
+ """
2969
+ self._end_phrase = end_phrase.strip() if isinstance(end_phrase, str) else end_phrase
2970
+ if self._end_phrase is None:
2971
+ self._end_phrase = random.choice(_ENDING_OPTIONS)
2972
+ self._description_pattern = (
2973
+ "Finish your response with this exact phrase {ender}. No other words should follow this phrase."
2974
+ )
2975
+ return self._description_pattern.format(ender=self._end_phrase)
2976
+
2977
+ def get_instruction_args(self):
2978
+ return {"end_phrase": self._end_phrase}
2979
+
2980
+ def get_instruction_args_keys(self):
2981
+ """Returns the args keys of `build_description`."""
2982
+ return ["end_phrase"]
2983
+
2984
+ def check_following(self, value):
2985
+ """Checks if the response ends with the expected phrase."""
2986
+ value = value.strip().strip('"').lower()
2987
+ self._end_phrase = self._end_phrase.strip().lower()
2988
+ return value.endswith(self._end_phrase)
2989
+
2990
+
2991
+ class TitleChecker(Instruction):
2992
+ """Checks the response for a title."""
2993
+
2994
+ def build_description(self):
2995
+ """Build the instruction description."""
2996
+ self._description_pattern = (
2997
+ "Your answer must contain a title, wrapped in double angular brackets, such as <<poem of joy>>."
2998
+ )
2999
+ return self._description_pattern
3000
+
3001
+ def get_instruction_args(self):
3002
+ return None
3003
+
3004
+ def get_instruction_args_keys(self):
3005
+ """Returns the args keys of `build_description`."""
3006
+ return []
3007
+
3008
+ def check_following(self, value):
3009
+ """Checks if the response contains a title."""
3010
+ pattern = r"<<[^\n]+>>"
3011
+ re_pattern = re.compile(pattern)
3012
+ titles = re.findall(re_pattern, value)
3013
+
3014
+ for title in titles:
3015
+ if title.lstrip("<").rstrip(">").strip():
3016
+ return True
3017
+ return False
3018
+
3019
+
3020
+ class LetterFrequencyChecker(Instruction):
3021
+ """Checks letter frequency."""
3022
+
3023
+ def build_description(self, *, letter=None, let_frequency=None, let_relation=None):
3024
+ """Build the instruction description.
3025
+
3026
+ Args:
3027
+ letter: A string representing a letter that is expected in the response.
3028
+ let_frequency: An integer specifying the number of times `keyword` is
3029
+ expected to appear in the response.
3030
+ let_relation: A string in (`less than`, `at least`), defining the
3031
+ relational operator for comparison. Two relational comparisons are
3032
+ supported for now; if 'less than', the actual number of
3033
+ occurrences < frequency; if 'at least', the actual number of
3034
+ occurrences >= frequency.
3035
+
3036
+ Returns:
3037
+ A string representing the instruction description.
3038
+ """
3039
+ if not letter or len(letter) > 1 or ord(letter.lower()) < 97 or ord(letter.lower()) > 122:
3040
+ self._letter = random.choice(list(string.ascii_letters))
3041
+ else:
3042
+ self._letter = letter.strip()
3043
+ self._letter = self._letter.lower()
3044
+
3045
+ self._frequency = let_frequency
3046
+ if self._frequency is None or self._frequency < 0:
3047
+ self._frequency = random.randint(1, _LETTER_FREQUENCY)
3048
+
3049
+ if let_relation is None:
3050
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
3051
+ elif let_relation not in _COMPARISON_RELATION:
3052
+ raise ValueError(
3053
+ f"The supported relation for comparison must be in {_COMPARISON_RELATION}, but {let_relation} is given."
3054
+ )
3055
+ else:
3056
+ self._comparison_relation = let_relation
3057
+
3058
+ self._description_pattern = (
3059
+ "In your response, the letter {letter} should appear {let_relation} {let_frequency} times."
3060
+ )
3061
+
3062
+ return self._description_pattern.format(
3063
+ letter=self._letter,
3064
+ let_frequency=self._frequency,
3065
+ let_relation=self._comparison_relation,
3066
+ )
3067
+
3068
+ def get_instruction_args(self):
3069
+ """Returns the keyword args of build description."""
3070
+ return {
3071
+ "letter": self._letter,
3072
+ "let_frequency": self._frequency,
3073
+ "let_relation": self._comparison_relation,
3074
+ }
3075
+
3076
+ def get_instruction_args_keys(self):
3077
+ """Returns the args keys of `build_description`."""
3078
+ return ["letter", "let_frequency", "let_relation"]
3079
+
3080
+ def check_following(self, value):
3081
+ """Checks that the response contains the letter at the right frequency."""
3082
+ value = value.lower()
3083
+ letters = collections.Counter(value)
3084
+
3085
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
3086
+ return letters[self._letter] < self._frequency
3087
+ else:
3088
+ return letters[self._letter] >= self._frequency
3089
+
3090
+
3091
+ class CapitalLettersEnglishChecker(Instruction):
3092
+ """Checks that the response is in english and is in all capital letters."""
3093
+
3094
+ def build_description(self):
3095
+ """Build the instruction description."""
3096
+ self._description_pattern = "Your entire response should be in English, and in all capital letters."
3097
+ return self._description_pattern
3098
+
3099
+ def get_instruction_args(self):
3100
+ return None
3101
+
3102
+ def get_instruction_args_keys(self):
3103
+ """Returns the args keys of `build_description`."""
3104
+ return []
3105
+
3106
+ def check_following(self, value):
3107
+ """Checks that the response is in English and in all capital letters."""
3108
+ assert isinstance(value, str)
3109
+
3110
+ try:
3111
+ return value.isupper() and langdetect.detect(value) == "en"
3112
+ except langdetect.LangDetectException as e:
3113
+ # Count as instruction is followed.
3114
+ logger.info("Unable to detect language for text %s due to %s", value, e) # refex: disable=pytotw.037
3115
+ return True
3116
+
3117
+
3118
+ class LowercaseLettersEnglishChecker(Instruction):
3119
+ """Checks that the response is in english and is in all lowercase letters."""
3120
+
3121
+ def build_description(self):
3122
+ """Build the instruction description."""
3123
+ self._description_pattern = (
3124
+ "Your entire response should be in English, and in all lowercase letters. No capital letters are allowed."
3125
+ )
3126
+ return self._description_pattern
3127
+
3128
+ def get_instruction_args(self):
3129
+ return None
3130
+
3131
+ def get_instruction_args_keys(self):
3132
+ """Returns the args keys of `build_description`."""
3133
+ return []
3134
+
3135
+ def check_following(self, value):
3136
+ """Checks that the response is in English and in all lowercase letters."""
3137
+ assert isinstance(value, str)
3138
+
3139
+ try:
3140
+ return value.islower() and langdetect.detect(value) == "en"
3141
+ except langdetect.LangDetectException as e:
3142
+ # Count as instruction is followed.
3143
+ logger.info("Unable to detect language for text %s due to %s", value, e) # refex: disable=pytotw.037
3144
+ return True
3145
+
3146
+
3147
+ class CommaChecker(Instruction):
3148
+ """Checks the response for no commas."""
3149
+
3150
+ def build_description(self, **kwargs):
3151
+ """Build the instruction description."""
3152
+ self._description_pattern = "In your entire response, refrain from the use of any commas."
3153
+ return self._description_pattern
3154
+
3155
+ def get_instruction_args(self):
3156
+ return None
3157
+
3158
+ def get_instruction_args_keys(self):
3159
+ """Returns the args keys of `build_description`."""
3160
+ return []
3161
+
3162
+ def check_following(self, value):
3163
+ """Checks that the response does not contain commas."""
3164
+ return not re.search(r"\,", value)
3165
+
3166
+
3167
+ class CapitalWordFrequencyChecker(Instruction):
3168
+ """Checks frequency of words with all capital letters."""
3169
+
3170
+ def build_description(
3171
+ self,
3172
+ capital_frequency=None,
3173
+ capital_relation=None,
3174
+ ):
3175
+ """Build the instruction description.
3176
+
3177
+ Args:
3178
+ capital_frequency: An integer that represents the number of words that
3179
+ should be in all capital letters.
3180
+ capital_relation: A string that is 'at least' or 'at most' that refers to
3181
+ the frequency.
3182
+
3183
+ Returns:
3184
+ A string representing the instruction description.
3185
+ """
3186
+ self._frequency = capital_frequency
3187
+ if self._frequency is None:
3188
+ self._frequency = random.randint(1, _ALL_CAPITAL_WORD_FREQUENCY)
3189
+
3190
+ self._comparison_relation = capital_relation
3191
+ if capital_relation is None:
3192
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
3193
+ elif capital_relation not in _COMPARISON_RELATION:
3194
+ raise ValueError(
3195
+ "The supported relation for comparison must be in "
3196
+ f"{_COMPARISON_RELATION}, but {capital_relation} is given."
3197
+ )
3198
+
3199
+ self._description_pattern = (
3200
+ "In your response, words with all capital letters should appear {relation} {frequency} times."
3201
+ )
3202
+
3203
+ return self._description_pattern.format(frequency=self._frequency, relation=self._comparison_relation)
3204
+
3205
+ def get_instruction_args(self):
3206
+ """Returns the keyword args of build description."""
3207
+ return {
3208
+ "capital_frequency": self._frequency,
3209
+ "capital_relation": self._comparison_relation,
3210
+ }
3211
+
3212
+ def get_instruction_args_keys(self):
3213
+ """Returns the args keys of `build_description`."""
3214
+ return ["capital_frequency", "capital_relation"]
3215
+
3216
+ def check_following(self, value):
3217
+ """Checks the frequency of words with all capital letters."""
3218
+ # Hyphenated words will count as one word
3219
+ nltk.download("punkt_tab")
3220
+ words = nltk.word_tokenize(value)
3221
+ capital_words = [word for word in words if word.isupper()]
3222
+
3223
+ capital_words = len(capital_words)
3224
+
3225
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
3226
+ return capital_words < self._frequency
3227
+ else:
3228
+ return capital_words >= self._frequency
3229
+
3230
+
3231
+ class QuotationChecker(Instruction):
3232
+ """Checks response is wrapped with double quotation marks."""
3233
+
3234
+ def build_description(self):
3235
+ """Build the instruction description."""
3236
+ self._description_pattern = "Wrap your entire response with double quotation marks."
3237
+ return self._description_pattern
3238
+
3239
+ def get_instruction_args(self):
3240
+ """Returns the keyword args of build description."""
3241
+ return None
3242
+
3243
+ def get_instruction_args_keys(self):
3244
+ """Returns the args keys of `build_description`."""
3245
+ return []
3246
+
3247
+ def check_following(self, value):
3248
+ """Checks if the response is wrapped with double quotation marks."""
3249
+ quotations_map = {
3250
+ "ja": "「」",
3251
+ "ru": "«»",
3252
+ "th": "“”",
3253
+ "zh": "“”",
3254
+ "zh-cn": "“”",
3255
+ "zh-tw": "“”",
3256
+ }
3257
+ value = value.strip()
3258
+ lang = get_langid(value)
3259
+ quotes = quotations_map.get(lang, '""')
3260
+ # TODO: We may wanna revisit this logic in new generations to only check of the response language's quotes.
3261
+ return len(value) > 1 and value[0] in [quotes[0], '"'] and value[-1] in [quotes[1], '"']
3262
+
3263
+
3264
+ # Define instruction dicts
3265
+ _KEYWORD = "keywords:"
3266
+ _LANGUAGE = "language:"
3267
+ _LENGTH = "length_constraints:"
3268
+ _CONTENT = "detectable_content:"
3269
+ _FORMAT = "detectable_format:"
3270
+ _MULTITURN = "multi-turn:"
3271
+ _COMBINATION = "combination:"
3272
+ _STARTEND = "startend:"
3273
+ _CHANGE_CASES = "change_case:"
3274
+ _PUNCTUATION = "punctuation:"
3275
+
3276
+ INSTRUCTION_DICT = {
3277
+ _KEYWORD + "existence": KeywordChecker,
3278
+ _KEYWORD + "frequency": KeywordFrequencyChecker,
3279
+ # _KEYWORD + "key_sentences": KeySentenceChecker,
3280
+ _KEYWORD + "forbidden_words": ForbiddenWords,
3281
+ _KEYWORD + "letter_frequency": LetterFrequencyChecker,
3282
+ _LANGUAGE + "response_language": ResponseLanguageChecker,
3283
+ _LENGTH + "number_sentences": NumberOfSentences,
3284
+ _LENGTH + "number_paragraphs": ParagraphChecker,
3285
+ _LENGTH + "number_words": NumberOfWords,
3286
+ _LENGTH + "nth_paragraph_first_word": ParagraphFirstWordCheck,
3287
+ _CONTENT + "number_placeholders": PlaceholderChecker,
3288
+ _CONTENT + "postscript": PostscriptChecker,
3289
+ _FORMAT + "number_bullet_lists": BulletListChecker,
3290
+ # _CONTENT + "rephrase_paragraph": RephraseParagraph,
3291
+ _FORMAT + "constrained_response": ConstrainedResponseChecker,
3292
+ _FORMAT + "number_highlighted_sections": (HighlightSectionChecker),
3293
+ _FORMAT + "multiple_sections": SectionChecker,
3294
+ # _FORMAT + "rephrase": RephraseChecker,
3295
+ _FORMAT + "json_format": JsonFormat,
3296
+ _FORMAT + "title": TitleChecker,
3297
+ # _MULTITURN + "constrained_start": ConstrainedStartChecker,
3298
+ _COMBINATION + "two_responses": TwoResponsesChecker,
3299
+ _COMBINATION + "repeat_prompt": RepeatPromptThenAnswer,
3300
+ _STARTEND + "end_checker": EndChecker,
3301
+ _CHANGE_CASES + "capital_word_frequency": CapitalWordFrequencyChecker,
3302
+ _CHANGE_CASES + "english_capital": CapitalLettersEnglishChecker,
3303
+ _CHANGE_CASES + "english_lowercase": LowercaseLettersEnglishChecker,
3304
+ _PUNCTUATION + "no_comma": CommaChecker,
3305
+ _STARTEND + "quotation": QuotationChecker,
3306
+ }
3307
+
3308
+ INSTRUCTION_LIST = list(INSTRUCTION_DICT.keys()) + [
3309
+ _KEYWORD[:-1],
3310
+ _LANGUAGE[:-1],
3311
+ _LENGTH[:-1],
3312
+ _CONTENT[:-1],
3313
+ _FORMAT[:-1],
3314
+ _MULTITURN[:-1],
3315
+ _COMBINATION[:-1],
3316
+ _STARTEND[:-1],
3317
+ _CHANGE_CASES[:-1],
3318
+ _PUNCTUATION[:-1],
3319
+ ]