-
Notifications
You must be signed in to change notification settings - Fork 11
Add ability for instructlab-knowledge notebook to take multiple source and qna files
#18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
fabianofranz
merged 16 commits into
instructlab:main
from
alimaredia:multiple-source-and-qna-files
Jun 12, 2025
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
14d5bb7
instructlab-knowledge: save chunks in single chunks.jsonl file
alimaredia 52b5390
Ensure chunking step is using docling json as input
alimaredia 6bcefab
Add ability to use multiple source files for a single qna.yaml
alimaredia cccf23d
Add ability to take multiple knowledge contributions
alimaredia 1200ada
Consolidate contributions into one dir per contribution
alimaredia 5bd6e38
ignore local workspaces
khaledsulayman f1bd6df
allow for steps to be run using artifacts from previous steps up unti…
khaledsulayman 491f17f
Refactored qna_gen code out of notebook resulting in qna_gen.py
alimaredia 3d7d5b8
Various CI, documentation and verification fixes
alimaredia b530505
Delete workspaces dir, minor review_seed_examples fixes
alimaredia 16a7c28
Revisions after code review
alimaredia 9ead8ac
Modify seed data creation docs and authoring variable names
alimaredia b3bfc43
Set number of seed examples generated higher
alimaredia 6a02177
Add constants for subdirectory names
alimaredia 5b32d35
Remove is_dir_valid() from create_seed_dataset.py
alimaredia 0841462
Slim down getting started section
alimaredia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| .DS_Store | ||
| notebooks/instructlab-knowledge/workspaces/* | ||
| !notebooks/instructlab-knowledge/workspaces/.gitkeep |
686 changes: 344 additions & 342 deletions
686
notebooks/instructlab-knowledge/instructlab-knowledge.ipynb
Large diffs are not rendered by default.
Oops, something went wrong.
Binary file not shown.
Binary file not shown.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| import json | ||
| import yaml | ||
| import random | ||
|
|
||
| from pathlib import Path | ||
| from pydantic import SecretStr | ||
| from textwrap import wrap | ||
|
|
||
| from docling_core.transforms.chunker.hierarchical_chunker import DocChunk, DocMeta | ||
| from docling_sdg.qa.utils import get_qa_chunks | ||
| from docling_sdg.qa.generate import Generator | ||
| from docling_sdg.qa.base import GenerateOptions, LlmProvider | ||
|
|
||
| chunk_filter = [ | ||
| lambda chunk: len(str(chunk.text)) > 500 | ||
| ] | ||
|
|
||
| def str_presenter(dumper, data): | ||
| if len(data.splitlines()) > 1: # check for multiline string | ||
| return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') | ||
| elif len(data) > 80: | ||
| data = "\n".join(wrap(data, 80)) | ||
| return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') | ||
| return dumper.represent_scalar('tag:yaml.org,2002:str', data) | ||
|
|
||
| yaml.add_representer(str, str_presenter) | ||
|
|
||
| # to use with safe_dump: | ||
| yaml.representer.SafeRepresenter.add_representer(str, str_presenter) | ||
|
|
||
| class IndentedDumper(yaml.Dumper): | ||
| def increase_indent(self, flow=False, indentless=False): | ||
| return super(IndentedDumper, self).increase_indent(flow, False) | ||
|
|
||
| def generate_seed_examples(contribution_name: str, chunks_jsonl_path: Path, output_dir: Path, domain: str, summary: str, num_seed_examples: int, api_key: str, api_url: str, model_id: str) -> Path: | ||
| """ | ||
| Creates a seed dataset from a path | ||
| Args: | ||
| contribution_name (str): Name of the contribution | ||
| chunks_jsonl_path (Path): Path to the chunks/chunks.jsonl file | ||
| output_dir (Path): Path to output dir for the qna.yaml and intermediate outputs by docling-sdg | ||
| contribution_metadata (dict): Dictionary with the domain and summary of the contribution | ||
| num_seed_examples (str): Number of seed examples user wishes to generate for the contribution | ||
| api_key (str): API key for the model used to generate questions and answers from contexts | ||
| api_url (str): Endpoint for the model used to generate questions and answers from contexts | ||
| model_id (str): Name of the model used to generate questions and answers from contexts | ||
| Returns: | ||
| qna_output_path (pathlib.Path): Path to the generated seed example file | ||
| """ | ||
| dataset = {} | ||
| dataset[contribution_name] = {} | ||
| dataset[contribution_name]["chunks"] = [] | ||
|
|
||
| if not chunks_jsonl_path.exists(): | ||
| raise ValueError(f"chunks.jsonl does not exist but should at {chunks_jsonl_path}") | ||
|
|
||
| docs = [] | ||
|
|
||
| with open(chunks_jsonl_path, 'r') as file: # khaled was here | ||
| for line in file: | ||
| file_in_docs = False | ||
| entry = json.loads(line) | ||
| #entry = yaml.safe_load(line) | ||
| meta = DocMeta(**entry['metadata']) | ||
| chunk = DocChunk(text=entry['chunk'], meta=meta) | ||
| for doc in docs: | ||
| if doc["file"] == entry['file']: | ||
| doc["chunk_objs"].append(chunk) | ||
| file_in_docs = True | ||
| break | ||
|
|
||
| if file_in_docs == False: | ||
| doc = dict(file=entry['file'], chunk_objs=[chunk]) | ||
| docs.append(doc) | ||
|
|
||
| for doc in docs: | ||
| print(f"Filtering smaller chunks out of document {doc['file']}") | ||
|
|
||
| qa_chunks = get_qa_chunks(doc["file"], doc["chunk_objs"], chunk_filter) | ||
| dataset[contribution_name]["chunks"].extend(list(qa_chunks)) | ||
|
|
||
|
|
||
| l = dataset[contribution_name]["chunks"] | ||
| selected_chunks = random.sample(l, num_seed_examples) | ||
|
|
||
| generate_options = GenerateOptions(project_id="project_id") | ||
| generate_options.provider = LlmProvider.OPENAI_LIKE | ||
| generate_options.api_key = SecretStr(api_key) | ||
| generate_options.url = api_url | ||
| generate_options.model_id = model_id | ||
| generate_options.generated_file = output_dir / f"qagen-{contribution_name}.json" | ||
| gen = Generator(generate_options=generate_options) | ||
|
|
||
| Path.unlink(generate_options.generated_file, missing_ok=True) | ||
| results = gen.generate_from_chunks(selected_chunks) # automatically saves to file | ||
|
|
||
| print(f"Status for Q&A generation for {contribution_name} is: {results.status}") | ||
|
|
||
| qnas = {} | ||
| chunk_id_to_text = {} | ||
| with open(generate_options.generated_file, "rt") as f: | ||
| for line in f.readlines(): | ||
| entry = json.loads(line) | ||
| chunk_id = entry['chunk_id'] | ||
| if chunk_id not in chunk_id_to_text: | ||
| chunk_id_to_text[chunk_id] = entry['context'] | ||
| if chunk_id not in qnas: | ||
| qnas[chunk_id] = [] | ||
| qnas[chunk_id].append({'question': entry['question'], 'answer': entry['answer']}) | ||
|
|
||
| qna_output_path = output_dir / "qna.yaml" | ||
|
|
||
| data = {'seed_examples': []} | ||
| for chunk_id, context in chunk_id_to_text.items(): | ||
| data['seed_examples'].append({ | ||
| 'context': context, | ||
| 'questions_and_answers': [ | ||
| { | ||
| 'question': example['question'], | ||
| 'answer': example['answer'], | ||
| } for example in qnas[chunk_id] | ||
| ] | ||
| }) | ||
|
|
||
|
|
||
| data['document_outline'] = summary | ||
| data['domain'] = domain | ||
|
|
||
| Path.unlink(qna_output_path, missing_ok=True) # shouldn't be necessary but was. jupyter caching thing? | ||
| with open(qna_output_path, 'w') as yaml_file: | ||
| yaml.dump(data, yaml_file, Dumper=IndentedDumper, default_flow_style=False, sort_keys=False, width=80) | ||
|
|
||
| return qna_output_path | ||
|
|
||
| def review_seed_examples_file(seed_examples_path: Path, min_seed_examples: int = 5, num_qa_pairs: int = 3) -> None: | ||
| with open(seed_examples_path, 'r') as yaml_file: | ||
| yaml_data = yaml.safe_load(yaml_file) | ||
| errors = [] | ||
| print(f"Reviewing seed examples file at {seed_examples_path.resolve()}") | ||
|
|
||
| # Check for document_outline | ||
| if 'document_outline' not in yaml_data: | ||
| errors.append("Missing contribution summary in 'document_outline'") | ||
| else: | ||
| # contribution summary is called document_outline internally | ||
| print(f"Found contribution summary...") | ||
|
|
||
| # Check for domain | ||
| if 'domain' not in yaml_data: | ||
| errors.append("Missing 'domain'") | ||
| else: | ||
| print(f"Found 'domain'...") | ||
|
|
||
| # Check seed_examples | ||
| seed_examples = yaml_data.get('seed_examples') | ||
| if not seed_examples: | ||
| errors.append("'seed_examples' section is missing or empty.") | ||
| elif len(seed_examples) < min_seed_examples: | ||
| errors.append(f"'seed_examples' should contain at least {min_seed_examples} examples, found {len(seed_examples)}. Please add {min_seed_examples - len(seed_examples)} more seed example(s)") | ||
| else: | ||
| print(f"Found {len(seed_examples)} 'contexts' in 'sed_examples'. Minimum expected number is {min_seed_examples}...") | ||
|
|
||
| if seed_examples: | ||
| for i, example in enumerate(seed_examples, start=1): | ||
| qa_pairs = example.get('questions_and_answers') | ||
| if not qa_pairs: | ||
| errors.append(f"Seed Example {i} is missing 'questions_and_answers' section.") | ||
| elif len(qa_pairs) != num_qa_pairs: | ||
| errors.append(f"Seed Example {i} should contain {num_qa_pairs} question-answer pairs, found {len(qa_pairs)}. Please add {num_qa_pairs - len(qa_pairs)} more question-answer pair(s) to seed example {i}") | ||
| else: | ||
| print(f"Seed Example {i} contains expected number ({num_qa_pairs}) of 'question_and_answers'...") | ||
|
|
||
| if errors: | ||
| print("\n\033[31mERROR! Seed Examples validation failed with the following issues:\033[0m") | ||
| for err in errors: | ||
| print(f"- {err}") | ||
| else: | ||
| print(f"Seed Examples YAML {seed_examples_path.resolve()} is valid :)") | ||
| print(f"\n") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just FYI, I successfully ran it end-to-end on 3.11 with just one minor adjustment. On notebooks/instructlab-knowledge/instructlab-knowledge.ipynb#232 , use
contribution['name'](single quotes).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I made that adjustment but I was hoping to use this PR as an opportunity to bump the python version for the notebook entirely. I'm not sure how high or low a user could go. If we say we're going to support python 3.11 and 3.12 then we should have a CI job for each one.