Task Gallery¶
This section contains the existing Task
subclasses implemented in distilabel
.
tasks
¶
APIGenExecutionChecker
¶
Bases: Step
Executes the generated function calls.
This step checks if a given answer from a model as generated by APIGenGenerator
can be executed against the given library (given by libpath
, which is a string
pointing to a python .py file with functions).
Attributes:
Name | Type | Description |
---|---|---|
libpath |
str
|
The path to the library where we will retrieve the functions. It can also point to a folder with the functions. In this case, the folder layout should be a folder with .py files, each containing a single function, the name of the function being the same as the filename. |
check_is_dangerous |
bool
|
Bool to exclude some potentially dangerous functions, it contains some heuristics found while testing. This functions can run subprocesses, deal with the OS, or have other potentially dangerous operations. Defaults to True. |
Input columns
- answers (
str
): List with arguments to be passed to the function, dumped as a string from a list of dictionaries. Should be loaded usingjson.loads
.
Output columns
- keep_row_after_execution_check (
bool
): Whether the function should be kept or not. - execution_result (
str
): The result from executing the function.
Categories
- filtering
- execution
References
Examples:
Execute a function from a given library with the answer from an LLM:
from distilabel.steps.tasks import APIGenExecutionChecker
# For the libpath you can use as an example the file at the tests folder:
# ../distilabel/tests/unit/steps/tasks/apigen/_sample_module.py
task = APIGenExecutionChecker(
libpath="../distilabel/tests/unit/steps/tasks/apigen/_sample_module.py",
)
task.load()
res = next(
task.process(
[
{
"answers": [
{
"arguments": {
"initial_velocity": 0.2,
"acceleration": 0.1,
"time": 0.5,
},
"name": "final_velocity",
}
],
}
]
)
)
res
#[{'answers': [{'arguments': {'initial_velocity': 0.2, 'acceleration': 0.1, 'time': 0.5}, 'name': 'final_velocity'}], 'keep_row_after_execution_check': True, 'execution_result': ['0.25']}]
Source code in src/distilabel/steps/tasks/apigen/execution_checker.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
|
inputs: StepColumns
property
¶
The inputs for the task are those found in the original dataset.
outputs: StepColumns
property
¶
The outputs are the columns required by APIGenGenerator
task.
load()
¶
Loads the library where the functions will be extracted from.
_get_function(function_name)
¶
Retrieves the function from the toolbox.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
function_name
|
str
|
The name of the function to retrieve. |
required |
Returns:
Name | Type | Description |
---|---|---|
Callable |
Callable
|
The function to be executed. |
Source code in src/distilabel/steps/tasks/apigen/execution_checker.py
_is_dangerous(function)
¶
Checks if a function is dangerous to remove it. Contains a list of heuristics to avoid executing possibly dangerous functions.
Source code in src/distilabel/steps/tasks/apigen/execution_checker.py
process(inputs)
¶
Checks the answer to see if it can be executed. Captures the possible errors and returns them.
If a single example is provided, it is copied to avoid raising an error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
inputs
|
StepInput
|
A list of dictionaries with the input data. |
required |
Yields:
Type | Description |
---|---|
StepOutput
|
A list of dictionaries with the output data. |
Source code in src/distilabel/steps/tasks/apigen/execution_checker.py
APIGenGenerator
¶
Bases: Task
Generate queries and answers for the given functions in JSON format.
The `APIGenGenerator` is inspired by the APIGen pipeline, which was designed to generate
verifiable and diverse function-calling datasets. The task generates a set of diverse queries
and corresponding answers for the given functions in JSON format.
Attributes:
system_prompt: The system prompt to guide the user in the generation of queries and answers.
use_tools: Whether to use the tools available in the prompt to generate the queries and answers.
In case the tools are given in the input, they will be added to the prompt.
number: The number of queries to generate. It can be a list, where each number will be
chosen randomly, or a dictionary with the number of queries and the probability of each.
I.e: `number=1`, `number=[1, 2, 3]`, `number={1: 0.5, 2: 0.3, 3: 0.2}` are all valid inputs.
It corresponds to the number of parallel queries to generate.
use_default_structured_output: Whether to use the default structured output or not.
Input columns:
- examples (`str`): Examples used as few shots to guide the model.
- func_name (`str`): Name for the function to generate.
- func_desc (`str`): Description of what the function should do.
- tools (`str`): JSON formatted string containing the tool representation of the function.
Output columns:
- query (`str`): The list of queries.
- answers (`str`): JSON formatted string with the list of answers, containing the info as
a dictionary to be passed to the functions.
Categories:
- text-generation
References:
- [APIGen: Automated Pipeline for Generating Verifiable and Diverse Function-Calling Datasets](https://arxiv.org/abs/2406.18518)
- [Salesforce/xlam-function-calling-60k](https://huggingface.co/datasets/Salesforce/xlam-function-calling-60k)
Examples:
Generate without structured output (original implementation):
```python
from distilabel.steps.tasks import ApiGenGenerator
from distilabel.llms import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 1024,
},
)
apigen = ApiGenGenerator(
use_default_structured_output=False,
llm=llm
)
apigen.load()
res = next(
apigen.process(
[
{
"examples": 'QUERY:
What is the binary sum of 10010 and 11101? ANSWER: [{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]', "func_name": "getrandommovie", "func_desc": "Returns a list of random movies from a database by calling an external API." } ] ) ) res # [{'examples': 'QUERY: What is the binary sum of 10010 and 11101? ANSWER: [{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]', # 'number': 1, # 'func_name': 'getrandommovie', # 'func_desc': 'Returns a list of random movies from a database by calling an external API.', # 'queries': ['I want to watch a movie tonight, can you recommend a random one from your database?', # 'Give me 5 random movie suggestions from your database to plan my weekend.'], # 'answers': [[{'name': 'getrandommovie', 'arguments': {}}], # [{'name': 'getrandommovie', 'arguments': {}}, # {'name': 'getrandommovie', 'arguments': {}}, # {'name': 'getrandommovie', 'arguments': {}}, # {'name': 'getrandommovie', 'arguments': {}}, # {'name': 'getrandommovie', 'arguments': {}}]], # 'raw_input_api_gen_generator_0': [{'role': 'system', # 'content': "You are a data labeler. Your responsibility is to generate a set of diverse queries and corresponding answers for the given functions in JSON format.
Construct queries and answers that exemplify how to use these functions in a practical scenario. Include in each query specific, plausible values for each parameter. For instance, if the function requires a date, use a typical and reasonable date.
Ensure the query: - Is clear and concise - Demonstrates typical use cases - Includes all necessary parameters in a meaningful way. For numerical parameters, it could be either numbers or words - Across a variety level of difficulties, ranging from beginner and advanced use cases - The corresponding result's parameter types and ranges match with the function's descriptions
Ensure the answer: - Is a list of function calls in JSON format - The length of the answer list should be equal to the number of requests in the query - Can solve all the requests in the query effectively"}, # {'role': 'user', # 'content': 'Here are examples of queries and the corresponding answers for similar functions: QUERY: What is the binary sum of 10010 and 11101? ANSWER: [{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]
Note that the query could be interpreted as a combination of several independent requests.
Based on these examples, generate 2 diverse query and answer pairs for the function getrandommovie
The detailed function description is the following:
Returns a list of random movies from a database by calling an external API.
The output MUST strictly adhere to the following JSON format, and NO other text MUST be included:
[
{
"query": "The generated query.",
"answers": [
{
"name": "api_name",
"arguments": {
"arg_name": "value"
... (more arguments as required)
}
},
... (more API calls as required)
]
}
]
Now please generate 2 diverse query and answer pairs following the above format.'}]}, # 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}] ```
Generate with structured output:
```python
from distilabel.steps.tasks import ApiGenGenerator
from distilabel.llms import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 1024,
},
)
apigen = ApiGenGenerator(
use_default_structured_output=True,
llm=llm
)
apigen.load()
res_struct = next(
apigen.process(
[
{
"examples": 'QUERY:
What is the binary sum of 10010 and 11101? ANSWER: [{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]', "func_name": "getrandommovie", "func_desc": "Returns a list of random movies from a database by calling an external API." } ] ) ) res_struct # [{'examples': 'QUERY: What is the binary sum of 10010 and 11101? ANSWER: [{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]', # 'number': 1, # 'func_name': 'getrandommovie', # 'func_desc': 'Returns a list of random movies from a database by calling an external API.', # 'queries': ["I'm bored and want to watch a movie. Can you suggest some movies?", # "My family and I are planning a movie night. We can't decide on what to watch. Can you suggest some random movie titles?"], # 'answers': [[{'arguments': {}, 'name': 'getrandommovie'}], # [{'arguments': {}, 'name': 'getrandommovie'}]], # 'raw_input_api_gen_generator_0': [{'role': 'system', # 'content': "You are a data labeler. Your responsibility is to generate a set of diverse queries and corresponding answers for the given functions in JSON format.
Construct queries and answers that exemplify how to use these functions in a practical scenario. Include in each query specific, plausible values for each parameter. For instance, if the function requires a date, use a typical and reasonable date.
Ensure the query: - Is clear and concise - Demonstrates typical use cases - Includes all necessary parameters in a meaningful way. For numerical parameters, it could be either numbers or words - Across a variety level of difficulties, ranging from beginner and advanced use cases - The corresponding result's parameter types and ranges match with the function's descriptions
Ensure the answer: - Is a list of function calls in JSON format - The length of the answer list should be equal to the number of requests in the query - Can solve all the requests in the query effectively"}, # {'role': 'user', # 'content': 'Here are examples of queries and the corresponding answers for similar functions: QUERY: What is the binary sum of 10010 and 11101? ANSWER: [{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]
Note that the query could be interpreted as a combination of several independent requests.
Based on these examples, generate 2 diverse query and answer pairs for the function getrandommovie
The detailed function description is the following:
Returns a list of random movies from a database by calling an external API.
Now please generate 2 diverse query and answer pairs following the above format.'}]}, # 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}] ```
Source code in src/distilabel/steps/tasks/apigen/generator.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
|
inputs: StepColumns
property
¶
The inputs for the task.
outputs: StepColumns
property
¶
The output for the task are the queries and corresponding answers.
load()
¶
Loads the template for the generator prompt.
Source code in src/distilabel/steps/tasks/apigen/generator.py
_parallel_queries(number)
¶
Prepares the function to update the parallel queries guide in the prompt.
Raises:
Type | Description |
---|---|
ValueError
|
if |
Returns:
Type | Description |
---|---|
Callable[[int], str]
|
The function to generate the parallel queries guide. |
Source code in src/distilabel/steps/tasks/apigen/generator.py
_get_number()
¶
Generates the number of queries to generate in a single call.
The number must be set to _number
to avoid changing the original value
when calling _default_error
.
Source code in src/distilabel/steps/tasks/apigen/generator.py
_set_format_inst()
¶
Prepares the function to generate the formatted instructions for the prompt.
If the default structured output is used, returns an empty string because nothing else is needed, otherwise, returns the original addition to the prompt to guide the model to generate a formatted JSON.
Source code in src/distilabel/steps/tasks/apigen/generator.py
_get_func_desc(input)
¶
If available and required, will use the info from the tools in the prompt for extra information. Otherwise will use jut the function description.
Source code in src/distilabel/steps/tasks/apigen/generator.py
format_input(input)
¶
The input is formatted as a ChatType
.
Source code in src/distilabel/steps/tasks/apigen/generator.py
format_output(output, input)
¶
The output is formatted as a list with the score of each instruction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output
|
Union[str, None]
|
the raw output of the LLM. |
required |
input
|
Dict[str, Any]
|
the input to the task. Used for obtaining the number of responses. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
A dict with the queries and answers pairs. |
Dict[str, Any]
|
The answers are an array of answers corresponding to the query. |
Dict[str, Any]
|
Each answer is represented as an object with the following properties: - name (string): The name of the tool used to generate the answer. - arguments (object): An object representing the arguments passed to the tool to generate the answer. |
Dict[str, Any]
|
Each argument is represented as a key-value pair, where the key is the parameter name and the |
Dict[str, Any]
|
value is the corresponding value. |
Source code in src/distilabel/steps/tasks/apigen/generator.py
_format_output(pairs, input)
¶
Parses the response, returning a dictionary with queries and answers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pairs
|
Dict[str, Any]
|
The parsed dictionary from the LLM's output. |
required |
input
|
Dict[str, Any]
|
The input from the |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Formatted output, where the |
Dict[str, Any]
|
are a list of objects. |
Source code in src/distilabel/steps/tasks/apigen/generator.py
_default_error(input)
¶
Returns a default error output, to fill the responses in case of failure.
Source code in src/distilabel/steps/tasks/apigen/generator.py
get_structured_output()
¶
Creates the json schema to be passed to the LLM, to enforce generating a dictionary with the output which can be directly parsed as a python dictionary.
The schema corresponds to the following:
from typing import Dict, List
from pydantic import BaseModel
class Answer(BaseModel):
name: str
arguments: Dict[str, str]
class QueryAnswer(BaseModel):
query: str
answers: List[Answer]
class QueryAnswerPairs(BaseModel):
pairs: List[QueryAnswer]
json.dumps(QueryAnswerPairs.model_json_schema(), indent=4)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
JSON Schema of the response to enforce. |
Source code in src/distilabel/steps/tasks/apigen/generator.py
APIGenSemanticChecker
¶
Bases: Task
Generate queries and answers for the given functions in JSON format.
The APIGenGenerator
is inspired by the APIGen pipeline, which was designed to generate
verifiable and diverse function-calling datasets. The task generates a set of diverse queries
and corresponding answers for the given functions in JSON format.
Attributes:
Name | Type | Description |
---|---|---|
system_prompt |
str
|
System prompt for the task. Has a default one. |
exclude_failed_execution |
str
|
Whether to exclude failed executions (won't run on those
rows that have a False in |
Input columns
- func_desc (
str
): Description of what the function should do. - query (
str
): Instruction from the user. - answers (
str
): JSON encoded list with arguments to be passed to the function/API. Should be loaded usingjson.loads
. - execution_result (
str
): Result of the function/API executed.
Output columns
- thought (
str
): Reasoning for the output on whether to keep this output or not. - keep_row_after_semantic_check (
bool
): True or False, can be used to filter afterwards.
Categories
- filtering
- text-generation
References
Examples:
Semantic checker for generated function calls (original implementation):
```python
from distilabel.steps.tasks import APIGenSemanticChecker
from distilabel.llms import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 1024,
},
)
semantic_checker = APIGenSemanticChecker(
use_default_structured_output=False,
llm=llm
)
semantic_checker.load()
res = next(
semantic_checker.process(
[
{
"func_desc": "Fetch information about a specific cat breed from the Cat Breeds API.",
"query": "What information can be obtained about the Maine Coon cat breed?",
"answers": json.dumps([{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}]),
"execution_result": "The Maine Coon is a big and hairy breed of cat",
}
]
)
)
res
# [{'func_desc': 'Fetch information about a specific cat breed from the Cat Breeds API.',
# 'query': 'What information can be obtained about the Maine Coon cat breed?',
# 'answers': [{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}],
# 'execution_result': 'The Maine Coon is a big and hairy breed of cat',
# 'thought': '',
# 'keep_row_after_semantic_check': True,
# 'raw_input_a_p_i_gen_semantic_checker_0': [{'role': 'system',
# 'content': 'As a data quality evaluator, you must assess the alignment between a user query, corresponding function calls, and their execution results.\nThese function calls and results are generated by other models, and your task is to ensure these results accurately reflect the user’s intentions.\n\nDo not pass if:\n1. The function call does not align with the query’s objective, or the input arguments appear incorrect.\n2. The function call and arguments are not properly chosen from the available functions.\n3. The number of function calls does not correspond to the user’s intentions.\n4. The execution results are irrelevant and do not match the function’s purpose.\n5. The execution results contain errors or reflect that the function calls were not executed successfully.\n'},
# {'role': 'user',
# 'content': 'Given Information:\n- All Available Functions:\nFetch information about a specific cat breed from the Cat Breeds API.\n- User Query: What information can be obtained about the Maine Coon cat breed?\n- Generated Function Calls: [{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}]\n- Execution Results: The Maine Coon is a big and hairy breed of cat\n\nNote: The query may have multiple intentions. Functions may be placeholders, and execution results may be truncated due to length, which is acceptable and should not cause a failure.\n\nThe main decision factor is wheather the function calls accurately reflect the query\'s intentions and the function descriptions.\nProvide your reasoning in the thought section and decide if the data passes (answer yes or no).\nIf not passing, concisely explain your reasons in the thought section; otherwise, leave this section blank.\n\nYour response MUST strictly adhere to the following JSON format, and NO other text MUST be included.\n```\n{\n "thought": "Concisely describe your reasoning here",\n "pass": "yes" or "no"\n}\n```\n'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
```
Semantic checker for generated function calls (structured output):
```python
from distilabel.steps.tasks import APIGenSemanticChecker
from distilabel.llms import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 1024,
},
)
semantic_checker = APIGenSemanticChecker(
use_default_structured_output=True,
llm=llm
)
semantic_checker.load()
res = next(
semantic_checker.process(
[
{
"func_desc": "Fetch information about a specific cat breed from the Cat Breeds API.",
"query": "What information can be obtained about the Maine Coon cat breed?",
"answers": json.dumps([{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}]),
"execution_result": "The Maine Coon is a big and hairy breed of cat",
}
]
)
)
res
# [{'func_desc': 'Fetch information about a specific cat breed from the Cat Breeds API.',
# 'query': 'What information can be obtained about the Maine Coon cat breed?',
# 'answers': [{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}],
# 'execution_result': 'The Maine Coon is a big and hairy breed of cat',
# 'keep_row_after_semantic_check': True,
# 'thought': '',
# 'raw_input_a_p_i_gen_semantic_checker_0': [{'role': 'system',
# 'content': 'As a data quality evaluator, you must assess the alignment between a user query, corresponding function calls, and their execution results.\nThese function calls and results are generated by other models, and your task is to ensure these results accurately reflect the user’s intentions.\n\nDo not pass if:\n1. The function call does not align with the query’s objective, or the input arguments appear incorrect.\n2. The function call and arguments are not properly chosen from the available functions.\n3. The number of function calls does not correspond to the user’s intentions.\n4. The execution results are irrelevant and do not match the function’s purpose.\n5. The execution results contain errors or reflect that the function calls were not executed successfully.\n'},
# {'role': 'user',
# 'content': 'Given Information:\n- All Available Functions:\nFetch information about a specific cat breed from the Cat Breeds API.\n- User Query: What information can be obtained about the Maine Coon cat breed?\n- Generated Function Calls: [{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}]\n- Execution Results: The Maine Coon is a big and hairy breed of cat\n\nNote: The query may have multiple intentions. Functions may be placeholders, and execution results may be truncated due to length, which is acceptable and should not cause a failure.\n\nThe main decision factor is wheather the function calls accurately reflect the query\'s intentions and the function descriptions.\nProvide your reasoning in the thought section and decide if the data passes (answer yes or no).\nIf not passing, concisely explain your reasons in the thought section; otherwise, leave this section blank.\n'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
```
Source code in src/distilabel/steps/tasks/apigen/semantic_checker.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 |
|
inputs: StepColumns
property
¶
The inputs for the task.
outputs: StepColumns
property
¶
The output for the task are the queries and corresponding answers.
load()
¶
Loads the template for the generator prompt.
Source code in src/distilabel/steps/tasks/apigen/semantic_checker.py
_set_format_inst()
¶
Prepares the function to generate the formatted instructions for the prompt.
If the default structured output is used, returns an empty string because nothing else is needed, otherwise, returns the original addition to the prompt to guide the model to generate a formatted JSON.
Source code in src/distilabel/steps/tasks/apigen/semantic_checker.py
format_input(input)
¶
The input is formatted as a ChatType
.
Source code in src/distilabel/steps/tasks/apigen/semantic_checker.py
format_output(output, input)
¶
The output is formatted as a list with the score of each instruction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output
|
Union[str, None]
|
the raw output of the LLM. |
required |
input
|
Dict[str, Any]
|
the input to the task. Used for obtaining the number of responses. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
A dict with the queries and answers pairs. |
Dict[str, Any]
|
The answers are an array of answers corresponding to the query. |
Dict[str, Any]
|
Each answer is represented as an object with the following properties: - name (string): The name of the tool used to generate the answer. - arguments (object): An object representing the arguments passed to the tool to generate the answer. |
Dict[str, Any]
|
Each argument is represented as a key-value pair, where the key is the parameter name and the |
Dict[str, Any]
|
value is the corresponding value. |
Source code in src/distilabel/steps/tasks/apigen/semantic_checker.py
_default_error(input)
¶
Default error message for the task.
get_structured_output()
¶
Creates the json schema to be passed to the LLM, to enforce generating a dictionary with the output which can be directly parsed as a python dictionary.
The schema corresponds to the following:
from typing import Literal
from pydantic import BaseModel
import json
class Checker(BaseModel):
thought: str
passes: Literal["yes", "no"]
json.dumps(Checker.model_json_schema(), indent=4)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
JSON Schema of the response to enforce. |
Source code in src/distilabel/steps/tasks/apigen/semantic_checker.py
ArgillaLabeller
¶
Bases: Task
Annotate Argilla records based on input fields, example records and question settings.
This task is designed to facilitate the annotation of Argilla records by leveraging a pre-trained LLM. It uses a system prompt that guides the LLM to understand the input fields, the question type, and the question settings. The task then formats the input data and generates a response based on the question. The response is validated against the question's value model, and the final suggestion is prepared for annotation.
Attributes:
Name | Type | Description |
---|---|---|
_template |
Union[Template, None]
|
a Jinja2 template used to format the input for the LLM. |
Input columns
- record (
argilla.Record
): The record to be annotated. - fields (
Optional[List[Dict[str, Any]]]
): The list of field settings for the input fields. - question (
Optional[Dict[str, Any]]
): The question settings for the question to be answered. - example_records (
Optional[List[Dict[str, Any]]]
): The few shot example records with responses to be used to answer the question. - guidelines (
Optional[str]
): The guidelines for the annotation task.
Output columns
- suggestion (
Dict[str, Any]
): The final suggestion for annotation.
Categories
- text-classification
- scorer
- text-generation
Examples:
Annotate a record with the same dataset and question:
import argilla as rg
from argilla import Suggestion
from distilabel.steps.tasks import ArgillaLabeller
from distilabel.llms.huggingface import InferenceEndpointsLLM
# Get information from Argilla dataset definition
dataset = rg.Dataset("my_dataset")
pending_records_filter = rg.Filter(("status", "==", "pending"))
completed_records_filter = rg.Filter(("status", "==", "completed"))
pending_records = list(
dataset.records(
query=rg.Query(filter=pending_records_filter),
limit=5,
)
)
example_records = list(
dataset.records(
query=rg.Query(filter=completed_records_filter),
limit=5,
)
)
field = dataset.settings.fields["text"]
question = dataset.settings.questions["label"]
# Initialize the labeller with the model and fields
labeller = ArgillaLabeller(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
fields=[field],
question=question,
example_records=example_records,
guidelines=dataset.guidelines
)
labeller.load()
# Process the pending records
result = next(
labeller.process(
[
{
"record": record
} for record in pending_records
]
)
)
# Add the suggestions to the records
for record, suggestion in zip(pending_records, result):
record.suggestions.add(Suggestion(**suggestion["suggestion"]))
# Log the updated records
dataset.records.log(pending_records)
Annotate a record with alternating datasets and questions:
import argilla as rg
from distilabel.steps.tasks import ArgillaLabeller
from distilabel.llms.huggingface import InferenceEndpointsLLM
# Get information from Argilla dataset definition
dataset = rg.Dataset("my_dataset")
field = dataset.settings.fields["text"]
question = dataset.settings.questions["label"]
question2 = dataset.settings.questions["label2"]
# Initialize the labeller with the model and fields
labeller = ArgillaLabeller(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
)
)
labeller.load()
# Process the record
record = next(dataset.records())
result = next(
labeller.process(
[
{
"record": record,
"fields": [field],
"question": question,
},
{
"record": record,
"fields": [field],
"question": question2,
}
]
)
)
# Add the suggestions to the record
for suggestion in result:
record.suggestions.add(rg.Suggestion(**suggestion["suggestion"]))
# Log the updated record
dataset.records.log([record])
Overwrite default prompts and instructions:
import argilla as rg
from distilabel.steps.tasks import ArgillaLabeller
from distilabel.llms.huggingface import InferenceEndpointsLLM
# Overwrite default prompts and instructions
labeller = ArgillaLabeller(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
system_prompt="You are an expert annotator and labelling assistant that understands complex domains and natural language processing.",
question_to_label_instruction={
"label_selection": "Select the appropriate label from the list of provided labels.",
"multi_label_selection": "Select none, one or multiple labels from the list of provided labels.",
"text": "Provide a text response to the question.",
"rating": "Provide a rating for the question.",
},
)
labeller.load()
Source code in src/distilabel/steps/tasks/argilla_labeller.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 |
|
load()
¶
Loads the Jinja2 template.
Source code in src/distilabel/steps/tasks/argilla_labeller.py
_format_record(record, fields)
¶
Format the record fields into a string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
record
|
Dict[str, Any]
|
The record to format. |
required |
fields
|
List[Dict[str, Any]]
|
The fields to format. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The formatted record fields. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
_get_label_instruction(question)
¶
Get the label instruction for the question.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
question
|
Dict[str, Any]
|
The question to get the label instruction for. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The label instruction for the question. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
_format_question(question)
¶
Format the question settings into a string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
question
|
Dict[str, Any]
|
The question to format. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The formatted question. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
_format_example_records(records, fields, question)
¶
Format the example records into a string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
records
|
List[Dict[str, Any]]
|
The records to format. |
required |
fields
|
List[Dict[str, Any]]
|
The fields to format. |
required |
question
|
Dict[str, Any]
|
The question to format. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The formatted example records. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
format_input(input)
¶
Format the input into a chat message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input
|
Dict[str, Union[Dict[str, Any], Record, TextField, MultiLabelQuestion, LabelQuestion, RatingQuestion, TextQuestion]]
|
The input to format. |
required |
Returns:
Type | Description |
---|---|
ChatType
|
The formatted chat message. |
Raises:
Type | Description |
---|---|
ValueError
|
If question or fields are not provided. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
format_output(output, input)
¶
Format the output into a dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output
|
Union[str, None]
|
The output to format. |
required |
input
|
Dict[str, Any]
|
The input to format. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: The formatted output. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
process(inputs)
¶
Process the input through the task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
inputs
|
StepInput
|
The input to process. |
required |
Returns:
Name | Type | Description |
---|---|---|
StepOutput |
StepOutput
|
The output of the task. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
_get_value_from_question_value_model(question_value_model)
¶
Get the value from the question value model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
question_value_model
|
BaseModel
|
The question value model to get the value from. |
required |
Returns:
Name | Type | Description |
---|---|---|
Any |
Any
|
The value from the question value model. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
_assign_value_to_question_value_model(value, question)
¶
Assign the value to the question value model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Any
|
The value to assign. |
required |
question
|
Dict[str, Any]
|
The question to assign the value to. |
required |
Returns:
Name | Type | Description |
---|---|---|
BaseModel |
BaseModel
|
The question value model with the assigned value. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
_get_pydantic_model_of_structured_output(question)
¶
Get the Pydantic model of the structured output.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
question
|
Dict[str, Any]
|
The question to get the Pydantic model of the structured output for. |
required |
Returns:
Name | Type | Description |
---|---|---|
BaseModel |
BaseModel
|
The Pydantic model of the structured output. |
Source code in src/distilabel/steps/tasks/argilla_labeller.py
CLAIR
¶
Bases: Task
Contrastive Learning from AI Revisions (CLAIR).
CLAIR uses an AI system to minimally revise a solution A→A´ such that the resulting
preference A preferred
A’ is much more contrastive and precise.
Input columns
- task (
str
): The task or instruction. - student_solution (
str
): An answer to the task that is to be revised.
Output columns
- revision (
str
): The revised text. - rational (
str
): The rational for the provided revision. - model_name (
str
): The name of the model used to generate the revision and rational.
Categories
- preference
- text-generation
References
Examples:
Create contrastive preference pairs:
from distilabel.steps.tasks import CLAIR
from distilabel.llms.huggingface import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 4096,
},
)
clair_task = CLAIR(llm=llm)
clair_task.load()
result = next(
clair_task.process(
[
{
"task": "How many gaps are there between the earth and the moon?",
"student_solution": 'There are no gaps between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon's orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range.\n\nSo, to summarize, there are no gaps between the Earth and the Moon. The Moon is simply a satellite that orbits the Earth, and its distance from our planet varies slightly due to the elliptical shape of its orbit.'
}
]
)
)
# result
# [{'task': 'How many gaps are there between the earth and the moon?',
# 'student_solution': 'There are no gaps between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon\'s orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range.\n\nSo, to summarize, there are no gaps between the Earth and the Moon. The Moon is simply a satellite that orbits the Earth, and its distance from our planet varies slightly due to the elliptical shape of its orbit.',
# 'revision': 'There are no physical gaps or empty spaces between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a significant separation or gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon\'s orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range. This variation in distance is a result of the Moon\'s orbital path, not the presence of any gaps.\n\nIn summary, the Moon\'s orbit is continuous, with no intervening gaps, and its distance from the Earth varies due to the elliptical shape of its orbit.',
# 'rational': 'The student\'s solution provides a clear and concise answer to the question. However, there are a few areas where it can be improved. Firstly, the term "gaps" can be misleading in this context. The student should clarify what they mean by "gaps." Secondly, the student provides some additional information about the Moon\'s orbit, which is correct but could be more clearly connected to the main point. Lastly, the student\'s conclusion could be more concise.',
# 'distilabel_metadata': {'raw_output_c_l_a_i_r_0': '{teacher_reasoning}: The student\'s solution provides a clear and concise answer to the question. However, there are a few areas where it can be improved. Firstly, the term "gaps" can be misleading in this context. The student should clarify what they mean by "gaps." Secondly, the student provides some additional information about the Moon\'s orbit, which is correct but could be more clearly connected to the main point. Lastly, the student\'s conclusion could be more concise.\n\n{corrected_student_solution}: There are no physical gaps or empty spaces between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a significant separation or gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon\'s orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range. This variation in distance is a result of the Moon\'s orbital path, not the presence of any gaps.\n\nIn summary, the Moon\'s orbit is continuous, with no intervening gaps, and its distance from the Earth varies due to the elliptical shape of its orbit.',
# 'raw_input_c_l_a_i_r_0': [{'role': 'system',
# 'content': "You are a teacher and your task is to minimally improve a student's answer. I will give you a {task} and a {student_solution}. Your job is to revise the {student_solution} such that it is clearer, more correct, and more engaging. Copy all non-corrected parts of the student's answer. Do not allude to the {corrected_student_solution} being a revision or a correction in your final solution."},
# {'role': 'user',
# 'content': '{task}: How many gaps are there between the earth and the moon?\n\n{student_solution}: There are no gaps between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon\'s orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range.\n\nSo, to summarize, there are no gaps between the Earth and the Moon. The Moon is simply a satellite that orbits the Earth, and its distance from our planet varies slightly due to the elliptical shape of its orbit.\n\n-----------------\n\nLet\'s first think step by step with a {teacher_reasoning} to decide how to improve the {student_solution}, then give the {corrected_student_solution}. Mention the {teacher_reasoning} and {corrected_student_solution} identifiers to structure your answer.'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
Citations:
```
@misc{doosterlinck2024anchoredpreferenceoptimizationcontrastive,
title={Anchored Preference Optimization and Contrastive Revisions: Addressing Underspecification in Alignment},
author={Karel D'Oosterlinck and Winnie Xu and Chris Develder and Thomas Demeester and Amanpreet Singh and Christopher Potts and Douwe Kiela and Shikib Mehri},
year={2024},
eprint={2408.06266},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2408.06266},
}
```
Source code in src/distilabel/steps/tasks/clair.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
|
format_input(input)
¶
The input is formatted as a ChatType
assuming that the instruction
is the first interaction from the user within a conversation.
Source code in src/distilabel/steps/tasks/clair.py
format_output(output, input)
¶
The output is formatted as a list with the score of each instruction-response pair.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output
|
Union[str, None]
|
the raw output of the LLM. |
required |
input
|
Dict[str, Any]
|
the input to the task. Used for obtaining the number of responses. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
A dict with the key |