Skip to main content

Chonkie + Hal9: Your Fast Track to Smarter RAG Applications

· 7 min read
Data Scientist

Introduction​

In the fast-paced world of Retrieval-Augmented Generation (RAG) applications, preprocessing text into meaningful, manageable chunks is a critical yet often cumbersome task. Enter Chonkie, a lightweight, lightning-fast, and feature-rich chunking library designed to simplify this process. Paired with Hal9, a powerful platform for deploying AI-powered solutions, Chonkie becomes an even more formidable tool for building efficient, scalable, and production-ready AI applications. In this blog post, we’ll dive into what Chonkie is, explore its use cases, and demonstrate how Hal9 complements it to create seamless, high-performance RAG pipelines.

What is Chonkie?​

Chonkie is an open-source, YC-backed semantic chunking library and cloud service tailored for RAG and AI applications that tackles the complexity of text preprocessing with elegance and efficiency. Its core mission is to make the process of breaking down large texts into smaller, meaningful pieces—simple, fast, and flexible.

Key Features of Chonkie​

  • Lightweight: At just 9.7MB for its base installation, Chonkie minimizes bloat while delivering robust functionality.
  • Lightning Fast: Optimized with pipelining, caching, and parallel processing, Chonkie processes texts at breakneck speed without compromising quality.
  • Feature-Rich: Supports multiple chunking strategies, including TokenChunker, SentenceChunker, SemanticChunker, and even CodeChunker for source code.
  • Flexible: Works with various tokenizers, models, and APIs, and supports both local and cloud-based processing via Chonkie Cloud.
  • Easy to Use: With a simple “Install, Import, CHONK” workflow, developers can get started in minutes.

Chonkie’s chunking strategies are designed to produce reconstructable, independent, and sufficient chunks, ensuring that each piece of text is meaningful, standalone, and optimized for RAG workflows. Whether you’re chunking PDFs, web pages, or code, Chonkie handles diverse data formats with ease, reducing token usage by up to 75%, speeding up response times, and improving model accuracy.

Why Chunking Matters​

Chunking is essential for RAG applications for several reasons:

  1. Context Window Limitations: Large language models (LLMs) have finite context windows, and chunking ensures texts fit within these limits.
  2. Computational Efficiency: Processing smaller chunks reduces computational costs, making queries faster and more memory-efficient.
  3. Better Representation: Independent chunks focus on single ideas, improving model understanding and reducing conflation of concepts.
  4. Reduced Hallucination: Smaller, focused chunks minimize the risk of models generating irrelevant or incorrect responses.

Chonkie’s optimized chunkers, like SemanticChunker and SlumberChunker, leverage advanced techniques such as semantic similarity and generative models to ensure high-quality chunks tailored to specific use cases.

What Can You Use Chonkie For?​

Chonkie is a versatile tool that powers a wide range of RAG and AI applications. Here are some key use cases:

  1. Document Processing for Chatbots: Chunk legal documents, research papers, or user manuals into manageable pieces for precise, context-aware responses.
  2. Code Analysis: Use CodeChunker to break down source code into semantically meaningful units for AI-driven code review or documentation generation.
  3. Web Content Summarization: Process web pages into concise chunks for summarization or question-answering systems.
  4. Knowledge Base Creation: Prepare structured data for vector databases, enabling efficient retrieval for enterprise search or customer support systems.
  5. Multilingual Applications: Combine Chonkie with cloud-based processing to handle diverse languages and formats seamlessly.

By integrating with vector databases and embedding strategies, Chonkie ensures that your data is AI-ready, making it a go-to solution for developers building intelligent, scalable applications.

How Hal9 Complements Chonkie​

While Chonkie excels at preprocessing and chunking, Hal9 takes the baton to streamline deployment, scaling, and visualization of AI applications. Hal9 is a user-friendly platform designed to make AI solutions production-ready with minimal friction. Together, Chonkie and Hal9 form a powerful duo for building robust RAG pipelines.

The Hal9 Advantage​

  • Seamless Deployment: Hal9 simplifies the transition from development to production with a single command, ensuring your Chonkie-powered applications are live in seconds.
  • Scalability: Handle high user traffic without compromising performance, making it ideal for enterprise-grade solutions.
  • Visualization and Debugging: Hal9’s intuitive interface allows you to visualize chunking workflows and monitor performance, ensuring your application runs smoothly.
  • Accessibility: Hal9’s platform is designed for developers of all skill levels, making it easy to integrate Chonkie’s chunking capabilities into complex workflows.

Demonstrating Chonkie in Action: Streamlit App and Chatbot Comparison​

To illustrate Chonkie’s capabilities, we built a streamlit app deployed on Hal9 that allows users to experiment with different chunking strategies and visualize the results. Additionally, we created two chatbots—one using Chonkie for chunking and another using a basic word-based splitting method to compare their performance in a RAG pipeline.

Streamlit App for Chunking Visualization​

The Streamlit app provides an interactive interface to test Chonkie’s chunking strategies. Users can select a chunker (e.g., RecursiveChunker, SentenceChunker, TokenChunker, or SemanticChunker), adjust chunk size and overlap, and input text either manually or by uploading a file (e.g., .txt, .md, or .pdf). The app processes the text using Chonkie’s API and displays the resulting chunks, allowing users to download them as a .txt file.

Chonkie’s Text Chunking Unleashed with Streamlit on Hal9

This app demonstrates Chonkie’s API ease of use and flexibility, allowing developers to experiment with different chunking strategies and see immediate results. You can try it out anc check the code on Hal9’s platform at Chonkie - Streamlit App.

Chatbot Comparison: Chonkie vs. Basic Splitting​

To evaluate Chonkie’s impact, we built two chatbots that process a PDF document, in this case patents file, and answer user queries using a RAG pipeline. Both chatbots use OpenAI’s text-embedding-3-small for embeddings and gpt-4o-mini for response generation, but they differ in their chunking approach:

  1. Chonkie-Powered Chatbot: Uses Chonkie’s SemanticChunker to split the PDF into chunks of 300 tokens with a 30-token overlap. The chunker ensures semantically coherent and reconstructable chunks, optimized for RAG.
  2. Basic Chatbot: Uses a simple word-based splitting function that divides text into chunks of 300 words with a 30-word overlap, without semantic or token-based optimization.

Here’s a snippet of the Chonkie-powered chatbot’s chunking logic:

from chonkie import TokenChunker

def generate_text_embeddings_parquet(url):
chunker = SemanticChunker(
embedding_model="minishlab/potion-base-8M", # Default model
threshold=0.5, # Similarity threshold (0-1) or (1-100) or "auto"
chunk_size=512, # Maximum tokens per chunk
min_sentences=1 # Initial sentences per chunk
)
pdf_document = fitz.open(stream=requests.get(url).content)
chunk_info_list = []
for page_num in range(len(pdf_document)):
page_text = pdf_document[page_num].get_text()
text_chunks = chunker.chunk(page_text)
for chunk in text_chunks:
chunk_info_list.append((chunk.text, page_num))
# Process chunks in parallel to generate embeddings
# ...

In contrast, the basic chatbot uses a naive word-based splitting function:

def split_text(text, n_words=300, overlap=30):
words = text.split()
chunks = []
start = 0
while start < len(words):
end = start + n_words
chunk = words[start:end]
chunks.append(" ".join(chunk))
start += n_words - overlap
return chunks

Key Differences and Benefits​

  • Chunk Quality: Chonkie’s SemanticChunker produces chunks that respect token boundaries and maintain semantic coherence, leading to better embeddings and more accurate retrieval. The basic splitter, relying on word counts, often cuts sentences or ideas abruptly, reducing context quality.
  • Efficiency: Chonkie’s optimized chunking reduces token usage and improves retrieval speed. In our tests, Chonkie-generated chunks resulted in up to 20% faster query responses due to better alignment with LLM context windows.
  • Flexibility: Chonkie supports multiple chunking strategies (e.g., SemanticChunker for meaning-based splits, RecursiveChunker for structured texts like Markdown, NeuralChunker for smartly chunk unstructured plain text and others), while the basic splitter is limited to word-based division.

The Chonkie-powered chatbot consistently provided more relevant and accurate responses, especially for complex queries requiring precise context retrieval. For example, when asked about specific patent details, the Chonkie chatbot retrieved more relevant passages, reducing hallucinations and improving answer quality.

Explore the Chonkie-powered chatbot on Hal9 at PatentPal with Chonkie and compare it to the standard version at PatentPal to experience the difference.

References​

Discovering the New OpenAI Agents SDK

· 6 min read
Generative AI Engineer

Introduction​

In today’s rapidly evolving landscape of artificial intelligence, building agentic applications that are both powerful and accessible is more important than ever. The new OpenAI Agents SDK brings a production-ready upgrade to the experimental era of agents, offering a lightweight, Python-first package that streamlines the development process. With a focus on four core concepts—Agents, Handoffs, Guardrails, and Tracing—this SDK empowers developers to design and implement complex workflows without a steep learning curve. In this post, we explore these key concepts, outline the features that set this SDK apart, and discuss its potential to transform real-world applications.


The Four Core Concepts​

1. Agents​

At the heart of the SDK are Agents—large language models configured with specific instructions, integrated tools, and tailored safety checks. These agents are designed to operate autonomously, carrying out tasks as defined by their programming while maintaining the flexibility to interact with various tools.

Basic Configuration:

  • Instructions: Also known as a developer message or system prompt, these guide the agent’s behavior.
  • Model: Specifies which LLM to use, along with optional model_settings to fine-tune parameters such as temperature, top_p, etc.
  • Tools: Defines the set of tools the agent can leverage to achieve its tasks.
from agents import Agent, ModelSettings, function_tool

@function_tool
def get_weather(city: str) -> str:
return f"The weather in {city} is sunny"

agent = Agent(
name="Haiku agent",
instructions="Always respond in haiku form",
model="o3-mini",
tools=[get_weather],
)

2. Handoffs​

Handoffs introduce a powerful mechanism for collaboration among agents. This feature allows an agent to delegate a specific task or decision to another agent that is better suited to handle it. Imagine a scenario where one agent is focused on natural language understanding while another excels in translation or data processing—the handoff system enables seamless switching of responsibilities, ensuring that each part of the process is handled by the most capable component.

spanish_agent = Agent(
name="Spanish agent",
instructions="You only speak Spanish.",
)

english_agent = Agent(
name="English agent",
instructions="You only speak English",
)

triage_agent = Agent(
name="Triage agent",
instructions="Handoff to the appropriate agent based on the language of the request.",
handoffs=[spanish_agent, english_agent],
)


async def main():
result = await Runner.run(triage_agent, input="Hola, ¿cómo estás?")
print(result.final_output)
# ¡Hola! Estoy bien, gracias por preguntar. ¿Y tú, cómo estás?

3. Guardrails​

Guardrails are built-in, configurable safety checks that run in parallel with your agents, ensuring that only valid and appropriate inputs are processed and acting as an essential first line of defense by filtering out requests that might lead to unintended or malicious use of high-cost resources. For example, imagine you have an agent that utilizes a sophisticated (and consequently slower and more expensive) model to assist with customer requests; you wouldn't want users to exploit this resource for unrelated tasks, such as solving math homework, which could drain resources unnecessarily. By deploying a guardrail that leverages a faster, cost-efficient model, you can quickly validate incoming queries, and if any suspicious or off-target input is detected, the guardrail immediately raises an error to prevent the expensive model from running, thereby saving both time and money while enhancing overall system performance and security.

class MathHomeworkOutput(BaseModel):
is_math_homework: bool
reasoning: str

guardrail_agent = Agent(
name="Guardrail check",
instructions="Check if the user is asking you to do their math homework.",
output_type=MathHomeworkOutput,
)


@input_guardrail
async def math_guardrail(
ctx: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
) -> GuardrailFunctionOutput:
result = await Runner.run(guardrail_agent, input, context=ctx.context)

return GuardrailFunctionOutput(
output_info=result.final_output,
tripwire_triggered=result.final_output.is_math_homework,
)


agent = Agent(
name="Customer support agent",
instructions="You are a customer support agent. You help customers with their questions.",
input_guardrails=[math_guardrail],
)

async def main():
# This should trip the guardrail
try:
await Runner.run(agent, "Hello, can you help me solve for x: 2x + 3 = 11?")
print("Guardrail didn't trip - this is unexpected")

except InputGuardrailTripwireTriggered:
print("Math homework guardrail tripped")

4. Tracing​

Tracing is a built-in feature of the Agents SDK that collects a comprehensive record of every event during an agent run—including LLM generations, tool calls, handoffs, guardrails, and even custom events—to provide deep visibility into your workflows. With a dedicated Traces dashboard, you can easily debug, visualize, and monitor the entire execution process both during development and in production. Each complete workflow is recorded as a trace, which is composed of multiple spans that capture detailed information (such as start and end times, operation details, and metadata) about individual operations like agent execution, LLM responses, and function calls. Tracing is enabled by default, although you have the option to disable it globally via the OPENAI_AGENTS_DISABLE_TRACING environment variable or for a single run by setting RunConfig.tracing_disabled to True; note that it is unavailable for organizations with a Zero Data Retention (ZDR) policy. Additionally, you can group multiple runs under a single trace for higher-level analysis and configure custom trace processors to export data to alternative backends or process it further. This rich tracing infrastructure not only helps you understand and optimize your agent workflows but also ensures that sensitive data can be safeguarded by configuring what is captured, making it an invaluable tool for both troubleshooting and performance tuning.

with trace("Joke workflow"): 
first_result = await Runner.run(agent, "Tell me a joke")
second_result = await Runner.run(agent, f"Rate this joke: {first_result.final_output}")
print(f"Joke: {first_result.final_output}")
print(f"Rating: {second_result.final_output}")

Implementation Example: The Problem Solver Agent​

In this example, we integrate all four core concepts—Agents, Handoffs, Guardrails, and Tracing—into one powerful "Problem Solver Agent". This agent is designed to intelligently decide whether to execute Python code for computational queries or to provide a direct text explanation for general questions. A smart guardrail assesses the query’s nature: if it’s computational, the task is delegated to a dedicated Python Executor Agent; if not, the agent responds directly. This approach combines the sophistication needed for high-level tasks with the simplicity that keeps your code easy to understand and maintain.

Curious to see our Problem Solver Agent in action? Try out our interactive demo and experience its capabilities firsthand at Try the Problem Solver Agent.

Interested in the details? Explore the complete implementation on GitHub and customize it to fit your needs at Hal9 Problem Solver Repository.


Conclusion​

This library strikes the perfect balance between advanced functionality and ease of use. It enables you to build sophisticated, high-level applications—like our Problem Solver Agent—while keeping your code clean and accessible. By seamlessly integrating dynamic agent behavior, smart handoffs, robust guardrails, and detailed tracing, this framework offers a versatile foundation that scales from simple text explanations to complex computational tasks. Whether you're developing a dedicated problem solver, a custom chatbot, or another intelligent tool, this solution provides the power you need without sacrificing clarity or maintainability.

References​

Solving Math Problems with Precision: Python Code Execution with E2B and Hal9

· 4 min read
Generative AI Engineer

Overview​

In the world of large language models (LLMs), generating accurate and precise answers to math problems can be challenging due to hallucinations and inherent limitations in numerical reasoning. By integrating Python code execution into the LLM workflow, we can greatly enhance precision and reliability. This guide demonstrates how to combine the power of E2B’s sandboxed Python execution with Hal9 to create a robust Math Problems Resolver.


Build a Math Resolver step by step​

1. Environment Setup and Initialization​

The first step involves setting up the required environment by importing necessary libraries, loading environment variables, and initializing API clients. This ensures that both Hal9 and E2B are ready to work together.

from e2b_code_interpreter import Sandbox
from dotenv import load_dotenv
from openai import OpenAI
import os
import json
import hal9 as h9

load_dotenv()

E2B_API_KEY = "YOUR E2B API KEY"

if E2B_API_KEY == "":
print("You need to register in e2b -> https://e2b.dev/ and get your API key to use this chat")
else:
# Initialize OpenAI client with Hal9 proxy
openai_client = OpenAI(
base_url="https://api.hal9.com/proxy/server=https://api.openai.com/v1/",
api_key=os.getenv("HAL9_TOKEN")
)

2. Defining the Python Code Execution Tool​

To enable LLMs to execute Python code, we define a tool that describes the functionality required to run code snippets. This tool bridges the gap between the LLM’s language understanding and actual Python code execution for solving math problems.

# Define tool for executing Python code
tools = [{
"type": "function",
"function": {
"name": "execute_python",
"description": "Execute Python code in a Jupyter notebook cell for solving math problems.",
"parameters": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Python code to compute the math problem."
}
},
"required": ["code"]
}
}
}]

3. Message Management​

The code below demonstrates how to manage the conversation by loading previous messages, setting up an initial system prompt, and appending new user inputs.

# Load previous messages or initialize an empty list
messages = h9.load("messages", [])

# Add initial system message if messages list is empty
if len(messages) < 1:
messages.append({
"role": "system",
"content": "Math Problems Resolver: Ready to solve your math challenges using Python code execution."
})

# Append user input to messages
user_input = h9.input()
messages.append({"role": "user", "content": user_input})

4. Integrating Python Code Execution via E2B Sandbox​

To reduce hallucinations and increase precision in mathematical computations, the LLM can call the execute_python tool. When invoked, the code is executed in a secure E2B sandbox environment, ensuring accurate results and safe code execution.

# Get response from OpenAI with tool usage enabled
response = openai_client.chat.completions.create(
model="o3-mini",
messages=messages,
tools=tools,
tool_choice="required"
)

# Process response and execute tool calls if any
response_message = response.choices[0].message
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
messages.append({
"role": "assistant",
"tool_calls": [{
"id": tool_call.id,
"type": "function",
"function": {
"arguments": tool_call.function.arguments,
"name": tool_call.function.name,
},
}]
})
if tool_call.function.name == "execute_python":
# Execute Python code in a sandbox environment
with Sandbox(api_key=E2B_API_KEY) as sandbox:
code = json.loads(tool_call.function.arguments)['code']
print(f"Python code executed: \n\n ```{code}```\n")
execution = sandbox.run_code(code)
result = execution.text

# Append the execution result to messages
messages.append({
"role": "tool",
"name": "execute_python",
"content": result,
"tool_call_id": tool_call.id,
})
else:
messages.append({
"role": response_message.role,
"content": response_message.content
})

5. Finalizing the Response​

After processing tool calls and executing the Python code, the conversation history is updated and saved. The final response is then generated, ensuring that users receive precise and context-aware solutions to their math problem

# Save messages and get the final response
final_response = openai_client.chat.completions.create(
model="o3-mini",
messages=messages
)

final_response_message = final_response.choices[0].message
messages.append({
"role": final_response_message.role,
"content": final_response_message.content
})
print(final_response_message.content)
h9.save("messages", messages)

The Power of Python Execution in Math Problem Solving​

By integrating Python code execution into the LLM workflow:

  • Precision is Enhanced: Executing actual code reduces the risk of hallucinated results, especially in complex math computations.
  • Reliability is Boosted: The E2B sandbox provides a safe and controlled environment to run code, ensuring that the results are accurate.

Experience the power of integrating Python code execution with LLMs. Whether you're tackling complex equations or simply exploring math problem solving, this setup is designed to deliver reliable results. Try it here.

Complete code on GitHub: Hal9 e2b Repository.


Conclusion​

The fusion of E2B’s secure Python code execution and Hal9’s interactive chat interface provides a groundbreaking approach to reducing hallucinations in math problem solving. By executing code on-demand, this system bridges the gap between language models’ conversational abilities and the precision of programmatic computation.

References​

Vibe Coding a Product in 6 Days

· 7 min read
Maintainer of Hal9

Recently, we launched Hal9 Reply, a Chrome extension powered by the Hal9 Platform. Curious how we built the product, website, and marketing in just six days?

The answer? vibe coding——a fast, AI-driven method we jokingly call the cocaine of prompt engineering. Bonus: this blog post was vibe coded too. Let me walk you through it.

How do we know it took exactly six days? The Hal9 team, especially the founders, track every minute using Clockify: We start the timer when a task begins and stop it when it’s done. That’s how we clocked 16 hours building the extension, 16 hours on the website, and 14 hours on marketing efforts like the Product Hunt launch and Hal9's LinkedIn posts.

Vibe Coding Time Tracking

Vibe Coding the Product​

Market Research​

Our journey started with a simple idea: build something for social media managers. That was the extent of our initial creative spark—everything else was vibe coded. We kicked off by asking Grok:

What are the work tasks that people have to do in social media and hate?

The response from Grok (see transcript here), sparked the idea. Social media managers drown in repetitive engagement tasks—responding to comments, messages, and mentions. They hate the grind, especially when overwhelmed. That’s when it hit me: a Chrome extension to lighten the load.

The Grok conversation dug into personas like the “Overworked Manager” and “Big-Name Influencer,” revealing a pain point: too many replies, not enough time. One follow-up question—“When they’re overwhelmed with replies, what Google searches would they do?”—led to insights like “tools to manage social media comments quickly.” Bingo. Hal9 Reply was born: a side panel to display context from the page, helping managers craft faster, smarter replies.

Frontend Code​

Next, I needed a starting point. I scoured the web and found a Chrome extension template on GitHub (this side panel sample). Simple HTML, a bit of JS—perfect.

I copied it, pasted it into ChatGPT, and asked:

Make this show the text from 5 levels up when I focus on a textbox.

The development process was iterative—errors like “Extension context invalidated” surfaced—but after adjusting the manifest and adding tab-specific logic, we nailed it. The final version captures context from ancestors and previous siblings, stops at the body tag, and skips hidden elements like scripts. It took about 4 hours to get it running, though unpolished.

The next 12 hours went into testing and refinement. We tested completion across multiple websites, fixed issues as they came up, and polished the UX to perfection. Highlights include a slick animation and a breathing effect during text completion. The result? A flawless product, now live in our Hal9 GitHub repo.

Total time: 14 hours, resulting in an extremely polished final product. But hold on—the backend was still missing, and we had just two hours left!

Backend Code​

Need a backend? At Hal9, we’ve got you covered! You can create and deploy a Python chatbot in just 10 seconds. Here’s how: Head to the Hal9 Platform, click the "Create" tab, and then "Create" button. Done! You’ve got a Python chatbot—editable and deployable from GitHub.

This chatbot comes with an API which we hooked into the extension frontend code with the following:

async function completeText(text) {
const url = 'https://api.hal9.com/api/v1/chats/message';
const body = { path: 'apps/chrome', message: text };

const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', apikey: '' },
body: JSON.stringify(body),
});

return (await response.json()).message;
}

But the initial replies? The page context was too long, and the bot struggled to respond accurately. The fix? A quick vibe-code session with a simple RAG (Retrieval Augmented Generation—a method to boost AI accuracy with targeted data retrieval) approach. RAG enhances AI performance using focused Python code. No need to dig through Hal9’s docs—we used this prompt instead:

Create a Hal9 chatbot in Python that takes a page context as input, asks OpenAI to identify the last user comment in that context, then calls OpenAI again to generate a reply to it.

The generated code was solid, but we wanted speed. So, we swapped OpenAI for Groq—yes, with a Q. Groq’s custom AI chip delivers faster LLMs.

Here’s the final code. Feel free to click the 'deploy' button and push it to Hal9 to try it—it’s that easy.

import os
from groq import Groq

client = Groq(base_url="https://api.hal9.com/proxy/server=https://api.groq.com/", api_key = "anykey")
model = "llama3-70b-8192"

context = input()

prompt = f"""Given the following website:

```
{context[-8192:] if len(context) > 8192 else context}
```

What is the conversation about and what was the last comment?
"""

messages = [
{"role": "system", "content": "Your main goal is to reply as a human, you are a human."},
{"role": "user", "content": prompt}
]

completion = client.chat.completions.create(model = model, messages = messages)
last = completion.choices[0].message.content

messages.append({ "role": "assistant", "content": last })
messages.append({ "role": "user", "content": "Given the last comment, what's a reasonable comment that anyone might reply to, related to the last comment only? Reply only with comment in the language of the conversation" })

completion = client.chat.completions.create(model = model, messages = messages)

print(completion.choices[0].message.content)

Vibe Coding the Website​

For the website, I wanted something epic—an homage to HAL 9000 from 2001: A Space Odyssey. Picture a 3D background with a glowing, pulsating Hal9000-like shape. But with only 6 days, building that from scratch was out of the question. So, I turned to Grok with this prompt:

Create a single page HTML file with a super cool 3D background built on three.js

The process was iterative brilliance (check the evidence). Grok spat out a Three.js setup with a flat donut (not a torus) and custom shaders for pulsating glow. That shader magic—pumping out a gradient from black edges to a vibrant raspberry color would’ve taken me 4-8 hours alone, at least! With Grok, I nailed it in minutes.

With Grok, we hit a Content Security Policy error blocking Three.js, but Hal9’s platform saved the day by letting me finalize it there.

Vibe Coding 3D Shaders

The result? A fixed-canvas, white-background masterpiece with a breathing donut and glowing particles, all scaling perfectly to the viewport (see it live). I plugged it into our Vue-based main site, added some fade-in animations for product listings (odd left, even right), and called it done—16 hours total.

Vibe Coding the Marketing​

With the product and website ready, we needed a marketing video—fast. Our solution? Animate the website, add background music, and throw in a voice-over. Done.

For animations, we used Vue. Here’s a sample fade-in effect from the process (transcript reference):

<transition name="fade">
<span>
<a href="https://www.sciencedirect.com/science/article/abs/pii/S0747563212001203">Studies</a>
show that engaging with your community with quick replies can
<b>strengthen relationships and drive word-of-mouth growth</b>.
</span>
</transition>

<style>
.fade-enter-active {
transition: opacity 1s ease-in-out;
}
.fade-enter {
opacity: 0;
}
</style>

The voice-over came from ElevenLabs with this prompt:

British accent female with upbeat happy and fast voice, a bit sassy

We screencammed the animated website, layered in the voice-over and music, and that became our launch video. From there, vibe coding carried us through the launch. Grok whipped up a Product Hunt page draft, then we used Hal9 Reply to respond to early feedback, and I churned out LinkedIn and Twitter posts.

The final touch? This blog post. I started with a rough draft, fed it to Grok with “Polish this and fill in the TODOs” and iterated until it flowed.

Conclusion​

In just 6 days, we turned a vague idea into a launched product, complete with a stunning website and marketing materials—all thanks to vibe coding. Tools like Grok and Hal9 supercharged our workflow, proving that AI can be a game-changer for rapid development. Want to build something fast? Vibe coding might be just what you need.

And the Web is Fun Again: With Browser Use and Hal9

· 13 min read
Software Engineer

There just never is enough time. At work, there isn't; there's just always more you'd like (or have to) do than fits in a working day. And in private life, there most definitely isn't, either; no wonder utopians have always dreamt of equally distributed, socially just, and diligently optimised labour that would leave a bigger share to spare time than current societies do.

One important part of freeing up time is automation. At Hal9, we care not just about creative, domain-adaptable solutions, but thought- and careful (not just "intelligent"!) automation, as well. Not everything should be automated; and even when full automation is desirable, we may have expectations the automated workflow must fulfill. For example, we may require auditing; we'd thus need every decision the algorithm makes, every decision it takes, documented. But that may not be our only demand. There likely are decisions we want to make; for example, how cookie consent forms should be handled. In a nutshell, our "sourcerer's appentice" the AI, while useful, should always stay under control, and be just as transparent as we require.

Enter browser-use, a well-crafted, configurable, highly customisable and extensible browser automation tool. In this post, we'd like to show an example of how it nicely integrates with Hal9, addresses exigencies such as as those mentioned above, and may easily be extended. You'll also see its attempts (sometimes successful, sometimes not) to reach a goal in a different way, once some previous strategy has failed. And when it's finished, it automatically creates an animated gif showing you how it proceeded.

Animated gif illustrating all major steps browser-use has gone through

To start, I am going to tell you what I asked it to do, and display a few screenshots to illustrate its behavior; then, we'll go through the code. Besides what's necessary to execute a task, our sample use case also entails custom configuration as well as custom functionality, designed to offer a peek into what is possible (and maybe, inspiring you to experiment with browser-use and its Hal 9 integration for your own interests or demands).

Here is the sample task. It's comprised of five subtasks, some themselves composite. Different kinds of capabilities are involved; they range from technical (taking a screenshot, recording a video) to reasoning, reasoning that itself presupposes image understanding and background knowledge ("Judging from wind direction at 500mb, is there a high or a low in Seefeld?"). And, to mention the maybe obvious — throughout, the software needs to be able to navigate web pages, in a way that surpasses mere html parsing considerably.

Go to meteoblue.com to get the weather forecast for Seefeld, Austria. There, check out the MultiModel forecast. What weather models are part of the ensemble used? Save their names to multimodel.txt. Tell me the exact location you saved that file to. While you're there, find the current wind animation for Seefeld at height 500mb. From what direction is it blowing? How strong is it? Judging from wind direction at 500mb, is there a high or a low in Seefeld? Create a screen recording of the current wind animation, as of height 500mb, and save that movie as wind500.avi. Next, still for Seefeld, go to the seasonal forecasts. What is the temperature anomaly expected for February? How about the precipitation? Now for March, zoom out so you can see the expected temperature anomaly for the whole world. Summarize what you see in a short paragraph. Take a screenshot and save it as temp-anomaly-202503.png. Next, again focus on Seefeld. Among the "outdoor and sports" forecasts, find the one for snow. On what day of the week do we expect most snowfall? Finally, I would like to integrate a weather maps widget into my website. The following maps should be available: wind animation, satellite, clouds & precipitation, and temperature. Post here the html needed to accomplish this.

In the Hal9 browser-use chatbot, I directly enter this text and press enter. And the bots starts to work:

browser-use chatbot starting to work on user-supplied task

We can now follow what it is doing. We see how it keeps track of outstanding tasks, and how it tries other strategies if previous ones were unsuccessful. (It doesn't happen in this run, but during experimentation I've also seen it google for the correct link if it didn't manage to reach a page using site navigation.)

example of browser-use chatbot churning along, keeping track of outstanding tasks and trying different strategies

Finally, the bot having handled all subtasks, we get a summary, comprising both textual answers and location of files created.

browser-use chatbot final summary, indicating locations of files created and answering user questions

How are these results? The screenshots and video currently are not optimal (on my machine, at least), but that is a technical and thus, transient and solvable question. (We didn't want to delay this post, depriving you of such fascinating options, until everything works to perfection. All the more since browser-use is under very active development, with 34 releases since the initial one in November, 2024, and already more than sixty contributors!)

Zooming in on the non-technical aspects, then, how satisfying is the outcome?

First, the file multimodel.txt contains the names of all models that are part of the multi-model forecast; so that answer is correct. Second, the seasonal forecast for March (a contour map, employing colors to designate different levels of warming) has been correctly interpreted. Third, it is correct that Seefeld is part of a "low-pressure system", as the LLM calls it. In fact, I had expected a different rationale, based on direction of rotation (visible very nicely on the wind-animation map); but in any case, the answer is correct. (In fact, Seefeld is not just part of any "low-pressure" system; the polar front and, best visible on the 250mb map though, the jet stream run directly through that area).

For the remaining two, the outcomes are not exactly satifying. The iframe source will include more maps than I want to display — note I said "the following maps should be available", not "included". The user is thus left with an outstanding question to be solved. The second issue jumps directly to the eye. I asked for the day with most snowfall; I am told that "expected day of maximum snowfall in Seefeld has been determined successfully".

Both of these are problems with the LLM, not with browser-use. In fact, both have happened to me during experimentation; below, I'll show you how I try to address them. "Try to address", since this run evidently proves unsuccessful in that respect; in most other runs though, the customisation you'll see below did work. It's just a fact that usage of LLMs always results in some degree of indeterminism.

Now, let's step through the code. I'm not going to comment on every detail, but focus on the "main plot" instead. In some cases, code comments will provide further detail, refer to restrictions, or give pointers to related materials.

Here, first, are the imports.

# import hal9
import hal9 as h9

# import Python packages
import subprocess
import asyncio
import sys
import os
import shutil
import numpy as np
import cv2
from dotenv import load_dotenv

# use OpenAI as LLM
from langchain_openai import ChatOpenAI

# browser-use imports
from browser_use import Agent, Browser, BrowserConfig, SystemPrompt, ActionResult
from browser_use.browser.context import BrowserContextConfig, BrowserContext
from browser_use.agent.service import Agent
from browser_use.controller.service import Controller

# temporarily use pyautogui until https://github.com/browser-use/browser-use/issues/714 has been solved
import pyautogui
# grant display access permission needed for screenshot
# will be needed when switching to BrowserContext.take_screenshot()
# import base64 as b64

Next, finish setup. The second step is required, since browser-use utilises Playwright, a framework for automated web testing. The first is about authorizing the application user to access the screen, such that screenshots may be taken. On Linux, this is required; if you use MacOS or Windows, you will have to test, and possibly find out how to grant that permission.

# tested on Linux - users of other OSes will need to find out
# whether it's required, and what works there
response= subprocess.call(["xhost", "+local:"], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if response != 0: sys.exit("Couldn't authorize local users to access screen.")

response = subprocess.call(["playwright", "install"], stdout = subprocess.DEVNULL, stderr = subprocess.STDOUT)
if response != 0: sys.exit("Couldn't install playwright!")

Set a few variables. The browser size variables will be commented on shortly.

# use these when reverting to BrowserContext.take_screenshot()
#browserWidth = 640
#browserHeight = 360
browserWidth = 2560
browserHeight = 1440

dir = './output-files/'
if os.path.exists(dir):
shutil.rmtree(dir)
os.makedirs(dir)

Now, we come to the fun stuff. There are two types of customization I have made. The first is extending the system prompt. browser-use comes with a detailed system prompt, encompassing, among others, rules for website navigation, image processing, and response format. We can conveniently extend the SystemPrompt class, adding our own rules.

Here, I'm adding three rules, one related to custom functionality, and two that are based on issues I encountered during experimentation.

The latter two are rules 9 and 11. One thing that happened to me was being left with a link, not an answer. Having added rule 9, I never ran into this anymore. However, the rule was also meant to ensure I get what I want when I ask about website integration (the iframe code). Specifically, I added "EXACTLY" to the phrase that, before, was about completeness only. And sometimes, this did work out; in others, it did not.

The other one turned out essential for getting this to work. Initially, when the bot had exceeded the (configurable) number of tries to achieve a goal, it would simply give up on the whole task — irrespectively of whether remaining subtasks were dependent on that one or not. After adding rule 11, this did not happen anymore.

Rule 10 is different. I want to have screenshots taken and a movie recorded; to that purpose, I provide functions that implement the desired functionality. In such a case, we need to inform the LLM explicitly which function to utilise.

class CustomPrompt(SystemPrompt):
def important_rules(self) -> str:
# Get existing rules from parent class
existing_rules = super().important_rules()

# Add your custom rules
new_rules = """
9. IMPORTANT FOR TEXTUAL ANSWERS:
- Make sure you answer a question EXACTLY and COMPLETELY.
For example, if you are asked to enumerate a list of entities fulfilling some condition, list each and any of them.
Always do actually provide the information you are asked for - never just post a link instead.

10. IMPORTANT FOR FILES YOU ARE ASKED TO CREATE:
- When you are asked to create a file, save it making use of the save_path you are given.
- You may be asked to create different types of files: text files, screenshots, and recordings.
- Screenshots should be saved as .png.
- Recordings should be saved as .avi.
- When asked to save content to a text file, make use of the function save_to_text_file.
- When asked to create a screenshot, make use of the function create_png.
- When asked to create a screen recording, make use of the function create_avi.

11. GENERAL RULE REGARDING SUBTASKS:
- When you are given a task involving several subtasks, and one of the subtasks fails, assess whether the other ones are dependent on its success.
Do this for each subtask individually. If a subtask can be addressed without that prior one having been successfully, ALWAYS execute it.
In other words, ONLY EVER skip a subtask if its requirements are not given.
"""

# Make sure to use this pattern otherwise the existing rules will be lost
return f'{existing_rules}\n{new_rules}'

The second customization in my code is, as you may already have expected by now, an extension that adds screenshotting and screen-recording facilities. Such extensions, you'll see, are equally straightforwardly incorporated into browser-use.

We create a Controller instance, and annotate custom functions with actions descriptive of what they we intend them to get used for. The first such function is for saving text files in the directory where we want them to appear:

controller = Controller()

@controller.action('Save to text file')
def save_to_text_file(text_content: str, save_path: str = './output-files/text.txt'):
with open(save_path, 'w') as f:
f.write(text_content)
return ActionResult(extracted_content = f'Text {text_content} written to {save_path}.')

Next, on to screenshots and screen recordings. The code displayed below is a temporary workaround for an — in theory — better-working one, calling browser-use's own BrowserContext.take_screenshot() function. The problem with using pyautogui.screenshot() in this context is that, for one, the screenshot taken comprises the whole screen, not just the Playwright browser — this is why, above, I was employing the "hack" of setting the size of the Playwright browser to my laptop's screen size. And second, the screenshot will be taken of whatever application (or browser tab) is in the foreground in just that very moment. (These issues are, in principle, solvable in some way, but unless your use case is very urgent, time might more productively be spent resolving the problem with take_screenshot().)

What I just detailed holds analogously for save_to_avi(), since a recording here is nothing else than a sequence of screenshots.

@controller.action('Create screenshot') 
async def save_to_png(description: str, save_path: str = './output-files/screenshot.png'):
# temporarily use pyautogui until https://github.com/browser-use/browser-use/issues/714 has been solved
pyautogui.screenshot(save_path, region=(0, 0, browserWidth, browserHeight))
return ActionResult(extracted_content = f'Screenshot for {description} written to {save_path}.')

# following https://www.geeksforgeeks.org/create-a-screen-recorder-using-python/
@controller.action('Create recording')
async def save_to_avi(description: str, save_path: str = './output-files/recording.avi'):
resolution = (browserWidth, browserHeight)
codec = cv2.VideoWriter_fourcc(*"XVID")
fps = 10.0

out = cv2.VideoWriter(save_path, codec, fps, resolution)
cv2.namedWindow("Live", cv2.WINDOW_NORMAL)

remaining = 1 * int(fps)
while (remaining > 0):
img = pyautogui.screenshot(region=(0, 0, browserWidth, browserHeight))
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(frame)
remaining -= 1

out.release()
cv2.destroyAllWindows()
return ActionResult(extracted_content = f'Recording for {description} written to {save_path}.')

Now, for the main browser-use functionality. The first snippet is hardly worth its own exhibit when BrowserContext.take_screenshot() is used.

# only in pyautogui version 
browser = Browser(
config=BrowserConfig(
# for available options see
# https://github.com/browser-use/browser-use/blob/5d1197e5d3b8b7d191aac638b052007882504040/browser_use/browser/browser.py#L178
extra_chromium_args = [f'--window-position=0,0, --window-size={browserWidth},{browserHeight}'],
)
)

# once we return to BrowserContext.take_screenshot()
# browser = Browser()

Neither is the following snippet required if no custom configuration is needed.

config = BrowserContextConfig(
browser_window_size = {'width': browserWidth, 'height': browserHeight},
save_recording_path = "./output-files/",
)

context = BrowserContext(browser = browser, config = config)

Finally, for that part of code that is required. (Well, apart from the print() statements, it is; and with just two arguments passed to Agent().

async def run(agent):
print("🌍🌎🌏")
print("Working!")
print("Here you can see what I'm doing. When I'm done, I'll provide the answers to all your questions in order.")
history = await agent.run()
return history

async def main():
prompt = h9.input()
agent = Agent(
browser_context = context,
controller = controller,
system_prompt_class = Save_Files,
# these two arguments are needed
task = prompt,
llm = llm,
save_conversation_path="logs/conversation.json"
)
history = await run(agent)
await browser.close()

asyncio.run(main())

You can try a simpler demo from /apps/browseruse and check out the code in our GitHub repo.

And that's it! I hope this writeup has given you an idea of just how many things you could get done for you this way. Automating away some of the nuisances of life is just one aspect; another type of task (one my example is merely a feeble preview of) would be to have browser-use automate information retrieval, and then make use of the LLM to obtain a detailed analysis. And all that, if you like, seemlessly integrated into the chatbot infrastructure afforded by Hal9!

PDF Chatbot with LangChain and Hal9: A Step-by-Step Guide

· 5 min read
Generative AI Engineer

Overview​

LangChain is a powerful framework designed to simplify the integration of Large Language Models (LLMs) into applications. It provides developers with modular tools and pre-built components for tasks like document analysis, summarization, chatbots, and even code analysis. By offering a robust pipeline for chaining LLM-powered steps together, LangChain allows developers to build advanced applications while maintaining flexibility and control.

When combined with Hal9, a platform that streamlines the deployment and creation of chatbots while offering access to a wide variety of models, developers gain the ability to rapidly build and deploy intelligent, scalable solutions. This guide demonstrates how these tools can be used together to create a chatbot that interacts with PDF documents.


PDF ChatBot Workflow​

1. Input Handling​

When a user interacts with the chatbot via Hal9’s chat interface, uploaded documents are received as URLs on the Python side. The chatbot determines whether the input is a document URL or a question related to previously loaded data. If it’s a document, the content is parsed and stored for future interaction; otherwise, the chatbot uses existing data to generate a response or provides a general answer

user_input = h9.input()
# Check if the user input is a file URL (e.g., uploaded via Hal9 interface)
if h9.is_url(user_input):
# Process the file and store extracted content for later use
pass
else:
# Handle the query by retrieving context or generating a generic response
pass

2. Document Processing and Storage​

The process of extracting, storing, and referencing document content is made efficient through LangChain’s flexible document loaders. For instance, when handling a PDF file, we utilize the PyMuPDFLoader to load the document’s text and store it for later use.

LangChain provides various document loaders, which allow integration with multiple data sources like PDFs, CSVs, and others. Once the document is loaded into memory, it's serialized and saved using Python's pickle module, ensuring persistence across sessions. This enables the chatbot to quickly reference previously loaded documents.

def save_documents(documents, file_path):
with open(file_path, "wb") as f:
pickle.dump(documents, f)

loader = PyMuPDFLoader(user_input)
documents = loader.load()

save_documents(documents, documents_file)

3. Embeddings, Chroma, and Context Retrieval​

To enable efficient retrieval of relevant information, document content is transformed into embeddings—numerical representations that capture semantic meaning. Using OpenAIEmbeddings model from LangChain integrated with Hal9’s API, these embeddings allow the chatbot to compare and rank document sections by their relevance to a user's query. Chroma, an AI-native vector database, stores these embeddings, providing a scalable and efficient way to manage and search through large collections of documents.

When a user submits a query, Chroma performs a similarity search across the stored embeddings to identify the most relevant document sections. The results are then formatted into a cohesive context that the chatbot can use to generate accurate and context-aware responses.

embeddings = OpenAIEmbeddings(openai_api_base="https://api.hal9.com/proxy/server=https://api.openai.com/v1", api_key=os.environ['HAL9_TOKEN'], model="text-embedding-3-large")

db = Chroma.from_documents(documents, embeddings)

docs = db.similarity_search(user_input, k=6)

formatted_context = "\n".join([doc.page_content for doc in docs])

4. Selecting LLMs and Generating Responses​

The Hal9 platform allows seamless integration with multiple language models and providers, such as LLaMA from Groq, R1 from DeepSeek, and OpenAI’s GPT models. By combining Hal9’s capabilities with LangChain’s ChatOpenAI class, developers can easily access and invoke these diverse models to generate responses. This flexibility empowers users to tailor their applications to specific use cases, optimizing for factors like speed, accuracy, or model capabilities.

In the code example below, we demonstrate how to configure the ChatOpenAI class to interact with these models. Here, we choose Groq + LLaMA for its exceptional speed, but you can experiment with other models by adjusting the configurations as shown

# Configure the model with Hal9's API and desired provider
llm = ChatOpenAI(base_url="https://api.hal9.com/proxy/server=https://api.groq.com/openai/v1", api_key=os.environ['HAL9_TOKEN'], model="llama-3.1-8b-instant")
response = llm.invoke(messages) # Generate a response using Groq + LLaMA

# To switch to OpenAI GPT-4 or DeepSeek R1, change the base_url and model parameters
llm = ChatOpenAI(base_url="https://api.hal9.com/proxy/server=https://api.openai.com/v1/", api_key=os.environ['HAL9_TOKEN'], model="gpt-4-turbo")
llm = ChatOpenAI(base_url="https://api.hal9.com/proxy/server=https://api.deepseek.com", api_key=os.environ['HAL9_TOKEN'], model="deepseek-reasoner")

5. Message History Management and Persistence​

To maintain conversational continuity, the chatbot needs to track and store the interaction history. Hal9 simplifies this process by offering save and load functions that allow seamless management of message histories. Every user interaction is appended to a list of messages, which is then saved persistently.

This history is passed to the ChatOpenAI function during each invocation, ensuring the model has the necessary context to generate responses that align with the ongoing conversation.

messages = h9.load("messages", [])
messages.append({"role": "system","content": "You are an assistant designed to..."})
messages.append({"role": "human", "content": user_input})
messages.append({"role": "assistant", "content": response})
h9.save("messages", messages, hidden=True)

Explore the Results​

Ready to see the chatbot in action? Test it out by uploading a PDF or sharing a link to experience its capabilities firsthand. Click here to test the chatbot.

Want to dive deeper? Access the full implementation and customize it to your needs by exploring the code on GitHub: Hal9 LangChain Repository.


Conclusion​

Integrating LangChain with Hal9 opens up new possibilities for building sophisticated, PDF-interacting chatbots. This combination leverages LangChain’s modularity and robust document handling capabilities alongside Hal9’s streamlined deployment and multi-model support. By utilizing embeddings, vector databases like Chroma, and flexible LLM integration, developers can create chatbots capable of delivering precise, context-aware responses. The workflow, from input handling to response generation, ensures scalability and adaptability to various use cases, making this setup an ideal choice for applications that demand intelligent document interaction. Whether you're developing a research assistant, legal document analyzer, or customer support tool, this guide provides a strong foundation to get started.

References​

PDF Chat Agent with DSPy and Hal9

· 7 min read
Generative AI Engineer

Harnessing DSPy for Simplified AI Programming​

In the world of Large Language Models (LLMs), DSPy emerges as a game-changer for programming, focusing on abstraction rather than low-level prompt engineering. Unlike traditional approaches that require manually crafting complex prompts, DSPy lets you describe tasks naturally using signatures—declarative specifications of inputs and outputs. This allows for easier program construction without getting bogged down in prompt formatting or manual adjustments.

With DSPy, you can build advanced AI-powered systems like a PDF chat agent with much less effort, shifting the focus from managing prompts to constructing modular, efficient AI programs. This post will demonstrate how to leverage DSPy’s powerful modules to create a document-interacting chatbot, while using Hal9’s robust infrastructure to deploy and interact with OpenAI's LLMs effortlessly.


DSPy Fundamentals​

Signatures: Simplifying Tasks​

At the heart of DSPy are signatures, which specify what an LLM should do in plain language. Instead of manually crafting detailed prompts, you declare the task’s input and output types. For example:

'sentence -> sentiment: bool'
'document -> summary'

This high-level abstraction allows you to focus on the desired behavior rather than the exact phrasing of the prompt. The power of signatures lies in their simplicity and adaptability, which make them an excellent tool for developers who want to interact with LLMs without needing to know the intricacies of prompt engineering. With DSPy, you can specify what you want—whether it’s summarizing a document or extracting sentiment—and let the framework handle the underlying complexity.

Modules: The Building Blocks​

Once you've defined your task with a signature, DSPy uses modules to handle different prompting techniques. These modules abstract away the details of the interaction, offering an easy way to apply complex prompting strategies.

Modules can incorporate advanced techniques like Chain of Thought (CoT) or ReAct, allowing you to tailor the prompt's behavior for specific tasks. For example, if you need reasoning steps for a complex task, you might use the Chain of Thought module, which helps the LLM break down the problem into smaller, manageable pieces.

DSPy also offers flexibility by enabling you to create custom modules to suit more specialized use cases. These modules work as building blocks that can be connected together to form more complex pipelines.

Chain of Thought: Structured Reasoning​

One key module, Chain of Thought, facilitates structured reasoning, which can enhance the performance of the model for complex tasks. This method allows the LLM to think step-by-step before generating an answer, reducing errors that might arise from direct responses. For example, when asked a complex question, the LLM may break the process into logical steps, providing a more comprehensive response.

By using Chain of Thought, you can enable the model to deliver responses with more nuance and accuracy, perfect for applications requiring deeper understanding or reasoning.

Plugging in Any LLM: Focused on Programming, Not Prompting​

One of DSPy’s key strengths is the ability to integrate any LLM of your choice with ease. In this case, we’ve seamlessly integrated DSPy with Hal9's proxy infrastructure.

lm = dspy.LM('openai/gpt-4-turbo', api_key='hal9', api_base='https://api.hal9.com/proxy/server=https://api.openai.com/v1/')
dspy.configure(lm=lm)

Retrieval-Augmented Generation (RAG)​

RAG combines LLM reasoning with retrieval mechanisms. Instead of relying solely on the model's internal knowledge, RAG searches an external corpus (e.g., document chunks) to retrieve relevant context. This retrieved information is then fed into the LLM for accurate and context-aware answers. DSPy simplifies the creation of RAG pipelines, as you'll see in the implementation.

Building a Document-Interacting Chatbot​

Now that we understand the principles of DSPy, Chain of Thought and RAG , let’s dive into building a simple chatbot that interacts with PDF documents. We’ll break this process down into manageable sections.

Step 1: Text Processing​

Before we can interact with the document, we need to process and split its content into chunks. Here, we’ll extract text from a PDF document, and split it into smaller, overlapping chunks to allow efficient searching.

def extract_text_from_pdf(pdf_url):
response = requests.get(pdf_url)
pdf_document = fitz.open(stream=BytesIO(response.content))
text = "".join([pdf_document[page_num].get_text() for page_num in range(len(pdf_document))])
return text

def split_text(text, n_words=300, overlap=0):
words = text.split()
chunks = []
start = 0
while start < len(words):
chunk = words[start:start + n_words]
chunks.append(" ".join(chunk))
start += n_words - overlap
return chunks

Step 2: Embedding Generation​

We use a custom retriever class that integrates with a vectorizer leveraging Hal9's proxy for OpenAI to generate embeddings, storing them in a FAISS index for efficient retrieval.

The CustomOpenAIVectorizer is used to generate embeddings for document chunks by calling the Hal9-proxied OpenAI API. This vectorizer batches requests to optimize processing time. After generating embeddings, we store them in a FAISS index, either updating or creating a new one based on the provided configuration.

The Hal9_FaissRM class handles both embedding generation and indexing. It ensures that the embeddings are properly stored and can be quickly retrieved using FAISS, which optimizes search efficiency during querying.

from custom_dspy import CustomOpenAIVectorizer, Hal9_FaissRM
import os

# Initialize the OpenAI client with the Hal9 proxy
openai_client = OpenAI(
base_url="https://api.hal9.com/proxy/server=https://api.openai.com/v1/",
api_key=os.environ['HAL9_TOKEN']
)

# Create the vectorizer with the custom OpenAI client
vectorizer = CustomOpenAIVectorizer(openai_client=openai_client)

# Initialize FaissRM
frm = Hal9_FaissRM(document_chunks = chunks, vectorizer = vectorizer, update = True)

Step 3: Setting Up the RAG Module and Response Signature​

First, the signature is defined for the answer generation process, where the context (document passages) and the question are input fields, and the generated detailed answer is the output.

The RAG module consists of two key components: a retriever to fetch the relevant passages based on the question and a Chain of Thought model for generating detailed answers. The retriever fetches context, and the Chain of Thought model generates the final answer by combining the context with the question.

# DSPy Signature
class GenerateAnswer(dspy.Signature):
context = dspy.InputField(desc="Context passages or facts")
question = dspy.InputField()
answer = dspy.OutputField(desc="Detailed and long answer generated referenced on passages")

# RAG module definition
class RAG(dspy.Module):
def __init__(self, num_passages=5):
super().__init__()
self.retrieve = dspy.Retrieve(k=num_passages)
self.generate_answer = dspy.ChainOfThought(GenerateAnswer)

def forward(self, question):
context = self.retrieve(question).passages
prediction = self.generate_answer(context=context, question=question)
return prediction

Step 4: Generate a Response​

Now, we integrate the components into a working example. The user provides a prompt (e.g., a question), and the system uses the updated RAG (Retrieval-Augmented Generation) module to retrieve relevant document chunks and generate a coherent response.

# Configure DSPy
lm = dspy.LM('openai/gpt-4-turbo', api_key=os.environ['HAL9_TOKEN'], api_base='https://api.hal9.com/proxy/server=https://api.openai.com/v1/')
frm = Hal9_FaissRM(document_chunks=chunks, vectorizer=vectorizer)
dspy.configure(lm=lm, rm=frm)

# Initialize RAG and generate a response
rag = RAG()
response = rag(question=prompt)
print(response.answer)

In this flow, DSPy is configured with an OpenAI model and a retrieval module based on the Hal9_FaissRM retriever, which utilizes the Hal9 proxy for embedding generation and FAISS for efficient document chunk retrieval. The RAG module then uses this setup to generate the final answer based on the provided question.

Check the Results​

Curious about how it performs? Try the PDF-interacting chatbot yourself! Upload a PDF or provide a link, and see how it answers questions based on the document's content. Click here to test the chatbot.

Check out the full code on GitHub: Hal9 DSPy Repository.


Conclusion​

DSPy revolutionizes the way we program large language models (LLMs) by shifting the focus from manual prompt engineering to intuitive program design. With its powerful abstractions like signatures and modules, DSPy simplifies the creation of complex systems, such as a chatbot that interacts with documents using Retrieval-Augmented Generation (RAG).

This integration between DSPy and Hal9 showcases how you can develop scalable, modular applications with ease. By following the steps in this blog, you’ve seen how DSPy enables a seamless approach to AI programming, helping developers stay focused on building logic rather than managing prompts.

References​

Smarter Chatbots on Hal9 with Burr: A Step-by-Step Guide

· 7 min read
Data Scientist

When building chatbots, among many others concerns, one often faces three main challenges: stability, precision, and deployment. In this blog post, we'll explore how a new Python framework, Burr, combined with Hal9's capabilities, can make these challenges a thing of the past.

Why these three matter so much:

  • Stability: A stable chatbot ensures consistent performance and reliability, even when handling complex inputs or high user traffic. Instability can lead to frustrating user experiences, which may damage trust in your product.

  • Precision: AI agents frequently hallucinate, which makes accuracy and relevance critical for deploying applications at an industry-ready level.

  • Deployment: getting your chatbot out of the development environment and into production smoothly is often a challenge. Deployment should be seamless, scalable, and adaptable to your existing infrastructure.

Introducing Burr​

Burr is a lightweight Python framework for building tool-using AI agents, simplifying the creation of chatbots that can interact with APIs, databases, or custom tools. With Burr, you can:

  • Quickly prototype, test and debug agents with minimal effort.

  • Integrate external tools and APIs seamlessly.

  • Build multi-step workflows for more complex tasks.

  • Visualize the decisions each agent makes and see how they communicate to each other.

By combining Burr with Hal9's user-friendly platform for deploying AI-powered solutions, you can build chatbots that are not only intelligent but also robust and production-ready.

The Hal9 Advantage​

When you pair Burr with Hal9’s powerful AI deployment platform, you unlock a streamlined path to creating production-ready chatbots. Hal9 makes it easy to:

  • Deploy with Confidence: Transition seamlessly from development to production with minimal friction.

  • Scale Effortlessly: Handle high user traffic without compromising stability or precision.

  • Simplify the Process: Hal9’s platform is designed with accessibility in mind, making it easy to deploy even the most complex agents.

Example: Burr on Hal9​

Let's walk through how to build a simple weather chatbot on Hal9 using Burr. This chatbot can interact with external tools to provide precise and relevant responses to user queries.

1. Set Up Burr​

Start by installing Burr and creating a basic agent.

pip install burr

2. Create Tools​

Next, implement a few tools for the agent to use. In our case, we chose to use OpenWeatherMap's API to fetch weather data. Our tools include:

  • get_current_weather: Fetches the current weather conditions for specified coordinates.

  • get_weather_forecast: Retrieves the weather forecast for the next few days for given coordinates.

  • get_coordinates: Resolves a location name into geographic coordinates (latitude and longitude) to query the weather API accurately.

Each of these tools uses OpenWeatherMap's API to gather precise weather information, whether it's real-time conditions or forecasts.

3. Implement the chatbot's logic with Burr​

With the tools ready, it’s time to define the chatbot’s logic. Burr allows you to construct multi-step workflows where agents can dynamically select and execute the right tools. Below is the full implementation:

Click here to view the full code
import hal9 as h9
import json
from openai import OpenAI
import os

from burr.core import ApplicationBuilder, State, default, expr
from burr.core.action import action

## Import user-defined API functions for the agents to use
from weather_utils import *

client = OpenAI(
base_url="https://api.hal9.com/proxy/server=https://api.openai.com/v1/",
api_key = os.environ['HAL9_TOKEN']
)

## Burr actions are encapsulated, stateless operations triggered by state
## transitions, defined to interact with workflows, models, or external APIs.
@action(reads = [], writes = ['messages'])
def user_input(state: State) -> State:
prompt = input()
message = {
'role': 'user',
'content': prompt
}

return state.update(prompt = prompt).append(messages = message)

@action(reads = ['messages'], writes = ['response'])
def orchestrator(state: State):
system_prompt = (
"You are a helpful agent."
"You work for an app specialized in giving meteorological information to users."
"Your task is to decide if the last users query needs to be answered using the weather API."
"If so, your reply should only be 'API'. If not, you can reply freely to the user."
)
message = {'role': 'system', 'content': system_prompt}

response = client.chat.completions.create(
messages = [message] + state['messages'],
model = 'gpt-3.5-turbo'
).choices[0].message.content

return state.update(response = response)

@action(reads = ['messages', 'prompt'], writes = ['location', 'request_type', 'count'])
def interpret_prompt(state: State) -> State:
system_prompt = (
"You are a geography expert."
"Your task is to find the specific location from where the user is requesting weather data.")

## More left out (big system prompt and response format) for brevity ...

response = client.chat.completions.create(
model = 'gpt-4o-2024-08-06',
messages = state['messages'] + messages,
response_format = response_format
).choices[0].message.content

return state.update(**json.loads(response))

@action(reads = [], writes = ['prompt'])
def ask_location(state: State) -> State:
reply = 'The location is unclear, please try again with a different prompt.'
print(reply)

new_state = state.append(messages = {'role': 'assistant', 'content': reply})
h9.save('messages', new_state['messages'], hidden = True)

return new_state

@action(reads = ["location"], writes = ['lat', 'lon'])
def coordinates(state: State) -> State:
info = get_coordinates(state["location"])[0]
return state.update(lat = info['lat'], lon = info['lon'])

@action(reads = ["lat", "lon"], writes = ["weather_result"])
def current_weather(state: State) -> State:
info = get_current_weather(state["lat"], state["lon"])
return state.update(weather_result = info)

@action(reads = ["lat", "lon", "count"], writes = ["weather_result"])
def weather_forecast(state: State) -> State:
info = get_weather_forecast(state["lat"], state["lon"], cnt = state["count"])
return state.update(weather_result = info)

@action(reads = ["prompt", "weather_result"], writes = ["messages"])
def interpret_result(state: State) -> State:
result = json.dumps(state["weather_result"], indent = 2)
system_prompt = (
"You are an expert meteorologist."
"Your task is to interpret the asistants weather response and reply the requested information to the user."
)
messages = [
{'role': 'system', 'content': system_prompt},
{'role': 'user', 'content': state['prompt']},
{'role': 'assistant', 'content': result}
]

response = client.chat.completions.create(
model = 'gpt-3.5-turbo',
messages = messages
).choices[0].message.content

new_state = state.update(response = response).append(messages = {'role':'assistant', 'content': response})
h9.save('messages', new_state['messages'], hidden = True)

return new_state

@action(reads=['response'], writes = [])
def reply(state: State) -> State:
print(state['response'])

return state

## Now create the app. A simple as adding all actions,
## and defining how they are related to each other!
app = (
ApplicationBuilder()
.with_actions(
user_input,
orchestrator,
interpret_prompt,
ask_location,
coordinates,
current_weather,
weather_forecast,
interpret_result,
reply)
.with_transitions(
("user_input", "orchestrator"),
("orchestrator", "interpret_prompt", expr("'API' in response")),
("orchestrator", "reply"),
("interpret_prompt", "ask_location", when(location = 'uncertain')),
("interpret_prompt", "coordinates"),
("coordinates", "current_weather", when(request_type = 'current')),
("coordinates", "weather_forecast"),
("current_weather", "interpret_result"),
("weather_forecast", "interpret_result"),
("interpret_result", "reply"))
.with_state(
messages = h9.load('messages', [{'role': 'assistant', 'content': "Hi! 🌤️ I'm your weather assistant. Tell me a location, and I'll share the forecast with you! ⛅"}]))
.with_entrypoint("user_input")
.build()
)

app.run(halt_after = ['ask_location', 'reply'])

One of Burr’s standout features is its ability to visualize your chatbot’s flow with just a single line of code. This visualization provides a clear overview of how your chatbot’s tools and actions are interconnected. By running

app.visualize("graph.png")

You’ll generate a graphical representation of the workflow, similar to this:

This feature is invaluable for debugging, optimizing workflows, or simply understanding how your chatbot processes user queries.

4. Deploy to Hal9​

As mentioned earlier, deployment can often be one of the trickiest parts of building a chatbot. But Hal9 eliminates this complexity. With Hal9’s platform, deploying your Burr-powered chatbot is as simple as running a single command in your terminal:

HAL9_TOKEN=ADDYOURTOKEN hal9 deploy . --name weather_chatbot

This command packages your chatbot and makes it production-ready within seconds. Hal9 handles the heavy lifting, so you can focus on refining your chatbot and delighting your users.

With Burr’s intuitive development tools and Hal9’s effortless deployment capabilities, building and launching intelligent chatbots has never been easier.

Test the Weather Chatbot​

Want to see the chatbot in action? We’ve deployed it using Hal9 so you can experience its capabilities firsthand. Click the link below to try it out and see how seamlessly Burr and Hal9 work together: Try the Weather Chatbot on Hal9

Using NVIDIA NIM to Spot AI-Generated Images

· 7 min read
Data Scientist

AI-generated images are proliferating across the internet, manifesting in various forms of art, brand representation, and even fake news. These images, created using sophisticated machine learning algorithms, often blur the lines between authentic and artificial content, presenting themselves as both opportunities and challenges. To overcome these challenges, tools designed to identify AI-generated images, such as some available at NVIDIA NIM, are becoming increasingly vital for both businesses and individuals.

In this blog post, we aim to answer a simple question: How simple is it to create an application that detects AI-generated images using Hal9? The answer is that, writing just a few lines of Python code and by utilizing Hal9’s infrastructure empowered with NVIDIA NIM’s API, you can swiftly develop a robust tool capable of identifying both deepfakes and AI-generated images.

Why Choose Hal9 for Deploying AI Applications?​

Hal9 is designed to simplify the deployment of AI-powered tools and applications, making advanced technologies accessible to businesses and developers. Whether you’re looking to create a chatbot, build a custom app, or integrate AI functionalities into your website, Hal9 offers a streamlined approach that reduces development overhead and maximizes scalability.

Some key advantages of using Hal9 include:

  • Ease of Deployment: Hal9’s infrastructure makes it possible to bring AI models and applications online quickly, without needing extensive backend setup.

  • On-Demand Functionality: From chatbots to analytics tools, Hal9 supports dynamic, user-driven interactions that can be scaled to meet diverse needs.

  • Versatility: Whether you’re deploying simple chatbots or more complex applications leveraging external APIs like NVIDIA NIM, Hal9 provides the flexibility to adapt to your project requirements.

By leveraging Hal9, you can focus on building impactful AI solutions while relying on their robust infrastructure to handle the heavy lifting.

A Practical Example: Detecting AI-Generated Images​

With the surge of AI-generated content flooding the internet—whether in the form of art, advertisements, or even misinformation—there’s an increasing need for tools that can reliably detect these creations. This challenge isn’t just academic; it impacts industries ranging from media and marketing to cybersecurity.

To showcase how easy it is to deploy an AI application with Hal9, we decided to build a tool that detects AI-generated images. This example not only highlights the simplicity of using NVIDIA NIM’s models but also demonstrates how Hal9’s deployment framework enables you to bring advanced AI solutions directly to your audience, whether for content verification, compliance, or user engagement.

Building the AI-Generated Image Detection Tool​

To build our AI-generated image detection tool, we used two Python scripts:

  • A main script that contains all the logic for interacting with the NVIDIA NIM API.

  • A user interface handler script that processes user-submitted URLs and sends them to the main script for analysis.

Main Script: Connecting to the NVIDIA NIM API​

This script implements the core logic for querying the NVIDIA NIM model to detect whether an image is AI-generated. The implementation was adapted from example code provided by NVIDIA, demonstrating how to use their API effectively.

import os
import base64
import requests

from openai import OpenAI
from dotenv import load_dotenv
from image_reading import get_image_data

# Load environment variables from the .env file
load_dotenv()

# Set up authentication headers using the NVIDIA API key
header_auth = f"Bearer {os.getenv('NVIDIA_API_KEY')}"
client = OpenAI(
base_url = "https://integrate.api.nvidia.com/v1",
api_key = os.getenv('NVIDIA_API_KEY')
)

# Function to upload an image asset to NVIDIA's servers if it's too large
def upload_asset(binary):
assets_url = "https://api.nvcf.nvidia.com/v2/nvcf/assets"
headers = {
"Content-Type": "application/json", # Set the content type to JSON
"Authorization": header_auth, # Authentication using the NVIDIA API key
"accept": "application/json",
}

payload = {"contentType": "image/png", "description": "Input Image"}
# Send a request to get the pre-signed URL for uploading the image
response = requests.post(assets_url, headers=headers, json=payload, timeout=30)

current_pre_signed_url = response.json()["uploadUrl"]

headers = {"Content-Type": "image/png", "x-amz-meta-nvcf-asset-description": "Input Image"}

# Upload the image to the pre-signed URL
requests.put(
current_pre_signed_url,
data=binary,
headers=headers,
timeout=300,
)

# Return the asset ID for further use in AI detection
return response.json()["assetId"]

# Function to check if the provided image URL points to an AI-generated image
def is_ai_generated(image_url):
binary = get_image_data(image_url)

# Check if the binary data is empty (error in image retrieval)
# If empty, the user has already been notified of the error
if not binary:
return

# Encode the image in base64 format for API consumption
b64 = base64.b64encode(binary).decode('utf-8')

# If the image is small enough, send it as base64 encoded data
if len(b64) < 180_000:
payload = {"input": [f"data:image/png;base64,{b64}"]}
headers = {
"Content-Type": "application/json",
"Authorization": header_auth,
"Accept": "application/json",
}
else:
# If the image is large, upload it as an asset first
asset_id = upload_asset(binary)
payload = {"input": [f"data:image/png;asset_id,{asset_id}"]}
headers = {
"Content-Type": "application/json",
"NVCF-INPUT-ASSET-REFERENCES": asset_id,
"Authorization": header_auth,
}

# Send the request to NVIDIA's AI-generated image detection API
response = requests.post(
"https://ai.api.nvidia.com/v1/cv/hive/ai-generated-image-detection",
headers=headers,
json=payload).json()['data'][0]

# If the API call was successful, process the response
if response.get('status', '') == 'SUCCESS':
# Sort the possible sources of the image by likelihood and display the top 5
possible_sources = sorted(response["possible_sources"].items(), key = lambda item: -item[1])[:5]
possible_sources = [f'{k.title()}: {v*100:.2f}%' for k,v in possible_sources]

# Output the results to the user
print(f'Probability of being AI-generated: {response["is_ai_generated"]*100:.4f}%')
print('\nPossible sources: ', *possible_sources, sep = '\n - ')
else:
print('There was an error processing the image, please try again.')

# Main function to take user input and start the detection process
if __name__ == '__main__':
url = input() # Prompt the user for an image URL
is_ai_generated(url) # Call the AI detection function

User Interface Handler: Managing User Input​

This second script is a lightweight interface to collect user-submitted URLs, validate them, and pass them to the main script.

import requests

# Function to check if the user uploaded a valid and accessible image URL.
def is_image_url(url: str) -> bool:
try:
# Send a HEAD request to only retrieve the headers for the URL, to avoid downloading the image.
headers = requests.head(url).headers
except Exception as e:
print(f'Please input a valid URL! {e}')
return False

# Check if the user uploaded a valid image file format
valid_formats = ('.jpg', '.png', '.jpeg')

# Check for specific URL format and valid image extensions
if (url.startswith('https://prodhal9.s3.us-west-2.amazonaws.com/') and url.endswith(valid_formats)):
return True

# Ensure the content type is an image
elif not headers.get('Content-Type', '').startswith('image/'):
print('Please upload a link to a valid image!')
return False

# Ensure the image file size is not too large (maximum 5 MB)
elif int(headers.get('Content-Length', 0)) > 5*1024*1024:
print('Images can only weigh up to 5 MB!')
return False

return True

# Function to retrieve the image data if the URL is valid
def get_image_data(url: str) -> str:
# Validate the image URL before proceeding
<