2024-03-26 14:38:10 +00:00
|
|
|
"""Generate **synthetic data** using LLM and few-shot template."""
|
2023-09-21 06:44:17 +00:00
|
|
|
from typing import Any, Dict, List, Optional
|
2023-09-19 23:29:50 +00:00
|
|
|
|
2023-09-21 06:44:17 +00:00
|
|
|
from langchain.chains.base import Chain
|
2023-09-19 23:29:50 +00:00
|
|
|
from langchain.chains.llm import LLMChain
|
2024-01-02 20:09:45 +00:00
|
|
|
from langchain_core.language_models import BaseLanguageModel
|
2024-03-27 00:03:13 +00:00
|
|
|
from langchain_core.prompts import PromptTemplate
|
2023-09-19 23:29:50 +00:00
|
|
|
|
|
|
|
from langchain_experimental.synthetic_data.prompts import SENTENCE_PROMPT
|
|
|
|
|
|
|
|
|
|
|
|
def create_data_generation_chain(
|
|
|
|
llm: BaseLanguageModel,
|
|
|
|
prompt: Optional[PromptTemplate] = None,
|
|
|
|
) -> Chain:
|
2024-02-24 02:24:16 +00:00
|
|
|
"""Create a chain that generates synthetic sentences with
|
2023-09-19 23:29:50 +00:00
|
|
|
provided fields.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
llm: The language model to use.
|
|
|
|
prompt: Prompt to feed the language model with.
|
|
|
|
If not provided, the default one will be used.
|
|
|
|
"""
|
|
|
|
prompt = prompt or SENTENCE_PROMPT
|
|
|
|
return LLMChain(
|
|
|
|
llm=llm,
|
|
|
|
prompt=prompt,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class DatasetGenerator:
|
2024-02-24 02:24:16 +00:00
|
|
|
"""Generate synthetic dataset with a given language model."""
|
2023-09-19 23:29:50 +00:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
llm: BaseLanguageModel,
|
|
|
|
sentence_preferences: Optional[Dict[str, Any]] = None,
|
|
|
|
):
|
|
|
|
self.generator = create_data_generation_chain(llm)
|
|
|
|
self.sentence_preferences = sentence_preferences or {}
|
|
|
|
|
|
|
|
def __call__(self, fields_collection: List[List[Any]]) -> List[Dict[str, Any]]:
|
|
|
|
results: List[Dict[str, Any]] = []
|
|
|
|
for fields in fields_collection:
|
|
|
|
results.append(
|
|
|
|
self.generator(
|
|
|
|
{"fields": fields, "preferences": self.sentence_preferences}
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return results
|