├── LICENSE ├── README.md ├── benchmark_query ├── benchmark_all.jsonl └── requirement │ ├── format │ ├── format_subset.jsonl │ └── format_subset_C.jsonl │ ├── length │ ├── length_subset.jsonl │ └── length_subset_C.jsonl │ └── style │ ├── style_subset.jsonl │ └── style_subset_C.jsonl ├── evaluate_benchmark.py ├── evaluator ├── __init__.py ├── critic.py └── llm.py ├── pics ├── construction.png └── criteria.png └── prompt.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WritingBench: A Comprehensive Benchmark for Generative Writing 2 |

3 | 📃 [Paper] • 🚀 [Github Repo] • 🏆 [Leaderboard] • 📏 [Critic Model] • ✍️ [Writing Model] 4 |

5 | 6 |
7 | Benchmark Construction Pipeline 10 |
11 | 12 | ## 🚀 What's New 13 | 14 | #### ```2025-04-29``` 15 | - **🏆 Leaderboard Launch**: Explore evaluation results on [Hugging Face Leaderboard](https://huggingface.co/spaces/WritingBench/WritingBench) and [ModelScope Leaderboard](https://modelscope.cn/studios/WritingBench/WritingBench). Update latest LLM evaluations (Claude-3-7-Sonnet, o3, grok-3, etc) 16 | - Parameters for response generation: `top_p: 0.8`; `top_k: 20`; `temperature: 0.7`; `max_length: 16000` (or maximum allowed if less than 16000) 17 | - Parameters for scoring: `top_p: 0.95`; `top_k: (empty)`; `temperature: 1.0`; `max_length: 2048` 18 | - Leaderboard scores are scaled from 10 to 100 by multiplying by 10 for easier viewing. 19 | - ‼️ Update [benchmark queries & criteria](https://github.com/X-PLUG/WritingBench/blob/main/benchmark_query/benchmark_all.jsonl) for improved assessment, including **1,000** queries and requirement dimension subsets. 20 | - ‼️ Update [evaluation prompt](https://github.com/X-PLUG/WritingBench/blob/main/prompt.py) for better scoring, and switch to using **Claude-3-7-Sonnet** for evaluation. 21 | 22 | #### ```2025-03-10``` 23 | - We release the first version of WritingBench, including **1,239** writing queries and style/format/length dimension subsets. 24 | 25 | ## 📖 Overview 26 | WritingBench is a comprehensive benchmark for evaluating LLMs' writing capabilities across **1,000 real-world queries**, spanning: 27 | - 6 primary domains 28 | - 100 fine-grained subdomains 29 | - 1,500+ avg. tokens per query 30 | 31 | WritingBench integrates diverse sources of materials. Each query is paired with **5 instance-specific criteria**, scoring either through LLM evaluators or through a finetuned critic model. 32 | 33 | 34 | ## 🏗️ Benchmark Construction 35 | 36 | WritingBench is built through a hybrid pipeline combining **Model-Augmented Query Generation** and **Human-in-the-Loop Refinement**, ensuring both diversity and real-world applicability. The construction process involves two key phases: 37 | 38 | ### 🤖 Model-Augmented Query Generation 39 | 40 | #### Phase 1: Initial Query Generation 41 | Leverage LLMs to generate queries from a two-tiered domain pool grounded in real-world writing scenarios, consisting of 6 primary domains and 100 secondary subdomains, covering: 42 | - 🔬 Academic & Engineering 43 | - 💼 Finance & Business 44 | - ⚖️ Politics & Law 45 | - 🎨 Literature & Art 46 | - 🎓 Education 47 | - 📢 Advertising & Marketing 48 | 49 | #### Phase 2: Query Diversification 50 | Enhance the diversity and practical applicability of queries by random selected strategies from **Query Refinement Guidance Pool**, covering: 51 | - Style Adjustments (e.g., kid-friendly tone) 52 | - Format Specifications (e.g., IEEE template) 53 | - Length Constraints (e.g., 500-word summary) 54 | - Personalization (e.g., educator's perspective) 55 | - Content Specificity (e.g., 2023 Q3 metrics) 56 | - Expression Optimization (query rewriting) 57 | 58 | ### ✍️ Human-in-the-Loop Refinement 59 | 60 | #### Phase 1: Material Collection 61 | 30 trained annotators collect necessary open-source materials (e.g., public financial statements or legal templates), guided by material requirements generated by LLMs. 62 | 63 | #### Phase 2: Expert Screening & Optimization 64 | 5 experts conduct a delicate two-stage filtering process: 65 | - query adaptation: ambiguous or unrealistic queries are revised to better align with the provided materials and practical scenarios 66 | - material pruning: redundant or irrelevant content is eliminated from the collected materials 67 | 68 | ## 📈 Evaluation Framework 69 | 70 |
71 | Instance-Specific Criteria 72 |
73 | 74 | ### Phase 1: Dynamic Criteria Generation 75 | Given a query $q$ in the WritingBench, the LLM is prompted to automatically generate a set of five evaluation criteria, $C_q = \{c_1, \ldots, c_5\}$. Each criterion comprises three components: a concise name summarizing the criterion, an extended description elaborating on the evaluation focus, and detailed scoring rubrics. 76 | 77 | ### Phase 2: Rubric-based Scoring 78 | For each criterion $c_i \in C_q$, the evaluator independently assigns a score on a 10-point scale to a response $r$, providing both a score and a justification. 79 | 80 | 81 | ## 🛠 Installation 82 | ```bash 83 | git clone https://github.com/X-PLUG/WritingBench.git 84 | ``` 85 | 86 | ## 📂 Repository Structure 87 | ```bash 88 | . 89 | ├── evaluate_benchmark.py # Evaluation script 90 | ├── prompt.py # Prompt templates 91 | ├── evaluator/ 92 | │ ├── __int__.py 93 | │ ├── critic.py # Critic model evaluation interface 94 | │ └── llm.py # LLM evaluation interface 95 | └── benchmark_query/ 96 | ├── benchmark_all.jsonl # Full dataset (1,000 queries) 97 | └── requirement/ 98 | ├── style/ 99 | │ ├── style_subset.jsonl # requirement-involved subset for style 100 | │ └── style_subset_C.jsonl # category-specific subset for style 101 | ├── format/ 102 | │ ├── format_subset.jsonl # requirement-involved subset for format 103 | │ └── format_subset_C.jsonl # category-specific subset for format 104 | └── length/ 105 | ├── length_subset.jsonl # requirement-involved subset for length 106 | └── length_subset_C.jsonl # category-specific subset for length 107 | ``` 108 | 109 | ## 🚀 Quick Start 110 | 111 | 1. Add your API credentials: 112 | - For LLM-as-a-Judge, see `evaluator/llm.py`. Recommend using `Claude-3-7-Sonnet` for evaluation. 113 | ```bash 114 | self.api_key = "your_api_key_here" 115 | self.url = "Your API endpoint" 116 | self.model = "Chose your model name" 117 | ``` 118 | - For critic model, see `evaluator/critic.py` 119 | ```bash 120 | self.model = LLM( 121 | model="", # Your local path. Please download critic model from https://huggingface.co/AQuarterMile/WritingBench-Critic-Model-Qwen-7B. 122 | tensor_parallel_size=1, # Your tensor parallel size setting. Defaults to 1, indicating no parallelism 123 | ) 124 | ``` 125 | 2. Choose appropriate evaluation sets from `benchmark_query/` 126 | ```bash 127 | python evaluate_benchmark.py \ 128 | --evaluator critic \ # or claude 129 | --query_criteria_file query_set.jsonl \ # use files under benchmark_query/ 130 | --input_file samples.jsonl \ 131 | --output_file scores.jsonl 132 | ``` 133 | 134 | An example of `samples.jsonl` used to store responses generated by the evaluated LLMs: 135 | ```bash 136 | {"index": i, "response": "xxx"} 137 | ``` 138 | 139 | ## 📝 Citation 140 | 141 | ``` 142 | @misc{wu2025writingbench, 143 | title={WritingBench: A Comprehensive Benchmark for Generative Writing}, 144 | author={Yuning Wu and Jiahao Mei and Ming Yan and Chenliang Li and Shaopeng Lai and Yuran Ren and Zijia Wang and Ji Zhang and Mengyue Wu and Qin Jin and Fei Huang}, 145 | year={2025}, 146 | url={https://arxiv.org/abs/2503.05244}, 147 | } 148 | ``` 149 | -------------------------------------------------------------------------------- /evaluate_benchmark.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import argparse 4 | import jsonlines 5 | from tqdm import tqdm 6 | from prompt import evaluate_system, evaluate_prompt 7 | from evaluator import ClaudeAgent, CriticAgent 8 | 9 | EVAL_TIMES = 1 10 | 11 | class EvalAgent(object): 12 | def __init__(self, agent): 13 | self.agent = agent 14 | 15 | def success_check_fn_score(self, response): 16 | try: 17 | result = json.loads(response.strip('json|```')) 18 | except json.JSONDecodeError as e: 19 | print("JSON decode error:", e) 20 | return False 21 | 22 | valid_score_values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 23 | 24 | if "score" not in result or "reason" not in result: 25 | print("Missing 'score' or 'reason' in the result") 26 | return False 27 | if result["score"] not in valid_score_values: 28 | return False 29 | if not isinstance(result["reason"], str): 30 | return False 31 | return True 32 | 33 | 34 | def generate_score(self, content, query, criteria): 35 | prompt_data = { 36 | "query": query, 37 | "response": content["response"], 38 | "criteria": criteria, 39 | } 40 | retry = 0 41 | success = False 42 | while not success and retry < 3: 43 | prompt = evaluate_prompt.format(**prompt_data) 44 | response, success = self.agent.run( 45 | prompt=prompt, 46 | success_check_fn=self.success_check_fn_score 47 | ) 48 | try: 49 | response = json.loads(response.strip('json|```')) 50 | except json.JSONDecodeError as e: 51 | print("JSON decode error:", e) 52 | response = eval(response.strip('json|```')) 53 | retry += 1 54 | if success: 55 | return response 56 | else: 57 | raise ValueError("Fail to generate score!") 58 | 59 | def save_output(output, file_name): 60 | """ 61 | Saves output data to a specified file in JSONL format. 62 | """ 63 | with open(file_name, 'a', encoding='utf-8') as f: 64 | for record in output: 65 | f.write(json.dumps(record, ensure_ascii=False) + '\n') 66 | 67 | def load_file(file_name): 68 | """ 69 | Loads JSONL lines from a file into a list of dictionaries. 70 | """ 71 | if os.path.isfile(file_name): 72 | with open(file_name, 'r', encoding='utf-8') as f: 73 | records = [json.loads(line) for line in f] 74 | return records, len(records) 75 | return [], 0 76 | 77 | def load_query_criteria(jsonl_file_path): 78 | """ 79 | Loads criteria from a JSONL file into a dictionary. 80 | """ 81 | data_list = {} 82 | with jsonlines.open(jsonl_file_path) as reader: 83 | for obj in reader: 84 | data_list[obj['index']] = {} 85 | data_list[obj['index']]['query'] = obj['query'] 86 | data_list[obj['index']]['criteria'] = obj['checklist'] 87 | return data_list 88 | 89 | def process(agent, input_file, out_file, id_query_criteria_map): 90 | """ 91 | Processes input files through the evaluation agent, producing scores and saving results. 92 | """ 93 | records, existing_count = load_file(out_file) 94 | cnt = existing_count 95 | contents, input_cnt = load_file(input_file) 96 | with tqdm(total=input_cnt, initial=0, desc=f"Processing {input_file.split('/')[-1]}") as pbar: 97 | for i, content in enumerate(contents): 98 | if existing_count > 0 and i < existing_count - 1: 99 | pbar.update() 100 | continue 101 | 102 | data = { 103 | "index": content["index"], 104 | "scores": {} 105 | } 106 | 107 | query = id_query_criteria_map[content["index"]]['query'] 108 | criteria = id_query_criteria_map[content["index"]]['criteria'] 109 | 110 | with tqdm(total=len(criteria) * EVAL_TIMES, desc=f"Data ID {content['index']} Progress", leave=False) as internal_pbar: 111 | for c in criteria: 112 | if c["name"] not in criteria: 113 | data["scores"][c["name"]] = [] 114 | while len(data["scores"][c["name"]]) < EVAL_TIMES: 115 | score = agent.generate_score(content, query, c) 116 | data["scores"][c["name"]].append(score) 117 | internal_pbar.update(1) 118 | 119 | save_output([data], out_file) 120 | cnt += 1 121 | pbar.update() 122 | 123 | print(f"CNT: {cnt}") 124 | 125 | return 126 | 127 | if __name__ == "__main__": 128 | 129 | parser = argparse.ArgumentParser(description="Process lines from an input file.") 130 | parser.add_argument("--evaluator", choices=['claude', 'critic'], required=True, help="Choose the scoring model to use: 'claude' or 'critic'.") 131 | parser.add_argument("--query_criteria_file", type=str, help="Path to the query and criteria file.") 132 | parser.add_argument("--input_file", type=str, help="Path to the input file.") 133 | parser.add_argument("--output_file", type=str, help="Path to the output file.") 134 | 135 | args = parser.parse_args() 136 | 137 | # Evaluator initialization based on chosen model 138 | if args.evaluator == 'claude': 139 | agent = EvalAgent(ClaudeAgent( 140 | system_prompt=evaluate_system, 141 | )) 142 | else: 143 | agent = EvalAgent(CriticAgent( 144 | system_prompt=evaluate_system, 145 | )) 146 | 147 | id_query_criteria_map = load_query_criteria(args.query_criteria_file) 148 | 149 | process(agent, args.input_file, args.output_file, id_query_criteria_map) 150 | -------------------------------------------------------------------------------- /evaluator/__init__.py: -------------------------------------------------------------------------------- 1 | from .llm import ClaudeAgent 2 | from .critic import CriticAgent -------------------------------------------------------------------------------- /evaluator/critic.py: -------------------------------------------------------------------------------- 1 | import time 2 | from typing import Callable 3 | from vllm import LLM, SamplingParams 4 | 5 | class CriticAgent(object): 6 | def __init__(self, 7 | system_prompt: str = None): 8 | self.system_prompt = system_prompt 9 | self.model = LLM( 10 | model="", # Your local path. Please download critic model from https://huggingface.co/AQuarterMile/WritingBench-Critic-Model-Qwen-7B. 11 | tensor_parallel_size=1, # Your tensor parallel size setting. Defaults to 1, indicating no parallelism 12 | ) 13 | 14 | def call_critic(self, 15 | messages: str, 16 | top_p: float = 0.95, 17 | temperature: float = 1.0, 18 | max_length: int = 2048): 19 | 20 | sampling_params = SamplingParams( 21 | temperature=temperature, 22 | top_p=top_p, 23 | max_tokens=int(max_length) 24 | ) 25 | 26 | attempt = 0 27 | max_attempts = 5 28 | wait_time = 1 29 | 30 | while attempt < max_attempts: 31 | try: 32 | response = self.model.chat(messages, sampling_params) 33 | return response[0].outputs[0].text 34 | 35 | except Exception as e: 36 | print(f"Attempt {attempt+1}: VLLM call failed due to error: {e}, retrying...") 37 | 38 | time.sleep(wait_time) 39 | attempt += 1 40 | 41 | raise Exception("Max attempts exceeded. Failed to get a successful response.") 42 | 43 | def basic_success_check(self, response): 44 | if not response: 45 | print(response) 46 | return False 47 | else: 48 | return True 49 | 50 | def run(self, 51 | prompt: str, 52 | top_p: float = 0.95, 53 | temperature: float = 1.0, 54 | max_length: int = 2048, 55 | max_try: int = 5, 56 | success_check_fn: Callable = None): 57 | 58 | messages = [ 59 | {"role": "system", "content": self.system_prompt}, 60 | {"role": "user","content": prompt} 61 | ] 62 | success = False 63 | try_times = 0 64 | 65 | while try_times < max_try: 66 | response = self.call_critic( 67 | messages=messages, 68 | top_p=top_p, 69 | temperature=temperature, 70 | max_length=max_length, 71 | ) 72 | 73 | if success_check_fn is None: 74 | success_check_fn = lambda x: True 75 | 76 | if success_check_fn(response): 77 | success = True 78 | break 79 | else: 80 | try_times += 1 81 | 82 | return response, success 83 | -------------------------------------------------------------------------------- /evaluator/llm.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | from typing import Callable 4 | 5 | 6 | class ClaudeAgent(object): 7 | def __init__(self, 8 | system_prompt: str = None): 9 | self.system_prompt = system_prompt 10 | self.api_key = '' # Yor API KEY 11 | self.url = '' # Your URL path 12 | self.model = '' # Model name 13 | 14 | def call_claude(self, 15 | messages: str, 16 | top_p: float = 0.95, 17 | temperature: float = 1.0, 18 | max_length: int = 2048): 19 | headers = { 20 | "Authorization": f"Bearer {self.api_key}", 21 | "Content-Type": "application/json" 22 | } 23 | 24 | data = { 25 | "model": f"{self.model}", 26 | "messages": messages, 27 | "max_tokens": max_length, 28 | "top_p": top_p, 29 | "temperature": temperature 30 | } 31 | 32 | attempt = 0 33 | max_attempts = 5 34 | wait_time = 1 35 | 36 | while attempt < max_attempts: 37 | try: 38 | response = requests.post(self.url, headers=headers, json=data) 39 | 40 | if response.status_code == 200: 41 | return response.json()["choices"][0]["message"]["content"] 42 | else: 43 | print(f"Attempt {attempt+1}: Failed with status {response.status_code}, retrying...") 44 | 45 | except requests.exceptions.RequestException as e: 46 | print(f"Attempt {attempt+1}: Request failed due to network error: {e}, retrying...") 47 | 48 | time.sleep(wait_time) 49 | attempt += 1 50 | 51 | raise Exception("Max attempts exceeded. Failed to get a successful response.") 52 | 53 | def basic_success_check(self, response): 54 | if not response: 55 | print(response) 56 | return False 57 | else: 58 | return True 59 | 60 | def run(self, 61 | prompt: str, 62 | top_p: float = 0.95, 63 | temperature: float = 1.0, 64 | max_length: int = 2048, 65 | max_try: int = 5, 66 | success_check_fn: Callable = None): 67 | 68 | messages = [ 69 | {"role": "system", "content": self.system_prompt}, 70 | {"role": "user","content": prompt} 71 | ] 72 | success = False 73 | try_times = 0 74 | 75 | while try_times < max_try: 76 | response = self.call_claude( 77 | messages=messages, 78 | top_p=top_p, 79 | temperature=temperature, 80 | max_length=max_length, 81 | ) 82 | 83 | if success_check_fn is None: 84 | success_check_fn = lambda x: True 85 | 86 | if success_check_fn(response): 87 | success = True 88 | break 89 | else: 90 | try_times += 1 91 | 92 | return response, success 93 | -------------------------------------------------------------------------------- /pics/construction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/X-PLUG/WritingBench/cf736a8c32773a790006c55d08721f2a41047ba4/pics/construction.png -------------------------------------------------------------------------------- /pics/criteria.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/X-PLUG/WritingBench/cf736a8c32773a790006c55d08721f2a41047ba4/pics/criteria.png -------------------------------------------------------------------------------- /prompt.py: -------------------------------------------------------------------------------- 1 | evaluate_system = """ 2 | You are an expert evaluator with extensive experience in evaluating response of given query. 3 | """.strip() 4 | 5 | evaluate_prompt = """ 6 | Evaluate the Response based on the Query and Criteria provided following the Scoring Rules. 7 | 8 | ** Scoring Rules ** 9 | 10 | "1-2": "Low score description: Critical deficiencies and major issues that prevent adequate functionality.", 11 | "3-4": "Below average score description: Lacking with noticeable shortcomings that impact overall effectiveness and require improvement.", 12 | "5-6": "Average score description: Adequate but not exemplary, Baseline performance that meets essential requirements. Most models may achieve this score.", 13 | "7-8": "Above average score description: Strong performance characterized by competent execution, though minor refinements are needed to achieve excellence.", 14 | "9-10": "High score description: Exceptional performance with all aspects optimally addressed, demonstrating superior effectiveness and quality without any flaws." 15 | 16 | -Provide reasons for each score by indicating specific strengths or deficiencies within the Response. Reference exact text passages to justify the score, ensuring that each reason is concrete and aligns with the criteria requirements while highlighting key gaps from the ideal answer. 17 | 18 | -Be very STRICT and do not be misled by format or length; ensure that the Response is thoroughly evaluated beyond superficial appearances. 19 | 20 | -Carefully discern whether the content of the Response is an illusion, appearing substantial but actually entirely fabricated. 21 | 22 | -Sometimes the model may only provide an introduction or an overview without truly completing the query, which should be considered a failed response. Carefully discern this. 23 | 24 | -Scoring Range: Assign an integer score between 1 to 10 25 | 26 | ** Output format ** 27 | (Remove symbols that interfere with JSON parsing, don't use " inside reason) 28 | Return the results in the following JSON format, Only output the following JSON format and nothing else: 29 | ```json 30 | {{ 31 | "score": an integer score between 1 to 10, 32 | "reason": "Specific and detailed justification for the score using text elements." 33 | }} 34 | 35 | ** Criteria ** 36 | ```{criteria}``` 37 | 38 | ** Query ** 39 | ```{query}``` 40 | 41 | ** Response ** 42 | ```{response}``` 43 | 44 | Provide your evaluation based on the criteria restated below: 45 | 46 | ```{criteria}``` 47 | 48 | ** Output format ** 49 | (Remove symbols that interfere with JSON parsing, don't use " inside reason) 50 | Return the results in the following JSON format, Only output the following JSON format and nothing else: 51 | ```json 52 | {{ 53 | "score": an integer score between 1 to 10, 54 | "reason": "Specific and detailed justification for the score using text elements." 55 | }} 56 | ``` 57 | """.strip() 58 | --------------------------------------------------------------------------------