<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Teddy Crépineau on Medium]]></title>
        <description><![CDATA[Stories by Teddy Crépineau on Medium]]></description>
        <link>https://medium.com/@teddycrpineau?source=rss-16e0670af08f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jLMiMbvmQXjK_nR0.jpg</url>
            <title>Stories by Teddy Crépineau on Medium</title>
            <link>https://medium.com/@teddycrpineau?source=rss-16e0670af08f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:42:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@teddycrpineau/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Intent-Based API Middleware: LoRA Fine-Tuning (Part 1)]]></title>
            <link>https://medium.com/@teddycrpineau/intent-based-api-middleware-lora-fine-tuning-part-1-92b850c8c91f?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/92b850c8c91f</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm-tool-calling]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[qwen]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 06:00:33 GMT</pubDate>
            <atom:updated>2026-07-04T06:18:35.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t46jvQpIB5D1-YEDjlswqA.png" /></figure><p>In a a traditional application, client requests are tightly linked to the REST layer. Every single action maps to an endpoint (e.g. I want to list my order). It creates a strong relationship between the UI implementation and the user experience. With the advance of LLM, this tight coupling can be removed and user experience can be built from intent through a LLM middleware. In this architecture, LLM seat between the client and the application, embedded as part of the software to provide a middleware agent responsible for dispatching tool calls to the relevant endpoint. It results in greater flexibility on the client side with the agent dispatching request while maintaining the deterministic aspect user want from application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ws23XYC-HQmeP6fChkwe-w.png" /></figure><p>For our demonstration, we’ll build an end to end application with a fine tuned open source model. While the fine tuning is probably optional for smaller application with limited number of endpoints, our experiment will demonstrate the ability for an organization to rely on small models freely available to deploy applications with cost decorrelated from token consumption.</p><p>This first part is centered around model fine tuning.</p><h3>1. Fine-Tuning our Model Using LoRA</h3><h4>1.1. Why Fine-Tuning and Why LoRA</h4><p>Language model are trained on vast amount of data. While it allows it to perform many generic tasks, it can be a problem in our case where we want the model to perform more specific tasks (such as specific tool calling). By fine-tuning our model we take that generic model and further train for our domain using specific examples.</p><p>We will use LoRA to fine tune as even small models can require an important amount of compute to fully tune. Imagine a model with 1.5 billions parameters. Let’s imagine we store each parameter as a float32. Float32 are represent as 4 bytes (i.e. 32bits). With 1.5 billions parameter the model has ~5.6GB of weights. With LoRA(Low-Rank Adaptation), we’ll be freezing the weight matrices of the base model and we’ll be adding 2 small matrices per weight matrices we’ll be targeting for each layer of the neural network. The idea behind LoRA is to approximate the update we would have made to the full weight matrices — but at a lower computing cost.</p><p>A note before we dive in. We are running our tutorial on apple silicon chips. Instead of using CUDA (Nvidia’s framework) we will be using apple’s MPS (Metal Performance Shaders).</p><h4>1.2. Environment Setup</h4><p>This assumes you already have python installed and your python virtual environment created. We used python 3.13.7 for this tutorial.</p><p>Let’s install PyTorch. On apple silicon it will install MPS automatically</p><pre>pip install torch</pre><p>Let’s now verify mps is available</p><pre>python -c “import torch; print(torch.backends.mps.is_available())”</pre><p>This should return True</p><p>Let’s now install a few hugginface libraries</p><pre>pip install transformers peft trl</pre><p>transformers is our model library. It gives us a single API to load any OS model. peft Parameter-Efficient Fine-Tuning is our LoRA library. trl Transformer Reinforcement Learning gives a complete training loop that handles chat template, formatting, loss masking on system/user turns, gradient accumulation, and more — it will save us some boilerplate code.</p><pre>pip install sentencepiece</pre><p>sentencepiece is a tokenizer backend some models rely on. Qwen2.5 ships its own BPE tokenizer and doesn’t strictly need it, but installing it keeps things working if you later swap in a model that does.</p><pre>pip install httpx fastapi uvicorn</pre><p>The base model we use in this tutorial, Qwen/Qwen2.5–1.5B-Instruct, is openly available and not gated, so no Hugging Face login is required to download it. If you later swap for a gated model (some Llama or Mistral checkpoints require accepting terms), install hugginggace_hub, generate a read token at huggingface.co/settings/tokens, and authenticate:</p><pre>pip install huggingface_hub<br>hf auth login</pre><p>You will be prompted to paste your token.</p><h3>1.3. Building blocks</h3><h4>1.3.1 Loading the model and the tokenizer</h4><p>We’ll create a model.py file that will perform a few different operations:</p><ul><li>Load our model</li><li>Load our tokenizer</li><li>Instantiate our LoRA config</li></ul><pre>import os<br><br>os.environ[&quot;PYTORCH_ENABLE_MPS_FALLBACK&quot;] = &quot;1&quot;<br>from transformers import AutoTokenizer, AutoModelForCausalLM<br>from peft import LoraConfig, TaskType<br>import torch</pre><p>We import the AutoTokenizer and AutoModelForCausalLM objects to load the corresponding objects based on the model we&#39;ll be using (in our example Qwen/Qwen2.5-1.5B-Instruct). Different categories of AutoModelFor_ exist. _CausalLM is used to generate the next token (left-to-right). This will allow us to implement the tool-calling logic.</p><p>We set os.environ[&quot;PYTORCH_ENABLE_MPS_FALLBACK&quot;] = &quot;1&quot; before importing PyTorch, as MPS does not support all the operations that CUDA does. With this flag set, operations not supported by MPS will fall back to CPU.</p><pre>def load_model(<br>        model_id: str = &quot;Qwen/Qwen2.5-1.5B-Instruct&quot;,<br>        trust_remote_code: bool = True,<br>        device: str = &quot;mps&quot;,<br>        dtype: torch.dtype = torch.float16<br>    ):<br>    return AutoModelForCausalLM.from_pretrained(<br>        model_id,<br>        dtype=dtype,<br>        device_map=device,<br>        trust_remote_code=trust_remote_code,<br>    )</pre><p>Here we load the corresponding model object using the AutoModelFor_ factory. We pass the model_id as the first argument so that we can load the correct model class from the built-in factory. We set dtype to float16 as the Qwen2.5 model parameters are bfloat16 and MPS does not support bfloat16.</p><pre>CHAT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), &quot;chat_template_qwen.jinja&quot;)<br><br>def load_tokenizer(<br>        model_id: str = &quot;Qwen/Qwen2.5-1.5B-Instruct&quot;,<br>        device_map: str = &quot;mps&quot;,<br>        padding_side: str = &quot;right&quot;,<br>        trust_remote_code: bool = True,<br>        chat_template_path: str = CHAT_TEMPLATE_PATH<br>    ):<br>    tokenizer = AutoTokenizer.from_pretrained(<br>        model_id,<br>        device_map=device_map,<br>        trust_remote_code=trust_remote_code<br>    )<br>    tokenizer.pad_token = tokenizer.eos_token<br>    tokenizer.padding_side = padding_side<br>    with open(chat_template_path) as f:<br>        tokenizer.chat_template = f.read()<br>    return tokenizer</pre><p>We then load the tokenizer object. This will convert text into tokens the model understands. We use the same Auto_ class as we did with the model, but this time for the tokenizer. We are also padding the array of tokens so our training examples can be batched together — the GPU requires a rectangular array — so every array in our training sample can be the same length. We pad on the right for training. The padded tokens are excluded from attention by the attention mask, and from the loss by label masking, so they do not affect what the model learns.</p><p>We also override the stock Qwen2.5 chat template with a local chat_template_qwen.jinja. That template wraps the assistant turns in {% generation %}...{% endgeneration %} markers, which lets apply_chat_template(..., return_assistant_tokens_mask=True) emit a per-token mask. Combined with SFTConfig(assistant_only_loss=True) (see the training section), this makes the loss apply to the assistant reply only, not to the prompt or the tool-schema scaffolding.</p><pre>def lora_config(<br>        task_type: TaskType = TaskType.CAUSAL_LM,<br>        r: int = 8,<br>        lora_alpha: int = 16,<br>        lora_dropout: float = 0.05,<br>        target_modules: list = [<br>            &quot;q_proj&quot;,<br>            &quot;k_proj&quot;,<br>            &quot;v_proj&quot;,<br>            &quot;o_proj&quot;,<br>            &quot;gate_proj&quot;,<br>            &quot;up_proj&quot;,<br>            &quot;down_proj&quot;,<br>        ],<br>        bias: str = &quot;none&quot;<br>):<br>    return LoraConfig(<br>        task_type=task_type,<br>        r=r,<br>        lora_alpha=lora_alpha,<br>        lora_dropout=lora_dropout,<br>        target_modules=target_modules,<br>        bias=bias,<br>    )</pre><p>We finally instantiate our LoraConfig object. We set the rank to 8; this makes our A and B matrices d.8 and 8.k, where d and k represent the weight-matrix shape of our model. The rank lets us dial the complexity of the fine-tuning we will be performing — this comes at a higher compute cost as the matrix size increases. Alpha is closely related to our rank, as it is used as a scaling factor for how much our LoRA matrices contribute to the output for a given layer. Finally, the dropout represents the probability that a value from the input/activations will be set to 0. This will prevent overfitting of our model.</p><p>We now have the methods defined to load our model, tokenizer, and LoRA config objects.</p><h4>1.3.2 Device selection</h4><p>The loaders above default to mps, but we want the same code to run on an Nvidia GPU (cuda) or fall back to cpu when neither is available. We centralize that choice in a small device.py module so every entry point (training, validation, inference) resolves the device the same way.</p><pre>import os<br><br>os.environ[&quot;PYTORCH_ENABLE_MPS_FALLBACK&quot;] = &quot;1&quot;<br><br>import torch<br><br>_DTYPE = {<br>    &quot;cuda&quot;: torch.bfloat16,<br>    &quot;mps&quot;: torch.float16,<br>    &quot;cpu&quot;: torch.float32,<br>}<br><br>def available(name: str) -&gt; bool:<br>    if name == &quot;cuda&quot;:<br>        return torch.cuda.is_available()<br>    if name == &quot;mps&quot;:<br>        return torch.backends.mps.is_available() and torch.backends.mps.is_built()<br>    if name == &quot;cpu&quot;:<br>        return True<br>    return False<br><br>def resolve_device(name: str = &quot;auto&quot;) -&gt; tuple[str, torch.dtype]:<br>    if name == &quot;auto&quot;:<br>        for candidate in (&quot;cuda&quot;, &quot;mps&quot;, &quot;cpu&quot;):<br>            if available(candidate):<br>                return candidate, _DTYPE[candidate]<br>    if name not in _DTYPE:<br>        raise SystemError(f&quot;Unknown device &#39;{name}&#39;. Choose from auto, cuda, mps, cpu.&quot;)<br>    if not available(name):<br>        raise SystemError(f&quot;Requested device &#39;{name}&#39; is not available on this machine.&quot;)<br>    return name, _DTYPE[name]</pre><p>resolve_device returns both the device string and a matching dtype: bfloat16 on CUDA, float16 on MPS (which does not support bfloat16), and float32 on CPU. Passing &quot;auto&quot; picks the best available backend.</p><p>The next step is to define our training dataset.</p><h4>1.3.3 The dataset</h4><p>The quality of the examples we’ll feed to our training directly impacts the quality of our fine-tuning — more so than optimizing the hyperparameters of the LoRA config. To bootstrap our examples, we created a few seed prompts users could send to our e-commerce website and used consumer models to generate variations of our seeds. The shape of the training examples is the important element. We can find what our class is expecting through the trl library documentation: <a href="https://huggingface.co/docs/trl/dataset_formats#tool-calling">https://huggingface.co/docs/trl/dataset_formats#tool-calling</a>. We have two components:</p><ul><li>messages: array of messages, where a message has:</li><li>role: role of the sender (user, system, assistant, etc.)</li><li>content: content of the message</li><li>tool_calls: only if there is/are tool calls. This key will take:</li><li>type</li><li>function</li><li>name: the name of the function</li><li>arguments: the arguments of the function</li><li>tools: array of all the tools the LLM will have access to when handling a user request. This allows our model to learn which tool to pick based on intent. The structure of a tool JSON is as follows:</li><li>type: type of the tool</li><li>properties: the arguments passed to the function call</li><li>&lt;nameOfArgument&gt;</li><li>type: the type of the value passed to the argument</li><li>description: description of the argument</li><li>required: array of required arguments</li></ul><p>We then create a small utility function in dataset.py that will take our training examples and save them as an Arrow file. This will allow for more efficient processing during training.</p><pre>import os<br><br>from datasets import Dataset, load_from_disk<br>def to_arrow(load_path: str = &quot;training_set.jsonl&quot;, save_path: str = &quot;agent_dataset&quot;) -&gt; None:<br>    Dataset.from_json(load_path).save_to_disk(save_path)</pre><p>We’ll also add a load_dataset function to load our training set to use while training our model.</p><pre>def load_dataset(path: str = &quot;agent_dataset&quot;, source: str = &quot;training_set.jsonl&quot;) -&gt; Dataset:<br>    &quot;&quot;&quot;Load the Arrow cache at `path`, building it from `source` (jsonl) if missing.&quot;&quot;&quot;<br>    if not os.path.exists(path):<br>        to_arrow(load_path=source, save_path=path)<br><br>return Dataset.load_from_disk(path)</pre><h3>1.4. Training the adapter</h3><h4>1.4.1 Training configuration</h4><p>For fine-tuning our model we’ll use the trl library from Hugging Face: <a href="https://huggingface.co/docs/trl/index">https://huggingface.co/docs/trl/index</a>. Let&#39;s first define our SFTConfig object (Supervised Fine-Tuning Config). We&#39;ll add the following to a utility module in training.py.</p><pre>def get_sft_config(<br>        output_dir: str = &quot;./weights/checkpoints&quot;,<br>        num_train_epochs: int = 10,<br>        per_device_train_batch_size: int = 1,<br>        per_device_eval_batch_size: int = 1,<br>        gradient_accumulation_steps: int = 16,<br>        learning_rate: float = 2e-4,<br>        lr_scheduler_type: str = &quot;cosine&quot;,<br>        warmup_steps: int = 50,<br>        bf16: bool = False,<br>        fp16: bool = False,<br>        greater_is_better=False,<br>        metric_for_best_model: str = &quot;eval_loss&quot;,<br>        logging_steps: int = 10,<br>        eval_strategy: str = &quot;steps&quot;,<br>        eval_steps: int = 50,<br>        save_strategy: str = &quot;steps&quot;,<br>        save_steps: int = 50,<br>        dataloader_pin_memory: bool = False,<br>        gradient_checkpointing: bool = True,<br>        optim: str = &quot;adamw_torch&quot;,<br>        max_length: int = 2560,<br>        load_best_model_at_end=True,<br>    ) -&gt; SFTConfig:<br>    return SFTConfig(<br>        output_dir=output_dir,<br>        num_train_epochs=num_train_epochs,<br>        per_device_train_batch_size=per_device_train_batch_size,<br>        per_device_eval_batch_size=per_device_eval_batch_size,<br>        gradient_accumulation_steps=gradient_accumulation_steps,<br>        learning_rate=learning_rate,<br>        lr_scheduler_type=lr_scheduler_type,<br>        warmup_steps=warmup_steps,<br>        bf16=bf16,<br>        fp16=fp16,<br>        logging_steps=logging_steps,<br>        eval_strategy=eval_strategy,<br>        eval_steps=eval_steps,<br>        save_strategy=save_strategy,<br>        save_steps=save_steps,<br>        dataloader_pin_memory=dataloader_pin_memory,<br>        optim=optim,<br>        gradient_checkpointing=gradient_checkpointing,<br>        max_length=max_length,<br>        load_best_model_at_end=load_best_model_at_end,<br>        greater_is_better=greater_is_better,<br>        metric_for_best_model=metric_for_best_model,<br>        assistant_only_loss=True,<br>    )</pre><p>Let’s go over the arguments that matter most:</p><ul><li>output_dir: this simply saves a snapshot of the LoRA weights at a point in time.</li><li>num_train_epochs: the number of complete passes over our training data (the one defined in the previous step).</li><li>per_device_train_batch_size / per_device_eval_batch_size: how many sequences are processed at the same time on each device. Bound by the amount of memory available.</li><li>gradient_accumulation_steps: defines over how many micro-batches gradients are accumulated before performing one optimization step. Allows for a larger effective batch and smoother gradient estimates.</li><li>learning_rate: how far weights move along the gradient at each update.</li><li>lr_scheduler_type: determines how the learning rate decays over time.</li><li>warmup_steps: the number of steps over which we linearly increase the learning rate from 0 to its peak (defined in learning_rate).</li><li>bf16 and fp16: set to false as we are running on Apple Silicon and both types are not well supported.</li><li>eval_strategy and eval_steps: we evaluate the trained model every 50 steps on the validation part of the dataset.</li><li>save_strategy and save_steps: we&#39;ll save a checkpoint every 50 steps by default.</li><li>dataloader_pin_memory: MPS-specific setting.</li><li>gradient_checkpointing: recomputes the activations during the backward pass, which keeps the memory footprint low.</li><li>optim: which optimizer we will use.</li><li>max_length: the maximum sequence length; longer examples are truncated.</li><li>load_best_model_at_end with metric_for_best_model=&quot;eval_loss&quot; and greater_is_better=False: keep the checkpoint with the lowest validation loss rather than the last one.</li><li>assistant_only_loss: pairs with the {% generation %} markers in our chat template so loss is computed on the assistant reply only.</li></ul><p>It is important to note that these hyperparameters can be changed, and different configs can be evaluated to see which produces the best results. As we’ll see in the CLI section, the most commonly tuned ones are exposed as command-line flags.</p><p>We now have all our pieces set. Our final step is to wire everything together into a train function, which we add to the same training.py module. It resolves the device, loads the model, tokenizer, and LoRA config, builds the dataset split, and runs the SFTTrainer.</p><h4>1.4.2 The training loop</h4><pre>SMALL_PRESET = {<br>    &quot;num_train_epochs&quot;: 1,<br>    &quot;per_device_train_batch_size&quot;: 1,<br>    &quot;gradient_accumulation_steps&quot;: 4,<br>    &quot;warmup_steps&quot;: 5,<br>    &quot;logging_steps&quot;: 5,<br>    &quot;max_length&quot;: 2560,<br>    &quot;eval_steps&quot;: 25,<br>}<br><br>def train(<br>        small: bool = False,<br>        device: str = &quot;auto&quot;,<br>        model_id: str = BASE_MODEL,<br>        chat_template: str | None = None,<br>        training_set: str = &quot;training_set.jsonl&quot;,<br>        adapter_out: str = &quot;./adapter&quot;,<br>        **overrides,<br>    ):<br>    dev, dtype = resolve_device(device)<br>    logger.info(&quot;Training %s on %s (small=%s)&quot;, model_id, dev, small)<br>    model = load_model(model_id=model_id, device=dev, dtype=dtype)<br>    tokenizer = load_tokenizer(<br>        model_id=model_id,<br>        device_map=dev,<br>        chat_template_path=chat_template or CHAT_TEMPLATE_PATH,<br>    )<br>    lora = lora_config()<br>    config_args = {**SMALL_PRESET, **overrides} if small else overrides<br>    config = get_sft_config(**config_args)<br>    dataset = load_dataset(source=training_set)<br>    split = dataset.train_test_split(test_size=0.1, seed=42)<br>    train_set, eval_set = split[&quot;train&quot;], split[&quot;test&quot;]<br>    if small:<br>        train_set = train_set.shuffle(seed=42).select(range(50))<br>        eval_set = eval_set.shuffle(seed=42).select(range(10))<br>    trainer = SFTTrainer(<br>        model=model,<br>        processing_class=tokenizer,<br>        train_dataset=train_set,<br>        eval_dataset=eval_set,<br>        args=config,<br>        peft_config=lora,<br>        callbacks=[<br>            EarlyStoppingCallback(early_stopping_patience=3, early_stopping_threshold=0.001),<br>        ],<br>    )<br>    trainer.train()<br>    trainer.save_model(adapter_out)<br>    logger.info(&quot;Saved adapter to %s&quot;, adapter_out)</pre><p>SFTTrainer is the class that trains our model, and save_model writes the LoRA matrix weights to adapter_out so we can later pair the adapter with the base model. A few things worth calling out:</p><ul><li>We resolve the device through resolve_device (from device.py) and pass the matching dtype down to load_model.</li><li>EarlyStoppingCallback halts training once the validation loss stops improving.</li><li>The small flag swaps in SMALL_PRESET and trims the split to a handful of examples, giving us a fast smoke-test run.</li></ul><h3>1.5. Evaluating the fine-tuned model</h3><h4>1.5.1 Reading the training data</h4><p>During the training phase, we received a stream of metrics giving us signals about the health of our training. We can bucket these metrics into 3 categories:</p><ul><li><strong>Is my model learning?</strong> This information can be monitored using the loss and accuracy metrics. The eval_loss is particularly interesting as it tells us how the model performs on samples it has not seen, while our train loss tells us how well the model fits our training samples.</li><li><strong>Is my learning stable?</strong> Here we use grad_norm and entropy to monitor it. Measuring the gradient norm helps us understand how much learning our fine-tuning is doing. A large gradient norm that does not decrease is a sign that our fine-tuning is not learning. Entropy tells us about the model&#39;s probability distribution over the vocabulary. A spread-out distribution means our model has low confidence in the tokens it predicts (giving multiple tokens some probability of being the correct one), while a smaller entropy signifies a narrower probability distribution, and therefore a more confident model.</li><li><strong>Is my model generalizing?</strong> The train/eval gap is what we’ll use to control this dimension. The gap between the two losses helps us control for overfitting.</li></ul><p><strong>Is the model learning?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPpupS3aAQ8YS6aQV5SD6A.jpeg" /></figure><p>We see our training loss smoothly drop and then stabilize around epoch 5 at ~0.01. On the evaluation loss we see it stabilizing around epoch 4 at ~0.03. This gives a positive signal that our model is performing well on samples it has not seen, and is able to fit our training samples without overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAJD1bRuzt5IHsBdp_S0HA.jpeg" /></figure><p>Mean token accuracy reaches ~99% a around epoch 4. This tells us our model was able to correctly predict the next token in 99% of the sample it saw. Use on its own it is less predictable as an evaluation of our training but use in conjunction with the loss it gives us a more solid indicator of the training performance.</p><p><strong>Is the model stable?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JIOxuaYYWzLq92JftCGh7g.jpeg" /></figure><p>We see gradient norm stabilizing around ~0.05 around epoch 5; meaning our model has learned most of the information needed from the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8b9RPK_5TAQsVVbQ4MULQ.jpeg" /></figure><p>Entropy stabilizes around ~0.01 around epoch 6, indicating a smaller probability distribution and a more confident model in predicting the next token.</p><p><strong>Has the model generalized?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_0XZZaaSp5Z3z5ilNzoLA.jpeg" /></figure><p>Analyzing the loss gap between our training and evaluation sample we see a small gap indicating the model has learned the underlying pattern of the data and not the specific of the training example.</p><p>Looking at the metrics together we can see most of the learning is achieved by epoch 5–6, and further iteration are marginally improving the model — or that we are starting to overfit our model and loose some generalization. Our early stop configuration correctly stoped the training after 8 epoch.</p><p>The accuracy we watch during training is computed with teacher forcing. The reference tokens are fed back in at every position and we score the next-token prediction. That measures something different from “can the model produce a correct tool call on its own. This is our next evaluation step. For this step we’ll use free generation. We’ll give the model a prompt and let it generate the entire assistant turn then parse and score the result against the expected tool calls and arguments passed to the tool calls.</p><h4><strong>1.5.2 Free-generation vs the base model</strong></h4><p>To get a deeper sense of the quality of our LoRA training, we’ll use our fine tune model (base model + adapter weights) against our validation set (a set of prompt our model has not seen) and evaluate the output vs the expected one. We’ll perform the same thing for our base (the model without the adapter weights) and compare both.</p><p>We start with an `inference.py` module that owns loading the base model, attaching the adapter, and generating a reply. Keeping this logic in one place lets both the evaluation loop and the CLI reuse it.</p><pre>```python<br>import os<br><br>os.environ[&quot;PYTORCH_ENABLE_MPS_FALLBACK&quot;] = &quot;1&quot;<br><br>import torch<br>from peft import PeftModel<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br>from device import resolve_device<br><br>BASE_MODEL = &quot;Qwen/Qwen2.5-1.5B-Instruct&quot;<br>ADAPTER = &quot;./adapter&quot;<br><br><br>def load(model: str = BASE_MODEL, adapter: str = ADAPTER, device: str = &quot;auto&quot;):<br>    dev, dtype = resolve_device(device)<br>    base_model = AutoModelForCausalLM.from_pretrained(model, dtype=dtype, device_map=dev)<br>    tokenizer = AutoTokenizer.from_pretrained(model)<br>    return PeftModel.from_pretrained(base_model, adapter), tokenizer, dev<br><br><br>def run(model, tokenizer, messages, tools=None, device=&quot;mps&quot;, max_new_tokens=512):<br>    inputs = tokenizer.apply_chat_template(<br>        messages,<br>        tools=tools,<br>        add_generation_prompt=True,<br>        return_tensors=&quot;pt&quot;,<br>        return_dict=True,<br>    ).to(device)<br><br>    with torch.no_grad():<br>        outputs = model.generate(<br>            **inputs,<br>            max_new_tokens=max_new_tokens,<br>            do_sample=False,<br>            pad_token_id=tokenizer.eos_token_id,<br>        )<br>        generated = outputs[0][inputs[&quot;input_ids&quot;].shape[-1]:]<br>        return tokenizer.decode(generated, skip_special_tokens=True).strip()</pre><p>load wraps the base model with the adapter via PeftModel.from_pretrained and returns the resolved device alongside the model and tokenizer. run applies the chat template (including any tools), generates greedily (do_sample=False) so the evaluation is deterministic, and decodes only the newly generated tokens.</p><p>The comparison itself lives in validation.py. PeftModel gives us disable_adapter() context manager, so we can evaluate the adapter and the raw base model with the exact same code path.</p><pre>import json<br>import logging<br>import os<br><br>from inference import BASE_MODEL, load, run<br><br>logger = logging.getLogger(__name__)<br><br>VALIDATION_SET = &quot;./validation_set.jsonl&quot;<br>LOG_DIR = &quot;./eval_logs&quot;<br><br><br>def evaluate(model, tokenizer, records, label, device):<br>    os.makedirs(LOG_DIR, exist_ok=True)<br>    log_path = os.path.join(LOG_DIR, f&quot;{label}.jsonl&quot;)<br><br>    with open(log_path, &quot;w&quot;) as log_file:<br>        for i, rec in enumerate(records, 1):<br>            prompt = prompt_messages(rec[&quot;messages&quot;])<br>            output = run(model, tokenizer, prompt, rec.get(&quot;tools&quot;), device)<br>            log_file.write(json.dumps({<br>                &quot;index&quot;: i,<br>                &quot;model&quot;: label,<br>                &quot;input&quot;: prompt,<br>                &quot;output&quot;: output,<br>                &quot;expected&quot;: expected_message(rec[&quot;messages&quot;]),<br>            }, ensure_ascii=False) + &quot;\n&quot;)<br>            logger.info(&quot;[%s] %d/%d&quot;, label, i, len(records))<br><br><br>def validate(validation_set: str = VALIDATION_SET, device: str = &quot;auto&quot;, model_id: str = BASE_MODEL):<br>    with open(validation_set) as f:<br>        records = [json.loads(line) for line in f if line.strip()]<br><br>    model, tokenizer, dev = load(model=model_id, device=device)<br><br>    evaluate(model, tokenizer, records, &quot;adapter&quot;, dev)          # with adapter<br>    with model.disable_adapter():<br>        evaluate(model, tokenizer, records, &quot;base&quot;, dev)         # base model only</pre><p>Each record is truncated to the prompt (everything up to and including the first user turn) by a small prompt_messages helper, generated, and logged next to the expected assistant turn in ./eval_logs/adapter.jsonl and ./eval_logs/base.jsonl. From those two logs we can score the routing and call-quality metrics below.</p><p>Running the evaluation against our 90 examples we end up with the following 2 matrices</p><p><strong>Adapter (n=90)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*eztXNXJGKkfiLMHysbYsDg.png" /></figure><p><strong>Base model (n=90)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*aZbYeqDK6xsNH5vrqXDp0A.png" /></figure><p>If we look at the routing decision we can see our fine tuned model outperform our base model for every metrics (recall, precision, specificity, F1, etc.) which is a positive sign as to whether our fine-tuned model is able to correctly call the right tool. Call quality metrics (was the tool called with the correct arguments) are pretty similar between both models, but the base model is much more unreliable as to whether it can correctly call the right tool in the first step.</p><h3>1.6 Packaging behind a CLI</h3><p>So far we have three entry points — training, validation, and single-message inference — scattered across modules. To make the project easy to drive, we wrap them in one small command-line interface using Python’s standard-library argparse (no extra dependency). The single-message case reuses the load/run helpers from inference.py through a thin infer wrapper.</p><pre>def infer(<br>    message: str,<br>    system: str | None = None,<br>    tools: list | None = None,<br>    use_adapter: bool = True,<br>    model: str = BASE_MODEL,<br>    adapter: str = ADAPTER,<br>    device: str = &quot;auto&quot;,<br>    max_new_tokens: int = 512,<br>) -&gt; str:<br>    loaded, tokenizer, dev = load(model, adapter, device)<br><br>    messages = []<br>    if system:<br>        messages.append({&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system})<br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message})<br><br>    if use_adapter:<br>        return run(loaded, tokenizer, messages, tools, dev, max_new_tokens)<br><br>    with loaded.disable_adapter():<br>        return run(loaded, tokenizer, messages, tools, dev, max_new_tokens)</pre><p>We then expose the three commands in cli.py. Each subcommand shares a --device {auto,cuda,mps,cpu} and a --model flag, train surfaces the most commonly tuned hyper parameters as flags (forwarding them into get_sft_config via the **overrides we saw earlier), and infer adds a --no-adapter switch to compare against the raw base model.</p><pre>import argparse<br>import logging<br><br>DEVICES = [&quot;auto&quot;, &quot;cuda&quot;, &quot;mps&quot;, &quot;cpu&quot;]<br>DEFAULT_MODEL = &quot;Qwen/Qwen2.5-1.5B-Instruct&quot;<br><br><br>def build_parser():<br>    parser = argparse.ArgumentParser(prog=&quot;daneel&quot;)<br>    parser.add_argument(&quot;--log-level&quot;, default=&quot;INFO&quot;)<br>    sub = parser.add_subparsers(dest=&quot;command&quot;, required=True)<br><br>    t = sub.add_parser(&quot;train&quot;, help=&quot;fine-tune the LoRA adapter&quot;)<br>    t.add_argument(&quot;--small&quot;, action=&quot;store_true&quot;, help=&quot;quick run on a tiny subset&quot;)<br>    t.add_argument(&quot;--model&quot;, default=DEFAULT_MODEL, help=&quot;base model id or path&quot;)<br>    t.add_argument(&quot;--chat-template&quot;, help=&quot;path to a chat template (.jinja); defaults to the bundled Qwen template&quot;)<br>    t.add_argument(&quot;--training-set&quot;, default=&quot;training_set.jsonl&quot;, help=&quot;path to the training jsonl&quot;)<br>    t.add_argument(&quot;--device&quot;, choices=DEVICES, default=&quot;auto&quot;)<br>    t.add_argument(&quot;--epochs&quot;, type=int)<br>    t.add_argument(&quot;--lr&quot;, type=float)<br>    t.add_argument(&quot;--batch-size&quot;, type=int)<br>    t.add_argument(&quot;--grad-accum&quot;, type=int)<br>    t.add_argument(&quot;--max-length&quot;, type=int)<br>    t.add_argument(&quot;--warmup-steps&quot;, type=int)<br>    t.add_argument(&quot;--output-dir&quot;)<br>    t.set_defaults(func=_train)<br><br>    v = sub.add_parser(&quot;validate&quot;, help=&quot;evaluate adapter vs base on the validation set&quot;)<br>    v.add_argument(&quot;--validation-set&quot;, default=&quot;./validation_set.jsonl&quot;)<br>    v.add_argument(&quot;--model&quot;, default=DEFAULT_MODEL, help=&quot;base model id or path&quot;)<br>    v.add_argument(&quot;--device&quot;, choices=DEVICES, default=&quot;auto&quot;)<br>    v.set_defaults(func=_validate)<br><br>    i = sub.add_parser(&quot;infer&quot;, help=&quot;answer a single message with the model&quot;)<br>    i.add_argument(&quot;message&quot;)<br>    i.add_argument(&quot;--system&quot;)<br>    i.add_argument(&quot;--no-adapter&quot;, action=&quot;store_true&quot;, help=&quot;use the base model only&quot;)<br>    i.add_argument(&quot;--model&quot;, default=DEFAULT_MODEL, help=&quot;base model id or path&quot;)<br>    i.add_argument(&quot;--device&quot;, choices=DEVICES, default=&quot;auto&quot;)<br>    i.add_argument(&quot;--max-new-tokens&quot;, type=int, default=512)<br>    i.set_defaults(func=_infer)<br><br>    return parser<br><br><br>def main():<br>    args = build_parser().parse_args()<br>    logging.basicConfig(level=args.log_level.upper(), format=&quot;%(levelname)s %(name)s: %(message)s&quot;)<br>    args.func(args)</pre><p>(The _train/_validate/_infer handlers are thin functions that import the relevant module lazily and forward the parsed flags to train, validate, and infer.)</p><p>With that in place the whole workflow is now three commands.</p><pre>pip install -e .<br><br>daneel train --small                       # quick smoke test<br>daneel train --epochs 5 --lr 1e-4          # a real run with tuned hyper parameters<br>daneel validate                            # adapter vs base on the validation set<br>daneel infer &quot;Where is my last order?&quot;     # single-message inference<br>daneel infer &quot;Where is my last order?&quot; --no-adapter   # same prompt, base model only</pre><p>The entire code is available at <a href="https://github.com/TeddyCr/daneel">https://github.com/TeddyCr/daneel</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92b850c8c91f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[sqlalchemy-redshift Is Back: Reviving a Critical Piece of the Python Data Ecosystem]]></title>
            <link>https://blog.open-metadata.org/sqlalchemy-redshift-is-back-reviving-a-critical-piece-of-the-python-data-ecosystem-1388d8dec83d?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1388d8dec83d</guid>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 19:15:25 GMT</pubDate>
            <atom:updated>2026-04-30T19:15:25.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GjdLAl8gw2zRsylMAkGyVw.png" /></figure><p>If you’ve ever connected to AWS Redshift from Python using SQLAlchemy, chances are you’ve used sqlalchemy-redshift. You may not have thought much about it — it’s one of those packages that just works in the background. That is, until it stops working.</p><p>For nearly three years, the project went quiet while the rest of the Python ecosystem moved on to SQLAlchemy 2.0, leaving sqlalchemy-redshift behind. I’ve taken full ownership of sqlalchemy-redshift, and this time around the project has the backing of the <strong>OpenMetadata </strong>engineering team to keep it maintained, stable, and up to date. With the release of <strong>v1.0.0</strong>, it’s back — <a href="https://github.com/sqlalchemy-redshift/sqlalchemy-redshift">sqlalchemy-redshift</a>.</p><h3>Why Does This Package Matter?</h3><p>The package is downloaded on average ~<strong>6 million times on PyPI</strong>. Over <strong>1,800 repositories</strong> and <strong>149 packages </strong>depend on sqlalchemy-redshift.</p><p>Critical data infrastructure projects rely on it. <strong>Apache Superset</strong> — the leading open-source BI platform with over 72k GitHub stars — lists sqlalchemy-redshift as the recommended way to connect to Redshift. We at <strong>OpenMetadata</strong> are using it. <strong>Great Expectations</strong> relies on it for data quality checks against Redshift warehouses, and it is used by <strong>MindsDB</strong>, <strong>Records</strong>, and <strong>Querybook</strong> by Pinterest — the list goes on.</p><p>When the package stalled in 2023 and SQLAlchemy released v2.0, many projects were affected. Apache Airflow removed sqlalchemy-redshift as a dependency in late 2024 because it couldn’t keep up with the SQLAlchemy 2.0 migration. Great Expectations and MindsDB ended up creating their own forks of the package just to get SQLAlchemy 2.0 support. For OpenMetadata, supporting SQLAlchemy 2.0 required sqlalchemy-redshift to also support SQLAlchemy 2.0. Taking over this project allowed us to unblock OpenMetadata and many other projects. This is illustrated by Sebastian Saavedra, a Software Engineer at ZeroFox, who said:</p><blockquote><em>We depend on OpenMetadata’s lineage backend to track data assets correctly. OpenMetadata supporting SQLAlchemy 2 removes friction and makes upgrades much smoother on our side.</em></blockquote><h3>What Does 1.0.0 Deliver?</h3><p>The <strong>v1.0.0</strong> release is a major update focused on modernization:</p><ul><li><strong>SQLAlchemy 2.0 support</strong> — the dialect now requires SQLAlchemy 2.0+ and is fully compatible with its new APIs, including the updated reflection system, select() syntax, and multi-reflection behavior.</li><li><strong>Python 3.10+</strong> — dropped support for Python 3.9 and below, aligning with current ecosystem standards.</li><li><strong>Codebase cleanup</strong> — removed the legacy redshift_sqlalchemy compatibility shim (a remnant from the project’s 2015 rename), replaced pkg_resources with importlib.metadata, and modernized the entire test suite.</li></ul><p>The migration touched <strong>35 files</strong> with over <strong>2,000 lines changed</strong>.</p><h3>What’s Next?</h3><p>Since v1.0.0 is a major upgrade, we’re starting from a clean slate — all existing issues and PRs will be closed. If any of them are still relevant under 1.0.0, you can reopen them. From here, we plan to actively develop new capabilities and keep the dialect current as both SQLAlchemy and Redshift continue to evolve.</p><p>If you use this package, upgrade to v1.0.0 and report any issues. Contributions are always welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1388d8dec83d" width="1" height="1" alt=""><hr><p><a href="https://blog.open-metadata.org/sqlalchemy-redshift-is-back-reviving-a-critical-piece-of-the-python-data-ecosystem-1388d8dec83d">sqlalchemy-redshift Is Back: Reviving a Critical Piece of the Python Data Ecosystem</a> was originally published in <a href="https://blog.open-metadata.org/">OpenMetadata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging the Power of OpenMetadata Data Quality Framework]]></title>
            <link>https://blog.open-metadata.org/leveraging-the-power-of-openmetadata-data-quality-framework-385ba2d8eaf?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/385ba2d8eaf</guid>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-catalog]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-quality-management]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 04:24:42 GMT</pubDate>
            <atom:updated>2023-11-18T18:34:28.039Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenMetadata offers the possibility to execute data quality tests directly from the UI, making it a powerful tool for everyone in the company. With close to 30 table and column tests, OpenMetadata makes it easy for everyone to own data quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*b828dVIB2rMBmubWZ0KeTQ.png" /><figcaption>figure 1 — Creating a test from OpenMetadata UI</figcaption></figure><p>We understand that teams can use third-party tools, or have custom data quality rules. That is why we offer-third party integration with dbt and Great Expectations, and comprehensive API integration to ingest all your test results into the platform.</p><figure><a href="https://www.getcollate.io/?pk_campaign=14_day_trial&amp;pk_source=medium&amp;pk_medium=small_rectangle"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*fUX9yyQ16MJvjWkevMKfHg.png" /></a></figure><p>Now you may ask yourself, “What if I want to extend OpenMetadata tests, and define custom tests that can be set up and executed directly from the UI”? Then look no further. With OpenMetadata Data Quality Framework, you can define your data quality tests and make them available to all your users.</p><p><strong>Disclaimer: </strong>You will need to work with the OpenMetadata API and write some Python code. You won’t need extensive knowledge of these two concepts; only basic familiarity with them will be enough.</p><h4>Configure your Test Definition</h4><p>The first step is to create your test definition. A test definition describes the different elements of your test (e.g., name, description, parameter, etc.). You will define this new test definition as shown below.</p><pre>{<br>    &quot;description&quot;: &quot;&lt;you test definition description&gt;&quot;,<br>    &quot;entityType&quot;: &quot;&lt;TABLE|COLUMN&gt;&quot;,<br>    &quot;name&quot;: &quot;&lt;your_test_name&gt;&quot;,<br>    &quot;displayName&quot;: &quot;&lt;your display name&gt;&quot;,<br>    &quot;testPlatforms&quot;: [&quot;OpenMetadata&quot;],<br>    &quot;supportedDataTypes&quot;: [&quot;NUMBER|TEXT|CHAR&quot;],<br>    &quot;parameterDefinition&quot;: [<br>      {<br>        &quot;name&quot;: &quot;&lt;name&gt;&quot;,<br>        &quot;displayName&quot;: &quot;&lt;display name&gt;&quot;,<br>        &quot;description&quot;: &quot;&lt;desription of the test&gt;&quot;,<br>        &quot;optionValues&quot;: [&quot;optionOne&quot;, &quot;optionTwo&quot;],<br>      },<br>      {<br>        &quot;name&quot;: &quot;&lt;name&gt;&quot;,<br>        &quot;displayName&quot;: &quot;&lt;display name&gt;&quot;,<br>        &quot;description&quot;: &quot;&lt;desription of the test&gt;&quot;,<br>        &quot;optionValues&quot;: [&quot;optionOne&quot;, &quot;optionTwo&quot;],<br>      }<br>    ]<br>}</pre><p>Let’s go over each element one by one:</p><ol><li>description: this is the description of your test. It will provide your users with more information and details</li><li>entityType: set TABLE if you are defining a table-level test or COLUMN if you are defining a column-level test</li><li>name: the name of your test definition. It should be unique across all test definitions</li><li>displayName: the name of your test definition as it will appear in OpenMetadata UI</li><li>testPlatforms: this is an array of test platforms. To make your test executable through OpenMetadata, this should be set to OpenMetadata</li><li>supportedDataTypes: (optional) pass a list of supported data types for your test definition. This will limit the ability for users to create the test only against columns with supported data types. The complete list of data type values can be found <a href="https://github.com/open-metadata/OpenMetadata/blob/222a8f898451f6dc7dafc7bfda232d91c21209cf/openmetadata-spec/src/main/resources/json/schema/entity/data/table.json#L74-L147">here</a>.</li><li>parameterDefinition: a list of parameters that will be used to configure a test<br>name: the name of your parameter<br>displayName: the display name of your parameter as it will appear in the UI<br>description: the description for your parameter. This will be used to populate the tooltip in the UI <br>optionValues: If you want to make your parameter value a selectable value from a dropdown menu</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*DLYdtcS7iwkX3CU-GWLQuQ.png" /></figure><h4>Creating your Test Definition in OpenMetadata</h4><h4>Create your Test Definition in OpenMetadata</h4><p>Once you have defined your test definition using the JSON template above, you must make the test available in OpenMetadata. Making it available in OpenMetadata will make your test usable through the UI. Users can navigate to the test creation page and select it from the dropdown menu.</p><p>For this step, you will need a way to send an API POST request to your OpenMetadata server endpoint/api/v1/dataQuality/testDefinitions. For this example, we’ll use curl (more info about curl<a href="https://curl.se/docs/"> here</a>).</p><p><strong>Test Definition</strong></p><pre>{<br>    &quot;description&quot;: &quot;Compute entropy for a given column&quot;,<br>    &quot;displayName&quot;: &quot;Column Entropy To Be Between&quot;,<br>    &quot;entityType&quot;: &quot;COLUMN&quot;,<br>    &quot;name&quot;: &quot;columnEntropyToBeBetween&quot;,<br>    &quot;testPlatforms&quot;: [&quot;OpenMetadata&quot;],<br>    &quot;parameterDefinition&quot;: [<br>      {<br>        &quot;name&quot;: &quot;minEntropy&quot;,<br>        &quot;displayName&quot;: &quot;Min&quot;,<br>        &quot;dataType&quot;: &quot;INT&quot;,<br>        &quot;required&quot;: true,<br>        &quot;description&quot;: &quot;minimum entropy&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;maxEntropy&quot;,<br>        &quot;displayName&quot;: &quot;Max&quot;,<br>        &quot;dataType&quot;: &quot;INT&quot;,<br>        &quot;required&quot;: true,<br>        &quot;description&quot;: &quot;maximum entropy&quot;<br>      }<br>    ]<br>}</pre><p><strong>curl Request</strong></p><pre>curl --location --request POST &#39;&lt;yourServerHost&gt;/api/v1/dataQuality/testDefinitions&#39; \<br>--header &#39;Authorization: Bearer &lt;yourJWTToken&gt;&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{<br>    &quot;description&quot;: &quot;Compute entropy for a given column&quot;,<br>    &quot;displayName&quot;: &quot;Column Entropy To Be Between&quot;,<br>    &quot;entityType&quot;: &quot;COLUMN&quot;,<br>    &quot;name&quot;: &quot;columnEntropyToBeBetween&quot;,<br>    &quot;testPlatforms&quot;: [&quot;OpenMetadata&quot;],<br>    &quot;parameterDefinition&quot;: [<br>      {<br>        &quot;name&quot;: &quot;minEntropy&quot;,<br>        &quot;displayName&quot;: &quot;Min&quot;,<br>        &quot;dataType&quot;: &quot;INT&quot;,<br>        &quot;required&quot;: true,<br>        &quot;description&quot;: &quot;minimum entropy&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;maxEntropy&quot;,<br>        &quot;displayName&quot;: &quot;Max&quot;,<br>        &quot;dataType&quot;: &quot;INT&quot;,<br>        &quot;required&quot;: true,<br>        &quot;description&quot;: &quot;maximum entropy&quot;<br>      }<br>    ]<br>}&#39;</pre><p>You will need to replace &lt;yourServerHost&gt; with the URL where the OpenMetadata server is hosted (e.g., http://localhost:8558 if you are working with a local installation). You will also need to replace &lt;yourJWTToken&gt; with your personal JWT Token (i.e., go to settings &gt; bot to find your JWT Token or generate one).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*rBf7hVbPqx9-ZSqNR9ZiUQ.png" /><figcaption>figure 2 — Our custom entropy test in OpenMetadata UI</figcaption></figure><h4>Define the Execution Logic</h4><p>Now that we have created our new test definition, we’ll need to tell OpenMetadata how we want to process and execute this test. To accomplish this, we can leverage OpenMetadata Data Quality Framework.</p><p><strong>Step 1 — Create a Python Package</strong></p><p>The first step is to create a new Python package. This will allow you to version control your custom tests and add unit tests. As we’ll be leveraging Python namesapce package, our package needs to have a specific structure.</p><ul><li>For a column level test: &lt;yourFolderName&gt;/metadata/data_quality/validations/columns/&lt;sqlalchemy|pandas&gt;/yourTestName.py</li><li>&lt;yourFolderName&gt;/metadata/data_quality/validations/table/&lt;sqlalchemy|pandas&gt;/yourTestName.py</li></ul><p>Use pandas if you are writing a test that will be used for data lake connectors; otherwise, use sqlalchemy for all other database connectors</p><p>For our column entropy test, our folder structure will look like this</p><pre>folderName/<br>├── setup.py<br>└── metadata/<br>    ├── __init__.py<br>    └── data_quality/<br>        ├── __init__.py<br>        └── validations/<br>            ├── __init__.py<br>            └── column/<br>                ├── __init__.py<br>                └── sqlalchemy/<br>                    ├── __init__.py<br>                    └── columnEntropyToBeBetween.py</pre><p><strong>Important:</strong> note how our test file name matches the above test definition name. This is important to respect.</p><p><strong>Step 2 — </strong><strong>setup.py and </strong><strong>__init__.py files</strong></p><p>For your setup.py file, you will, at minimum, need to call the setup function calling find_packages() for the packages argument.</p><p>For our entropy test, we have added the requirements needed to execute our test (e.g., scipy )</p><pre>from setuptools import find_packages, setup<br><br>base_requirements = [&quot;scipy&quot;]<br>setup(name=&#39;custom-tests&#39;,<br>      version=&#39;0.0.1&#39;,<br>      description=&#39;OpenMetadata Custom Tests&#39;,<br>      packages=find_packages(),<br>      install_requires=list(base_requirements)<br>     )</pre><p>Finally, you must add the line below to all your __init__.py files. This tells Python that we are working with namespace packages (this is at the core of OpenMetadata flexible Data Quality Framework).</p><pre>__path__ = __import__(&#39;pkgutil&#39;).extend_path(__path__, __name__)</pre><p><strong>Step 3 — Defining your Test Execution Logic</strong></p><p>One of the last two missing pieces to our puzzle is adding the logic to execute our test. You will need to create a new class name &lt;YourTestName&gt;Validator that will inherit from BaseTestValidator.</p><p>You will then need to implement the run_validation method where your core logic is being executed.</p><pre>from itertools import chain<br>from sqlalchemy import Column, inspect<br>from scipy import stats<br>from metadata.data_quality.validations.base_test_handler import BaseTestValidator<br>from metadata.generated.schema.tests.basic import TestCaseResult, TestResultValue<br>from metadata.utils.entity_link import get_decoded_column<br><br>class ColumnEntropyToBeBetweenValidator(BaseTestValidator):<br>    &quot;&quot;&quot;Implements custom test validator for OpenMetadata.<br>    Args:<br>        BaseTestValidator (_type_): inherits from BaseTestValidator<br>    &quot;&quot;&quot;<br>    def _get_column_name(self) -&gt; Column:<br>        &quot;&quot;&quot;get column name from the test case entity link<br>        Returns:<br>            Column: column<br>        &quot;&quot;&quot;<br>        column = get_decoded_column(self.test_case.entityLink.__root__)<br>        columns = inspect(self.runner.table).c<br>        column_obj = next(<br>            (col for col in columns if col.name == column),<br>            None,<br>        )<br>        if column_obj is None:<br>            raise ValueError(f&quot;Cannot find column {column}&quot;)<br>        return column_obj<br><br>    def run_validation(self) -&gt; TestCaseResult:<br>        &quot;&quot;&quot;Run test validation&quot;&quot;&quot;<br>        rows = self.runner.select_all_from_table(self._get_column_name())<br>        list_of_values = list(chain.from_iterable(rows))<br>        entropy = stats.entropy(list_of_values)<br>        min_bound = self.get_min_bound(&quot;minEntropy&quot;)<br>        max_bound = self.get_max_bound(&quot;maxEntropy&quot;)<br>        return self.get_test_case_result_object(<br>            self.execution_date,<br>            self.get_test_case_status(min_bound &lt;= entropy &lt;= max_bound),<br>            f&quot;Found entropy={entropy} vs. the expected  min={min_bound} and max={max_bound}].&quot;,<br>            [TestResultValue(name=&quot;entropy&quot;, value=str(entropy))],<br>        )</pre><p>For our entropy test above, we created our new class ColumnEntropyToBeBetweenValidator, which inherits from BaseTestValidator. We then implemented run_validation, fetching the rows from our table column with self.runner.select_all_from_tabl(self._get_column_name()). self._get_column_name() fetches the column for which our test was created. We then compute the entropy for the column stats.entropy(list_of_values). Finally, we fetch the min and max bounds that were set self.get_min_bound(&quot;minEntropy&quot;) — note how the argument we pass to get_&lt;min|max&gt;_bound corresponds to the name of our test definition. Finally, we call self.get_test_case_result_object(...) which will return the status of our test alongside other information.</p><p><strong>Step 4 — Install your package in your environment</strong></p><p>Finally, you must install your package where your OpenMetadata ingestion is running using pip install &lt;...&gt;.</p><p>If you enjoy OpenMetadata and want to contribute new tests to the community, you can head to our <a href="https://github.com/open-metadata/OpenMetadata">GitHub Repo</a>, browse the <a href="https://github.com/open-metadata/OpenMetadata/tree/main/ingestion/src/metadata/data_quality">Data Quality code</a>, and open a new PR. 😊</p><figure><a href="https://www.getcollate.io/?pk_campaign=14_day_trial&amp;pk_source=medium&amp;pk_medium=large_rectangle"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*p3bWeQSUb_qBKGlariCwyQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=385ba2d8eaf" width="1" height="1" alt=""><hr><p><a href="https://blog.open-metadata.org/leveraging-the-power-of-openmetadata-data-quality-framework-385ba2d8eaf">Leveraging the Power of OpenMetadata Data Quality Framework</a> was originally published in <a href="https://blog.open-metadata.org/">OpenMetadata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple, Easy, and Efficient Data Quality with OpenMetadata]]></title>
            <link>https://blog.open-metadata.org/simple-easy-and-efficient-data-quality-with-openmetadata-1c4e7d329364?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c4e7d329364</guid>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-catalog]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[data-governance]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 14:59:38 GMT</pubDate>
            <atom:updated>2024-01-06T20:59:21.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioMhIqAhguFxd1YxKSRgGA.png" /></figure><p>Data quality and reliability are two top priorities for organizations. Many organizations have made considerable investments in Data Quality initiatives. With the current crop of tools, success has been limited due to tool disconnect, lack of collaboration, and accessibility to a broader audience.</p><p>We have a different take on how data quality should be done. Our approach has been to start with metadata. Gathering metadata based on a <a href="https://docs.open-metadata.org/v1.2.x/main-concepts/metadata-standard/schemas">metadata standard</a> allows us to contextualize data in a centralized place and to develop applications and automation on top of this metadata standard — one of which is our data quality solution.</p><figure><a href="https://www.getcollate.io/?pk_campaign=14_day_trial&amp;pk_source=medium&amp;pk_medium=small_rectangle"><img alt="" src="https://cdn-images-1.medium.com/max/720/0*T0_GHaaxmJ_NWU4W.png" /></a></figure><p>In this blog, we’ll explore how <a href="https://open-metadata.org/">OpenMetadata</a> natively supports data quality that is key to many advantages — lowered cost, improved productivity, better <a href="https://docs.open-metadata.org/v1.2.x/how-to-guides/data-collaboration">collaboration</a>, and many more. Let’s dive deep into some of these advantages to show why the approach taken by OpenMetadata is superior. We will use data validation tools like <a href="https://greatexpectations.io/">Great Expectations</a> and <a href="https://soda.io/">Soda</a> to contrast with <a href="https://open-metadata.org/">OpenMetadata</a>.</p><h3>No need for yet another tool for data quality</h3><p>With <a href="https://open-metadata.org/">OpenMetadata</a>, you don’t need a separate standalone system for data quality. The data quality validations are run as data workflows similar to workflows like ETL. This reduces the cost of buying yet another tool in the already fragmented data architecture and the operational costs of installing it, integrating it with various databases with various access control permissions, and managing another service.</p><h3>Efficient creation and running of validation</h3><p>The diagram below shows the steps for creating and running validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*EHfpglAmmQYfGB_O" /></figure><p><a href="https://open-metadata.org/">OpenMetadata</a> reuses the existing metadata, and data source connections are already set up. For other tools, such as <a href="https://greatexpectations.io/">great expectations</a> or <a href="https://www.soda.io/">Soda</a> a connection to the data sources must be set up, and a duplicate copy of metadata must be created even before writing tests. Creating a test is simple in <a href="https://open-metadata.org/">OpenMetadata</a>; it requires only two steps and a few clicks. You can have a suite of assertions running against your table in no time. <strong>Writing validations for a table can be reduced from hours to minutes.</strong></p><h3>Rich data context makes writing validations easy</h3><p><a href="https://open-metadata.org/">OpenMetadata</a> provides rich data profile visualization that helps you identify data quality issues quickly and write validations to detect them, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yo_xt7Np-ivaqBug" /></figure><p>If you see a column with many unexpected null values, you can quickly add a test to validate for null values. If you see a column like total orders having unexpected negative values, you can add a test to check for a valid range.</p><h3>No code tests to democratize data quality</h3><p>For <a href="https://greatexpectations.io/">great expectations</a> and <a href="https://www.soda.io/">Soda</a>, writing tests involves installing Python packages, writing tests in YAML or Python, and running them using schedulers. This makes these tools only accessible to technical users. <a href="https://open-metadata.org/">OpenMetadata</a> provides simple no code and intuitive UI to allow even business users to write tests easily to democratize data quality. Suppose an analyst or a data scientist is making assumptions about the data (non-null, a range of values, cardinality, etc.); they can contribute a test to ensure those assumptions are validated. This helps build a culture where data quality is not just a responsibility of some technical users but a shared responsibility of the organization.</p><p>With the current data quality tools, there is no central place to store the tests and collect the results. You will also need to deploy and maintain a separate user interface to visualize your test results separately per project. Oftentimes, different teams write the same validations in siloes resulting in needless duplication of tests and unnecessary compute costs. All this can be avoided with the central metadata repository for all the tests and results with OpenMetadata.</p><h3>Faster debugging and resolution of data quality issues</h3><p>Writing validation is just the first step. These tests often fail for various reasons. Currently, debugging data quality issues requires a user to jump from tool to tool to understand lineage, schema changes, code changes, etc., as the data quality tools lack the complete context. Fixing the issue requires identifying owners and going from team to team, which can take multiple days of firefighting.</p><p><a href="https://docs.open-metadata.org/">Central metadata</a> provides one place to get the complete picture of your data instead of piecing it together by jumping across the tools. When a validation fails, all the concerned users are alerted about what is failing. The end-to-end lineage is provided to help in impact analysis to identify where the failure originated. All the changes to data and ETL pipelines are versioned, which helps identify how a change might have introduced the issue. Users can easily identify the owner of the data assets to identify who should fix the issue, start a conversation directly inside <a href="https://open-metadata.org/">OpenMetadata</a>, and collaborate on resolving the issue. <strong>The complete context of what failed, where it failed, how it failed, and who is responsible for fixing it helps save countless hours in debugging and resolving data quality issues.</strong></p><p>Communication is key when there are data quality issues. With <a href="https://open-metadata.org/">OpenMetadata</a>, you can also quickly implement a resolution workflow. Test failures will be marked as “New” in the entity data quality dashboard, informing users of ongoing failures. The status can be changed to “Ack” for acknowledgment to let users of the table know the failure is being investigated. Once resolved, users can edit the status to resolved and choose a failure reason that best explains the incident.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTswLdOTog_zVXkD" /></figure><h3>Organizational Visibility to Data Quality</h3><p>In <a href="https://open-metadata.org/">OpenMetadata</a>, you will also find a data quality health dashboard, allowing you to understand the overall health of your quality assertions. This view is available at the data asset and the organization level. The dashboard shows how the organization is doing with data quality and where improvements are needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yARoIeOMx52-Igva" /></figure><h3>Extensibility for power users</h3><p>The native tests OpenMetadata offers cover a wide range of data quality dimensions. It provides assertions covering <strong>Accuracy</strong>, <strong>Completeness</strong>, <strong>Timeliness</strong>, <strong>Relevance</strong>, <strong>Uniqueness</strong>, and <strong>Validity</strong>. It enables teams from across the organization to collaborate on data quality definition to test the business standard of data sets and the engineering ones.</p><p><a href="https://open-metadata.org/">OpenMetadata</a> goes one step further by making the data quality tool easily extensible. For users with SQL knowledge, our custom SQL test enables users to implement testing logic that is specific to their use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*A1xusP_lN0EsOeLK" /></figure><p>Users with Python knowledge can easily extend the <a href="https://open-metadata.org/">OpenMetadata</a> quality framework. You can create and define your own data quality assertions, install them inside <a href="https://open-metadata.org/">OpenMetadata</a>, and have your users configure them and run them directly from the OpenMetadata UI — more details here. With its extensive SDKs and APIs, it is easy to integrate <a href="https://open-metadata.org/">OpenMetadata</a> tests with your data processing pipeline. You can define your tests in <a href="https://open-metadata.org/">OpenMetadata</a> and execute them as a step of your ETL/ELT process — more details <a href="https://blog.open-metadata.org/leveraging-the-power-of-openmetadata-data-quality-framework-385ba2d8eaf">here</a>.</p><p>While data quality programs have become strategic for organizations, few tools have approached it as such. Focused primarily on validation, requiring technical expertise, or treating metadata as a by-product, they have fallen short in solving the multiple challenges of data quality programs.</p><p>With its metadata standard first approach and easy-to-use and extensible data quality tool, <a href="https://open-metadata.org/">OpenMetadata</a> is the solution that can help organizations scale and foster innovation with reliable data at their fingertips.</p><h3>Feature Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*YRRm9X4cSmAFa-epq03g5A.png" /></figure><h3>Data Quality , How to Guides</h3><p>Please refer to our <a href="https://docs.open-metadata.org/v1.2.x/how-to-guides/data-quality-profiler">documentation about Data Quality , Profiler</a> to learn more about the features in <a href="https://open-metadata.org/">OpenMetadata</a></p><h3>Road Ahead</h3><p>We have many amazing features related to Data Quality in our roadmap:</p><p><strong>Anomaly Detection</strong> — Automated Anomaly detection of Freshness, Volume, Completeness, and Schema change detection.</p><p><strong>Suggest Tests for Tables — </strong>OpenMetadata will suggest tests based on Tables and Columns using Machine Learning.</p><p><strong>Data Diff — </strong>Show the differences between tables across different database services.</p><p><strong>Data SLAs — </strong>Data SLAs to provide guarantees around data assets.</p><figure><a href="https://www.getcollate.io/?pk_campaign=14_day_trial&amp;pk_source=medium&amp;pk_medium=large_rectangle"><img alt="" src="https://cdn-images-1.medium.com/max/720/0*47MNbpPQEQIMKsvI.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c4e7d329364" width="1" height="1" alt=""><hr><p><a href="https://blog.open-metadata.org/simple-easy-and-efficient-data-quality-with-openmetadata-1c4e7d329364">Simple, Easy, and Efficient Data Quality with OpenMetadata</a> was originally published in <a href="https://blog.open-metadata.org/">OpenMetadata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate OpenMetadata Test Suites with Your Data Pipelines]]></title>
            <link>https://blog.open-metadata.org/how-to-integrate-openmetadata-test-suites-with-your-data-pipelines-d83fb55fa494?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d83fb55fa494</guid>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-discovery]]></category>
            <category><![CDATA[data-catalog]]></category>
            <category><![CDATA[data-processing]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 16:44:01 GMT</pubDate>
            <atom:updated>2023-09-04T12:37:53.896Z</atom:updated>
            <content:encoded><![CDATA[<p>With OpenMetadata v0.12.0 onwards, users can create and execute test suites directly from the user interface for Data Quality. While this approach covers most use cases, certain data teams will want to integrate their test suite executions with their data processing pipelines. Instead of validating data after it has been modeled, integrating your test suite execution with your data processing pipeline allows you to stop any further tasks to run if quality criteria are not met.</p><p>In this article, we will go over OpenMetadata test suite concepts, how to create a test suite in OpenMetadata, and how to integrate your test suite execution with your data processing pipelines. We’ll use Airflow as our workflow scheduler for our pipelines, but the concepts apply to any type of workflow.</p><figure><a href="https://www.getcollate.io/?pk_campaign=14_day_trial&amp;pk_source=medium&amp;pk_medium=small_rectangle"><img alt="" src="https://cdn-images-1.medium.com/max/728/1*M_tTyWDVeLK72TX0_DklIg.png" /></a></figure><h3>What are OpenMetadata Test Suites</h3><p>At their core, <a href="https://github.com/open-metadata/OpenMetadata/blob/main/openmetadata-spec/src/main/resources/json/schema/tests/testSuite.json">Test suites</a> are execution containers. They hold <a href="https://github.com/open-metadata/OpenMetadata/blob/main/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json">test cases</a>, which themselves represent the specification of <a href="https://github.com/open-metadata/OpenMetadata/blob/main/openmetadata-spec/src/main/resources/json/schema/tests/testDefinition.json">test definitions</a>. OpenMetadata provides a growing number of table-level tests [<a href="https://docs.open-metadata.org/connectors/ingestion/workflows/data-quality/tests#table-tests">details</a>] and column-level tests [<a href="https://docs.open-metadata.org/connectors/ingestion/workflows/data-quality/tests#table-custom-sql-test">details</a>], as well as custom SQL tests allowing you to write SQL tests [<a href="https://docs.open-metadata.org/connectors/ingestion/workflows/data-quality/tests#table-custom-sql-test">details</a>].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lwFRYSaN3vWErsIK" /><figcaption>Image 1-0 — Test Suite, Test Case, and Test Definition relationship</figcaption></figure><p>Test Suite represents a grouping of test cases for a table. In OpenMetadata 1.1.0 and up, test suites are divided into executable (test suites used to run test cases) and logical (test suites used to group tests together and visualize the assertion results). Tests from different tables can be grouped within the same logical test suite. This allows users to visualize tests from different tables in one place. We can imagine multiple source tables used to model a downstream table. All the tests from the source tables can be grouped together to ensure the accuracy of the newly modeled table.</p><h3>How to Create a Test Suite?</h3><p>Make sure you have a running instance of OpenMetadata v1.1.0 or later. If you don’t, check out our <a href="https://docs.open-metadata.org/quick-start/local-deployment">Try OpenMetadata in Docker</a>. Once OpenMetadata is running, ingest metadata for a Database service. Then, navigate to your table data asset and click “Profiler &amp; Data Quality”. From there, you will be able to create a test. Go ahead and click on “Add Test” — you will need to select your test type “Table” or “Column”. Next, you will have to select the test definition you want to run. Select the definition you want and configure your test according to your needs.</p><p>The final step will be to add an ingestion workflow for our test execution. To integrate our test suite execution with our data processing pipeline, we won’t add a schedule. On the “Schedule for Ingestion” page, simply select “none” as a scheduled time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UVHolW4ryDFiARpGJ9H9Pw.gif" /><figcaption>Image 1.1 — Test Suite Creation</figcaption></figure><h3>Integrating OpenMetadata in your Data Processing Pipeline</h3><p>For this example, we’ll create a simple pipeline with 3 tasks (data extraction, OpenMetadata test suite, modelization). We’ll use Los Angeles Sewer data for our example. The data can be fetched at the following API endpoint 👉 <a href="https://data.lacity.org/resource/qcn5-9nfy.json">https://data.lacity.org/resource/qcn5-9nfy.json</a>. It also assumes you have:</p><ol><li>A running OpenMetadata instance, and</li><li>Followed the instructions in “How to Create a Test Suite” to create a test suite.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1xoU5wBOxpJUqG-mM1Nyg.gif" /><figcaption>Image 1.2 — Test Suite before executing our pipeline</figcaption></figure><h4>Extract Source Data</h4><p>Example 1–1 shows our Airflow task used to extract Los Angeles sewer data using the API.</p><p><em>example 1–1 — extract and insert task</em></p><pre>@task(task_id=&quot;extract_and_insert_data&quot;) ①<br>def extract_and_insert(**kwargs):<br>    &quot;&quot;&quot;Extract function&quot;&quot;&quot;   <br>    resp = requests.get(ENDPOINT)<br>    df = pd.DataFrame(resp.json())<br>    hook = RedshiftSQLHook() ②<br>    engine = hook.get_sqlalchemy_engine() ③<br>    engine.dialect.description_encoding = None<br>    df.iloc[:100,1:].to_sql(<br>            &quot;los_angeles_sewer_system&quot;,<br>            con=engine,<br>            if_exists=&quot;replace&quot;,<br>            index=False,<br>    ) ④</pre><ul><li>① @task is an Airflow decorator used to define tasks in the pipeline</li><li>② we get a DbpApiHook which allows us to access specific SQLAlchemy methods</li><li>③ we get the SQLAlchemy engine (our database connection) that we will use to write our data</li><li>④ write 100 rows skipping the first column</li></ul><p>Now that we have written our source extraction function, the next step is to execute our OpenMetadata tests against our data source. Before moving on to the next step, ensure that you have:</p><ol><li>Ingested metadata for the source table, and</li><li>Created a test suite with some tests for your data source table (we named our test suite LASewerTests).</li></ol><h4>Execute Tests Against the Source Data</h4><p>We chose to break down this step into 2 tasks, although it can be combined together. First, we will execute the test suite (i.e. run the test cases associated with our test suite) (<em>example 1–3</em>) and then we will check the results of our test suite’s test cases (<em>example 1–4</em>). We also defined a get_ingestion_pipeline() function (<em>example 1–2</em>) used by 1–3 and 1–4.</p><p><em>example 1–2 — get ingestion pipeline util function</em></p><pre>def get_ingestion_pipeline(name: str):<br>   &quot;&quot;&quot;get ingestion pipeline by name<br> <br>   Args:<br>       name (str): start or full name of ingestion<br>   &quot;&quot;&quot;<br>   pipelines = OPENMETADATA.list_entities(<br>       IngestionPipeline,<br>       fields=&quot;*&quot;,<br>   ).entities ①<br>  <br>   test_suite_pipeline: Optional[IngestionPipeline] = next(<br>       (pipeline for pipeline in pipelines if pipeline.fullyQualifiedName.__root__.startswith(&quot;LASewerTests&quot;)),<br>       None<br>   ) ②<br> <br>   return test_suite_pipeline</pre><ul><li>① we use OpenMetadata Python SDK to list all of our ingestion pipelines</li><li>② we filter the test suite ingestion we have created when creating our test suite or we return None if we don’t find our test suite ingestion pipeline</li></ul><p><em>example 1–3 — execute test suite pipeline</em></p><pre>@task(task_id=&quot;run_om_test&quot;)<br>def run_om_test(**kwargs):<br>    &quot;&quot;&quot;Run Openmetadata tests&quot;&quot;&quot;<br><br>    test_suite_pipeline: Optional[IngestionPipeline] = get_ingestion_pipeline(&quot;LASewerTests&quot;) ①<br><br>    if not test_suite_pipeline:<br>        raise RuntimeError(&quot;No pipeline entity found for {test_suite_pipeline}&quot;)<br><br><br>    OPENMETADATA.run_pipeline(test_suite_pipeline.id.__root__) ②<br><br>    timeout = time.time() + TIMEOUT ③<br>    while True:<br>        statuses = OPENMETADATA.get_pipeline_status_between_ts(<br>                test_suite_pipeline.fullyQualifiedName.__root__,<br>                get_beginning_of_day_timestamp_mill(),<br>                get_end_of_day_timestamp_mill(),<br>            ) ④<br><br>        if statuses:<br>            status = max(statuses, key=operator.attrgetter(&quot;timestamp.__root__&quot;)) ⑤<br>            if status.pipelineState in {PipelineState.success, PipelineState.partialSuccess}:<br>                break<br>            if status.pipelineState == PipelineState.failed:<br>                raise RuntimeError(&quot;Execution failed&quot;)<br>        if time.time() &gt; timeout:<br>            raise RuntimeError(&quot;Execution timed out&quot;)</pre><ul><li>① get our pipeline entity</li><li>② run our pipeline entity which will run the tests</li><li>③ we’ll be checking the status of our pipeline using a while loop so we’ll add a timeout to make sure we don’t get stuck in an infinite loop</li><li>④ retrieve the pipeline statuses for today. get_pipeline_status_between_ts takes 2 timestamps milliseconds as its second and third argument</li><li>⑤ get the latest pipeline status</li></ul><p>Once our pipeline finishes without failure we need to check the results of our test cases. We’ll do that in the below task.</p><pre>@task(task_id=&quot;check_om_test_results&quot;)<br>def check_om_test_results(**kwargs):<br>    &quot;&quot;&quot;Check test results&quot;&quot;&quot;<br>    test_cases = OPENMETADATA.list_entities(<br>        TestCase,<br>        fields=&quot;*&quot;,<br>    ) ①<br><br>    test_cases = [<br>        entity for entity in test_cases.entities if entity.testSuite.name == &quot;LASewerTests&quot;<br>    ] ②<br><br>    test_suite_pipeline: Optional[IngestionPipeline] = get_ingestion_pipeline(&quot;LASewerTests&quot;)<br>    pipelines_statuses = OPENMETADATA.get_pipeline_status_between_ts(<br>            test_suite_pipeline.fullyQualifiedName.__root__,<br>            get_beginning_of_day_timestamp_mill(),<br>            get_end_of_day_timestamp_mill(),<br>        )<br><br>    if not pipelines_statuses:<br>        raise RuntimeError(&quot;Could not find pipeline&quot;)<br>    <br>    latest_pipeline_status: PipelineStatus = max(pipelines_statuses, key=operator.attrgetter(&quot;timestamp.__root__&quot;))<br><br>    for test_case in test_cases:<br>        timeout = time.time() + TIMEOUT<br>        while True:<br>            test_case_results = OPENMETADATA.get_test_case_results(<br>                test_case.fullyQualifiedName.__root__,<br>                get_beginning_of_day_timestamp_mill(),<br>                get_end_of_day_timestamp_mill()<br>            )  ③<br>            if time.time() &gt; timeout:<br>                raise RuntimeError(&quot;Execution timed out&quot;)<br>            if test_case_results:<br>                latest_test_case_result = max(test_case_results, key=operator.attrgetter(&quot;timestamp.__root__&quot;))<br>                if latest_test_case_result.timestamp.__root__ &lt; latest_pipeline_status.startDate.__root__: ④<br>                    continue<br>                if latest_test_case_result.testCaseStatus in {TestCaseStatus.Failed, TestCaseStatus.Aborted}: ④<br>                    raise RuntimeError(f&quot;Test case {test_case.name.__root__} returned status {latest_test_case_result.testCaseStatus.value} &quot;)<br>                break</pre><ul><li>① Get our test case entities</li><li>② Filter test cases that belong to our test suite. It is also possible to pass a testSuiteId parameter in ①, though we prefer this approach in this demo as we have a small number of test cases, and it prevents us from sending another API request</li><li>③ We iterate through all of our test cases and retrieve the results</li><li>④ If our result timestamp is earlier than our pipeline execution, we keep iterating. This means our results are not yet available.</li><li>⑤ If our test result has either failed or was aborted, we fail our task.</li></ul><p>Examples 1–3 and 1–4 allow us to stop our data processing if an error is raised in one of our test cases. Unlike traditional data quality tools test results will be centralized back inside OpenMetadata, allowing the whole team to know a test has failed. On top of centralizing data test failure, any user with the right permission can add additional tests to that test suite, which will be executed as part of the data processing pipeline.</p><p>It is simple to imagine a flow where a Data Engineer creates a data processing pipeline, where an OpenMetadata test suite is run, and a business user defines test cases directly from OpenMetadata user interface. This ensures that teams with business knowledge can easily define quality rules that a data asset needs to have.</p><h4>Create our Modeled Data</h4><p>Our final step is to model our data. <em>Example 1–5</em> takes the source data and performs some aggregation.</p><p><em>Example 1–5</em></p><pre>@task(task_id=&quot;model&quot;)<br>def model(**kwargs):<br>    &quot;&quot;&quot;model function&quot;&quot;&quot;<br>    hook = RedshiftSQLHook()<br>    engine = hook.get_sqlalchemy_engine()<br>    engine.dialect.description_encoding = None<br>    df = pd.read_sql(<br>        &quot;SELECT mapsheet, avg(shape_leng) mean_shape_leng FROM los_angeles_sewer_system GROUP BY 1;&quot;,<br>        con=engine<br>    )<br><br>    df.to_sql(&quot;sewer_mean_len&quot;, con=engine, index=False, if_exists=&quot;replace&quot;)</pre><h3>Conclusion</h3><p>[<a href="https://github.com/open-metadata/openmetadata-demo/blob/main/test-suite/DAGs/test_suite_dag.py">Full DAG Code</a>]</p><p>Now that we have our whole DAG it is time to execute it. As we saw in Image 1.2, OpenMetadata had no test results for our “LA Sewer Tests” test suite. We created our test case to make it fail to show how our modelization task will not run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9I3DhUKQDKldqp6q" /><figcaption>Image 1.3 — Airflow data processing pipeline execution</figcaption></figure><p>Image 1.3 shows the 4 tasks we previously defined. Task #4 was not executed as task #3 check_om_test_results reported test case failures and failed the Airflow task. This prevented our modelization task to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vSyvdBUPAzaxtWq3UWKIA.png" /><figcaption>Image 1.4 — OpenMetadata UI after Airflow DAG execution</figcaption></figure><p>After our data processing pipeline execution, we can navigate to OpenMetdata test suite to view that our test result has been updated in our test suite with a failed test. This allows easy discovery of test failure for OpenMetadata users.</p><p>This illustrates the strength of OpenMetadata. With the API at the core of its architecture, technical teams, and business teams can easily collaborate on building accurate and reliable data products.</p><figure><a href="https://www.getcollate.io/?pk_campaign=14_day_trial&amp;pk_source=medium&amp;pk_medium=large_rectangle"><img alt="" src="https://cdn-images-1.medium.com/max/728/1*B5kZqafplTME5JQ_COWGwA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d83fb55fa494" width="1" height="1" alt=""><hr><p><a href="https://blog.open-metadata.org/how-to-integrate-openmetadata-test-suites-with-your-data-pipelines-d83fb55fa494">How to Integrate OpenMetadata Test Suites with Your Data Pipelines</a> was originally published in <a href="https://blog.open-metadata.org/">OpenMetadata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why an open standard for data quality is important]]></title>
            <link>https://blog.open-metadata.org/why-are-we-building-a-data-quality-standard-1753fae87259?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1753fae87259</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[data-discovery]]></category>
            <category><![CDATA[data-quality]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Tue, 12 Jul 2022 18:16:33 GMT</pubDate>
            <atom:updated>2023-05-25T06:28:19.074Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Written by: </em><a href="https://medium.com/u/5d3218cd196e"><em>Pere Miquel Brull</em></a><em> and </em><a href="https://medium.com/u/16e0670af08f"><em>Teddy Crépineau</em></a></p><p>Data is at the heart of every organization, whether it’s to improve business strategies and operations, product innovation, improve customer experience, or build new efficiencies, the role of data is becoming more and more important. Considering this new reality, driven and backed by data, an important question arises - <strong>Can we trust the data? </strong>Data Quality issues are plaguing organizations and preventing them from realizing the full potential of data.</p><figure><a href="https://www.getcollate.io/?pk_campaign=14_day_trial&amp;pk_source=medium&amp;pk_medium=small_rectangle"><img alt="" src="https://cdn-images-1.medium.com/max/728/1*M_tTyWDVeLK72TX0_DklIg.png" /></a></figure><h3>From Data to Data Products</h3><p>Data is becoming the end goal, not just the means with which to gain business insights. As a result, companies invest more resources to ensure that data is available, discoverable, and usable for all the teams. One key factor driving this trend is building <strong>Trust In Data</strong>.</p><p>Data-related teams should focus on finding insights, building solutions, or other productive activities rather than searching and validating data. Therefore, teams producing data are no longer just concentrating on gathering, but also testing data like any other piece of software. This new requirement brings the need for innovative solutions in the Data Quality and Testing space.</p><h3>The Current Landscape</h3><p>When there’s a lack of a clear winner for solving Data Quality issues in the market, one can usually observe two scenarios:</p><ol><li><strong>Custom and in-house Solutions</strong></li><li><strong>Third-party Solutions</strong></li></ol><p><strong>Custom Solutions </strong><br>Many organizations build in-house solutions, as existing tools either don’t cover specific use cases or can’t easily be integrated within their current processes or architectures. These proprietary solutions need to constantly evolve to keep up with the growing needs and changing use cases and require a sizable investment in both people and resources.</p><p><strong>Third-party Solutions</strong><br>Many tools exist today to solve data quality issues each focusing on a different set of problems. Given no tool is addressing the problem comprehensively, multiple tools are required by an organization to address its needs. These tools also have an overlapping feature set that creates confusion for the users. With a growing number of tools organizations are suffering from data architecture complexity.</p><p>In the current crop of Data Quality software, one solution stands out from the crowd by providing a framework for data contracts and a platform to enable and automate them - <strong>Great Expectations</strong>.</p><h3>Metadata Standard for Data Quality</h3><p>At OpenMetadata, we believe that Open Standards for metadata is a must to make metadata fuel innovation and for true interoperability in the metadata space. Data quality metadata lacks standard schemas to capture the quality tests and results. With standardized schemas, teams see the benefit of tool portability and choose the best one for the job freely. Also, the tests that are created in an organization can be freely exchanged and reused across teams.</p><p>Great Expectations has been doing an excellent job in defining Data Quality tests; thanks to the OpenSource community behind the project. Opening the doors to a community of users with different backgrounds, use cases, and degrees of experience brings in the richness of diversity. This can be seen by the comprehensive suite of data quality tests called <a href="http://greatexpectations.io/expectations">Expectations</a>, developed by the community.</p><p>This is a goal we share in the OpenMetadata community. Building a metadata standard is not something that a few can drive, which is why we are basing our Data Quality efforts on top of what Great Expectations brings to the table.</p><h3>Data Quality Integration</h3><p>Scattered tools and broken user workflows are one of the biggest blockers to unlocking the true potential of data. That’s why we are bringing the data profiling and validation information together with tables’ definitions, schemas, lineage, and ownership.</p><p>Providing users with an overall understanding of the different facets of a data asset, and how it interacts with the rest of the entities within a Data Platform, OpenMetadata is a one-stop solution for finding answers and fueling collaboration.</p><p>Porting Great Expectations’ test case definitions to the metadata standard as <a href="https://github.com/open-metadata/OpenMetadata/tree/main/catalog-rest-service/src/main/resources/json/schema/tests">JSON Schemas</a> has helped us build a robust and validated approach to data quality as part of our Ingestion Framework.</p><p>Moreover, following the API-centric design, any tests adhering to the standard can be collected with their results shown directly in the UI. In the upcoming releases, we are applying this thought aimed directly at Great Expectations, providing an action that will allow current GX users to push tests to OpenMetadata.</p><h3>How to Ingest Great Expectations Test Results to OpenMetadata?</h3><p>With the Actions feature, GX offers the ability to trigger actions after running your Expectations. OpenMetadata takes advantage of this feature to collect metadata generated by GX and centralize it with the other existing metadata helping users from both communities.</p><p>Here are the steps:</p><p><em>The steps below assume you have a running OpenMetadata instance and have created Expectations and checkpoint files in GX.</em></p><h4>Step 1: Pip Install</h4><p>First, pip install our submodule containing the Great Expectations action.</p><pre>pip install openmetadata-ingestion[great-expectations]</pre><p>This command will download the latest version of openmetadata-ingestion. You need to make sure to download the same version as your running OpenMetadata server. For example, if you have OpenMetadata server 0.12.2 running, you will need to download openmetadata-ingestion version 0.12.2.x using the below command</p><pre>pip install &#39;openmetadata-ingestion~=0.12.2.0[great-expectations]&#39;</pre><h4>Step 2: Configure your Checkpoint File</h4><p>Next, configure the checkpoint file with the validator to run against your data. It is also where you will configure your custom actions that will be performed after the validation. You can find out more about checkpoints <a href="https://docs.greatexpectations.io/docs/terms/checkpoint/#relationships-to-other-objects">here</a>.</p><pre>[…]<br>action:<br>    module_name: metadata.great_expectations.action<br>    class_name: OpenMetadataValidationAction<br>    config_file_path: path/to/ometa/config/file/<br>    ometa_service_name: my_service_name<br>[…]</pre><p>ometa_service_name is optional. If you don’t specify it, when looking for the table entity, it will look for the service name where the table entity name exists. If the same table entity name exists in more than one service name, it will raise an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ClyDyRAShUai9ZENWucrTA.gif" /></figure><h4>Step 3: Create your OpenMetadata Config File config.yaml</h4><p>To ingest GX results into OpenMetadata, you will need to specify your OpenMetadata security configuration for the REST endpoint. This configuration file needs to be located inside the config_file_path referenced in step 2 and named config.yaml.</p><pre>hostPort: http://localhost:8585/api<br>authProvider: azure<br>apiVersion: v1<br>securityConfig:<br>    clientSecret: {{ env(&#39;CLIENT_SECRET&#39;) }}<br>    authority: my<br>    clientId: 123<br>    scopes:<br>        - a<br>        - b</pre><p>You can use environment variables in your configuration file by simply using {{ env(&#39;&lt;MY_ENV_VAR&gt;&#39;) }}. These will be parsed and rendered at runtime allowing you to securely create your configuration and commit it to your favorite version control tool.</p><p>As we support multiple security configurations, you can check out <a href="https://docs.open-metadata.org/deploy/secure-openmetadata">the documentation page</a> for more information on specific providers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddfVh8Vpjx2cfft-JmPYzg.gif" /></figure><h4>Step 4: Run your Checkpoint File</h4><p>With everything set up, it is now time to run your checkpoint file.</p><pre>great_expectations checkpoint run &lt;my_checkpoint&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7h-60-GdEkgB9fh7L_YCuw.gif" /></figure><h3>What’s Next?</h3><p>As we strive to always provide the best user experience, we are working on providing generic test definitions. This feature will allow users to ingest all data quality tests supported by GX, DBT, or other data quality tools. Bringing test results from third-party tools in OpenMetadata will allow data consumers to have a 360 view of their data assets while accommodating existing infrastructure across teams.</p><p>We are also working on improving how data quality tests are displayed in the platform by providing a dedicated dashboard at the column level. With this feature, users will be able to quickly understand what type of data they are working on and also the quality of the data. With the historical view, it’ll be possible to understand the evolution of the data quality for a specific asset.</p><p>These next steps are focused on providing an improved user experience to increase trust and understanding of the data; ultimately reducing the time to gain crucial insights.</p><figure><a href="https://www.getcollate.io/?pk_campaign=14_day_trial&amp;pk_source=medium&amp;pk_medium=large_rectangle"><img alt="" src="https://cdn-images-1.medium.com/max/728/1*B5kZqafplTME5JQ_COWGwA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1753fae87259" width="1" height="1" alt=""><hr><p><a href="https://blog.open-metadata.org/why-are-we-building-a-data-quality-standard-1753fae87259">Why an open standard for data quality is important</a> was originally published in <a href="https://blog.open-metadata.org/">OpenMetadata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Profile of a First Time Home Buyer]]></title>
            <link>https://medium.com/@teddycrpineau/profile-of-a-first-time-home-buyer-f6498b9aacc8?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6498b9aacc8</guid>
            <category><![CDATA[mortgage]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Sun, 23 Dec 2018 02:35:06 GMT</pubDate>
            <atom:updated>2018-12-24T04:32:22.964Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Disclaimer:</em></strong><em> this post does not intend to explain trends observed in the graphs below. It simply aims at defining the profile of a first time home buyer in 2017. Trend analysis will be the subject of a different post.</em></p><h4>Context</h4><p>The below analysis has been realized using FHL Banks data from <a href="https://www.fhfa.gov/DataTools/Downloads/Pages/FHLBank-Public-Use-Database-Previous-Years.aspx">fhfa.gov</a>. FHL Banks (Federal Home Loan Banks) are 11 government-sponsored banks providing liquidities to commercial banks to support home buying in their communities. Each bank is responsible for a specific region — see figure 1.</p><figure><img alt="Figure 1 - FHL Banks Region Division" src="https://cdn-images-1.medium.com/max/960/0*uPwaSGNwR6zc3LhC" /><figcaption>Figure 1 — FHL Banks Region Division</figcaption></figure><p>This analysis attempts to define who a typical first time home buyer in the US is. To realize this analysis, the data have been analyzed using python (<a href="https://github.com/TeddyCr/FHLBank_Data_Analysis">GitHub Repo</a>) and cross-referenced with US Census data. To establish a “typical” profile, we analyzed first time home buyers across 4 attributes:</p><ul><li>Average age</li><li>Gender</li><li>Ethnicity</li><li>Income</li></ul><p><strong><em>Note:</em></strong><em> the income analysis includes the total income of borrower(s) (which includes co-borrowers income if one was present). Age, ethnicity, and gender only look at the principal borrower information.</em></p><h4>Average Age</h4><p>In 2017, the average age of a first time home buyer was 36.7 years old, which represents a significant decrease since its pick in 2011 (43.4 years old) — see figure 2. Since 2011, the average age of a first time home buyer has decreased by 15%.</p><figure><img alt="Figure 2 - Average Age of a First Time Home Buyer" src="https://cdn-images-1.medium.com/max/700/0*aoKFvBxEjYIbhTOq" /><figcaption>Figure 2 — Average Age of a First Time Home Buyer</figcaption></figure><h4>Gender Distribution</h4><p>Most of the principal borrowers in 2017 were males (~64% males vs ~31% females). The percentage of first-time male borrowers has been slightly decreasing for the past 8 years (~ -3%) — see figure 3.</p><figure><img alt="Figure 3 - Distribution of Gender for First Time Home Buyer" src="https://cdn-images-1.medium.com/max/700/0*NKoC2644BNRMy-pq" /><figcaption>Figure 3 — Distribution of Gender for First Time Home Buyer</figcaption></figure><h4>Ethnicity Distribution</h4><p>With ~80%, Caucasian/white represent most of the borrowers. They are followed by Asian (~7%), African American (~3.5%), American Indian (~2%), and Pacific Islanders (~0.5%). It is important to note the over-representation of the Caucasian ethnicity amongst borrowers in comparison to the census data. The African American ethnic group is under-represented amongst borrowers in comparison to the Census data.</p><figure><img alt="Figure 3 - Distribution of Gender for First Time Home Buyer" src="https://cdn-images-1.medium.com/max/700/0*UYyTjia0hA1Tz-QL" /><figcaption>Figure 3 — Distribution of Gender for First Time Home Buyer</figcaption></figure><h4>Average Income</h4><p>In 2017 the average income of a first-time borrower was ~$85,000, which represents a ~39% increase since 2009. Comparing the 2017 average income of borrower(s) with the US Census, we can see that it is ~$24,000 greater. Comparing the US Census Median income for the period 2013–2017 with the average borrower(s) income for the same period, the former increased by ~13%, while the later increased by ~40%.</p><figure><img alt="Figure 4 - Average Income of a First Time Home Buyer" src="https://cdn-images-1.medium.com/max/700/0*mgj5AkM-F3nmBAGt" /><figcaption>Figure 4 — Average Income of a First Time Home Buyer</figcaption></figure><h4>Wrapping Up</h4><p>Base on our analysis, we can define a “typical” first time home buyer in the US as: “an individual/household with a 36/37 years old caucasian male as the principal borrower, and an average income of about $85,000 per year”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6498b9aacc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Has Gimlet Media Invented A New Genre Of Podcasts?]]></title>
            <link>https://medium.com/@teddycrpineau/has-gimlet-media-invented-the-plog-983533737398?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/983533737398</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[podcast]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Thu, 14 Apr 2016 01:09:32 GMT</pubDate>
            <atom:updated>2016-04-14T01:20:28.361Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-nd/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-fTitIDJkDCOiDl8G-vTQ.png" /><figcaption>Photo Credit: <a href="https://www.flickr.com/photos/tofu_mugwump/">Topher McCulloch</a></figcaption></figure><p>Tomorrow (April 14th), <a href="https://medium.com/u/fa6b33784f07">Gimlet Media</a> will release <a href="https://gimletmedia.com/show/startup/episodes/">the first episode of StartUp season 3</a>. For those of you who don’t know, StartUp is a podcast hosted by <a href="https://medium.com/u/66e153d84bf9">Alex Blumberg</a> and Lisa Chow that shows “what it’s really like to get a business off the ground”. In season 1, listeners were following week by week the creation of Gimlet Media.</p><p>This format is not without similarities with a popular type of videos on YouTube. I am obviously talking about vlogs. But can we really compare StartUp with Vlogs, and if so, can we say that Gimlet Media has Invented the “Plog”[1]?</p><h4>From Blog to Vlog</h4><p>Let’s start with some etymology. Blog is short for weblog. It is the digital version of what people have been doing for centuries, keeping track of their activities and their thoughts.</p><p>It’s hard to define exactly when people have started to blog. Though, many sources (<a href="http://www.npr.org/templates/story/story.php?storyId=17421022">NPR</a>, <a href="http://www.creativebloq.com/web-design/history-blogging-51411626">Creative Bloq</a>, <a href="https://en.wikipedia.org/wiki/History_of_blogging">Wikipedia</a>, and <a href="http://www.webdesignerdepot.com/2011/03/a-brief-history-of-blogging/">others</a>) tend to consider that <a href="http://links.net/">Justin Hall</a> was the first person to start some sort of blog. Yet, almost 10 years before that, Brian Redman created <a href="https://groups.google.com/forum/#!forum/mod.ber">mod.br</a>, a newsgroup in which he was posting summaries of interesting things he saw online and offline.</p><p>First used to write about one’s personal life, blogs have slowly sparked the interest of companies. With many benefits, blogging is now widely used among companies. As blogs are moving away from their first usage, a 2.0 version of blogging has emerged: vlogging</p><p>Vlog, short for video log, is a video version of a blog. The principle is the same, but the medium is different. Yet, unlike modern blogs, vloggers share their entire life: what they do in a day, what they eat, and how they dress up. Vlogs embrace what blogs once were. The phenomenon is growing fast and YouTube is one of the main facilitators of this growth.</p><p>As personal diaries have conquered almost every digital medium (writing, and video), you may wonder “What‘s the next?”</p><h4>And now has come the “Plog”</h4><p>Until recently, the landscape of online personal diaries was quite clear; blogs had now evolved into a marketing tool, and vlogs were growing in popularity. Yet, the boom of podcasts has disturbed this setup.</p><p>In 2014, Alex Blumberg, a former employee of the public radio, decided to pursue his dream: build a digital media company. It is with his partner Matthew Lieber, that he has created Gimlet Media — a company 100% dedicated to podcasts. As their first show, they have simply broadcast week by week the creation of the company. StartUp listeners were able to follow Alex and Matthew in their journey to creating Gimlet Media. They were part of the ups and the downs of the company.</p><p>This show was a breakthrough for multiple reasons. But one overseen reasons is Gimlet Media invention of a new type of podcast: The “Plog”. It was the first time that a podcast was broadcasting almost day by day the “life” of someone. The show uses a mix a high-quality journalism with well-established codes of blogs and vlogs: sharing personal and “intimate” moments with a sort of raw, unedited feels, and a live and “unscripted” story.</p><p>The show is still telling stories of startup founders, but it no longer tells the one of Gimlet Media— even though listeners get constant updates on the company. StartUp has kept its intimate and personal tone while still offering great journalistic work. Though, the show has slightly moved away from what it might have invented. The question is now, what’s the future of the “Plog”, and how can companies leverage this new type of podcast.</p><p><em>[1] Refers to PodcastLog</em></p><p><em>Thanks for reading ツ ! If you liked this article, don’t forget to share the love. Just hit the 💗 button down below.</em></p><p><em>You can also get more stories like this by visiting </em><a href="http://www.teddycrepineau.com/blog.html"><em>teddycrepineau.com</em></a><em>, or by following me on </em><a href="https://twitter.com/TeddyCrepineau"><em>twitter</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983533737398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unicorns: From Imaginary Horses To Tech Startups]]></title>
            <link>https://medium.com/@teddycrpineau/unicorns-from-imaginary-horses-to-tech-startups-b5183a88106f?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5183a88106f</guid>
            <category><![CDATA[unicorns]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Sun, 10 Apr 2016 02:46:05 GMT</pubDate>
            <atom:updated>2016-04-14T16:29:31.302Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-nd/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fx7_c_00zTDBRthg4a95Tg.jpeg" /><figcaption>Photo credit: <a href="https://www.flickr.com/photos/hamur0w0/">yosuke muroya</a></figcaption></figure><p>While scrolling through <a href="https://twitter.com/TeddyCrepineau">my Twitter feed</a> this morning, I saw an interesting trending hashtag: <a href="https://twitter.com/hashtag/NationalUnicornDay?src=tren"><strong>#NationalUnicornDay</strong></a>. I did what everyone trying to find excuses to not work would do, I clicked on the hashtag. There, I saw what you would expect: pictures of unicorns (Lady Gaga deserves a special round of applause for the effort she put in to celebrate this special day — <em>see picture bellow</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RIBc4wddnslVjRftk2A5w.png" /></figure><p>Yet, it got me thinking, How this cute imaginary horse — <em>according to the myth it would actually be a “ wild ass” with a single horn</em> — has become a popular term used to describe certain tech startups?</p><h3>What Is A Unicorn</h3><p>Let’s start with some etymology. The term unicorn comes form <em>uni</em>, which means single, and <em>cornu</em>, which means horn.</p><p>This imaginary animal first appeared in Western literature in 400 B.C. It is described by Ctesias as “<a href="http://www.britannica.com/topic/unicorn"><em>a horse, with a white body, purple head, and blue eyes, and on its forehead was a cubit-long horn coloured red at the pointed tip, black in the middle, and white at the base</em></a>”. Still according to the myth, it was believed that “<a href="http://www.britannica.com/topic/unicorn"><em>those who drank from its horn were thought to be protected from stomach trouble, epilepsy, and poison</em></a>”.</p><p>In our modern culture, unicorns look way nicer — no purple head, and no scary red, black, and white horn. These white stuff animals and cartoon characters now leave shining rainbows behind them.</p><p>Yet, after more than 2,000 years of evolution, the term unicorn has faced its biggest change in 2013. Popularized by <a href="https://medium.com/u/66aa3eb10e2d">aileenlee</a> in her article “<a href="http://techcrunch.com/2013/11/02/welcome-to-the-unicorn-club/"><em>Welcome To The Unicorn Club: Learning From Billion-Dollar Startups</em></a>”, it is now used to describe a Tech Startup valued by public or private investors at $1 billion or more.</p><h3>How Did We Get From An Imaginary Horse To A Tech Startup?</h3><p>While developing her article for Tech Crunch (“<a href="http://techcrunch.com/2013/11/02/welcome-to-the-unicorn-club/"><em>Welcome To The Unicorn Club: Learning From Billion-Dollar Startups</em></a><em>”)</em>, <a href="https://medium.com/u/66aa3eb10e2d">aileenlee</a> decided she had to come up with a name that would best describe tech startups valued at $1 billion or more. After coming up with few terms “<em>home run</em>” or “<em>megahits</em>” she settled with “unicorn”. But why did she chose this mythologic term?</p><p>One of the reasons she chose this term is because of its mythologic conotation. In one of her interview, <a href="https://medium.com/u/66aa3eb10e2d">aileenlee</a> says how startups have a mythical and playful feeling. She also mention the notion of rarety. Unicorns are rare, as startups valued at more than $1 billion — at the time of her article, only 0.07% of the tech startups had made the cut. Another reason, she mentioned, is the impact of the term. Unicorns have been in the imaginary of people for centuries. It’s instantaneously associated with magical thoughts, and it’s a well-known term.</p><p>This term is nothing but the imaginary of one person. Even though certain persons in the industry criticize it, it only makes tech startups look cuter. What’s funnier than thinking about Marc Zuckerberg riding a My Little Pony unicorn — with all the respect I have for what he accomplished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ta9RxWvx12B696KkbeaRgw.jpeg" /><figcaption>Photo credit: <a href="https://www.flickr.com/photos/partymonstrrrr/">Charles Rodstrom</a></figcaption></figure><p><em>Thanks for reading ツ ! If you liked this article, don’t forget to share the love. Just hit the 💗 button down below.</em></p><p><em>You can also get more stories like this by visiting </em><a href="http://www.teddycrepineau.com/blog.html"><em>teddycrepineau.com</em></a><em>, or by following me on </em><a href="https://twitter.com/TeddyCrepineau"><em>twitter</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5183a88106f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Books Every Content Marketer Should Read]]></title>
            <link>https://medium.com/small-business-forum/3-books-every-content-marketer-should-read-5545629a81fa?source=rss-16e0670af08f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5545629a81fa</guid>
            <category><![CDATA[content-marketing]]></category>
            <category><![CDATA[content-strategy]]></category>
            <category><![CDATA[writing-tips]]></category>
            <dc:creator><![CDATA[Teddy Crépineau]]></dc:creator>
            <pubDate>Sun, 27 Mar 2016 19:01:01 GMT</pubDate>
            <atom:updated>2016-05-09T16:23:57.796Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-nd/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baCd0JkqFRbvrCMq-RS9Mg.jpeg" /></figure><p>Developing content has many benefits for companies. It helps businesses to generate inbound leads, develop brand awareness, strengthen brand image, and improve SEO. Most companies have understood all of these benefits.This term has become popular amongst companies. On indeed, more than 7,000 job offers are available for content writing positions — and this is just in the United States. And if you want to read all the articles or blog posts about content marketing, it will take you more than a life.</p><p>While writing content is easy, writing good and engaging content is harder. Hence the thousands of articles on “<em>how to write good content</em>”. However, most of these articles give the same generic tips “<em>create a call to action</em>”, “<em>get to know your target customer first</em>”, “<em>share your articles on social media</em>”, and my favorite “<em>develop valuable, relevant, and compelling content</em>”.</p><p>When it comes to the last tip, we are often left with this broad term and no more information. What content marketers often forget is that content marketing is about writing. You cannot run unless you know how to walk first. It’s the same for content marketing. You cannot create great content unless you know how to write properly.</p><p>And before diving into any articles talking about call to actions, or developing valuable content, there are 3 books you should read.</p><h3>3 Books Content Marketers Should Have On Their Night Stand</h3><h4>On Writing — Stephen King</h4><p>On writing is part biographical, and part educational. More than the tips laid out by Stephen King, it’s King’s writing style that helps you learn the most.</p><p>In his book, King emphasizes the importance of building and strengthening your spelling, your grammar, and your vocabulary. He insists on the fact that, as a toolbox, you should carry these elements with you all the time. He also demystifies the art of composition by bringing us through his own creation process — sharing with us his own doubts while writing.</p><blockquote>Life isn’t a support-system for art. It’s the other way around — Stephen King</blockquote><p>This book has limited technical tips about writing. Yet, out of the 3 books, it is the most inspirational and empowering.</p><h4>The Elements of Style — Strunk &amp; White</h4><p>The Elements of Style is a well-known book amongst writers. Written at the beginning of the 20th century, this book was first designed for academic purpose. Unlike other English textbook, the Elements of Style is 85 pages long and contains 21 basic English rules.</p><p>The authors have broken down the book into 4 parts: Elementary Rules of Usage, Elementary Principles of Composition, A Few Matter of Form, and Words And Expressions Commonly Misused.</p><blockquote>Instead of announcing what you are about to tell is interesting, make it so — William Strunk Jr.</blockquote><p>In addition to explaining how to best use commas, semicolons or colons, Strunk and White also advise the reader how to use paragraphs, or how to avoid loose sentences.</p><p>Unlike On Writing by Stephen King, Strunk and White have made a book full of technical tips. The size and the layout of The Elements of Style, make it a to go book whenever you have a stylistic or grammatical question.</p><h4>Warriner’s English Grammar and Composition — John E. Warriner</h4><p>Warriner’s English Grammar and Composition is a small and thick book. It is a classic for English grammar. If you have spent your high school years in the US you are certainly familiar with it.</p><p>The book focuses on grammar and structure. Unlike the previous 2 books, Warriner’s English Grammar and Composition is written as a textbook. It is thorough with a lot of details and comprehensive examples. With this book, you will go over basics (pronoun, noun, adverb, etc.), but also more advanced elements of composition (specifics of the English language, language and logic, etc.). It also provides great information for business writing.</p><p>This book is perfect for advanced and beginner content writer.</p><h4>Wrap-up</h4><p>Content writing is before everything else about content; content is about grammar, composition, and vocabulary. Before learning where to place call to actions content marketers should strengthen their composition skills. You only have 3 ways to develop the quality of your composition: refresh your English skills, write, write, write, and read.</p><p><em>Thanks for reading ツ ! If you liked this article, don’t forget to share the love. Just hit the 💗 button down below.</em></p><p><em>You can also get more stories like this by visiting </em><a href="http://www.teddycrepineau.com/blog.html"><em>teddycrepineau.com</em></a><em>, or by following me on </em><a href="https://twitter.com/TeddyCrepineau"><em>twitter</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5545629a81fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/small-business-forum/3-books-every-content-marketer-should-read-5545629a81fa">3 Books Every Content Marketer Should Read</a> was originally published in <a href="https://medium.com/small-business-forum">Small Business Forum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>