Synthetic Dialogue Generation and Analysis
Project description
SDialog is a modular Python toolkit for synthetic dialog generation, evaluation, and analysis. It standardizes a Dialog schema and offers persona‑driven multi‑agent simulation with LLMs, composable orchestration, built‑in metrics, and mechanistic interpretability—so you can generate reliable, controllable dialog data at scale.
Quick links: Docs • API • Demo (Colab) • Tutorials • Datasets (HF) • Issues
✨ Key features
- Standard dialog schema with JSON import/export (aiming to standardize dialog datasets format with your help 🙏)
- Persona‑driven multi‑agent simulation with contexts, tools, and thoughts
- Composable orchestration for precise control over behavior and flow
- Built‑in evaluation (metrics + LLM‑as‑judge) for comparison and iteration
- Native mechanistic interpretability (inspect and steer activations)
- Easy creation of user-defined components by inheriting from base classes (personas, metrics, orchestrators, etc.)
- Interoperability across OpenAI, HuggingFace, Ollama, AWS, and more
If you are building controlled multi‑agent conversational systems, benchmarking dialog models, producing synthetic training corpora, simulating diverse users to test or probe conversational systems, or analyzing internal model behavior, SDialog provides an end‑to‑end workflow.
⚡ Installation
pip install sdialog
🏁 Quickstart tour
Here's a short, hands-on example where a support agent helps a customer disputing a double charge—we'll add a tiny rule to steer refund behavior and a simple tool to check order status, generate three dialogs for later evaluation, and then serve the support agent on port 1333 for Open WebUI or any OpenAI‑compatible client.
import sdialog
from sdialog import Context
from sdialog.agents import Agent
from sdialog.personas import SupportAgent, Customer
from sdialog.orchestrators import SimpleReflexOrchestrator
# First, let's set our preferred default backend:model and parameters
sdialog.config.llm("openai:gpt-4.1", temperature=0.7)
# sdialog.config.llm("ollama:qwen3:14b") # etc.
# Let's define our personas (use built-ins like in this example, or create your own!)
support_persona = SupportAgent(
name="Ava",
role="Customer Support Agent",
product_scope="Subscriptions and Billing",
communication_style="clear and empathetic",
resolution_authority_level="standard",
escalation_policy="Escalate to Billing Specialist if refund exceptions are requested",
)
customer_persona = Customer(
name="Riley",
issue="Charged twice this month",
issue_category="billing",
issue_description="I see two charges for October on my card",
anger_level="medium",
times_called=1,
desired_outcome="refund the duplicate charge",
)
# (Optional) Let's add a concrete conversational context
ctx = Context(
location="Online chat",
environment="support portal",
circumstances="Billing cycle just renewed",
)
# (Optional) Let's add a simple tool (just a plain Python function) for our support agent
def check_order_status(order_id: str) -> dict:
# In production, connect to your DB or API here
return {"order_id": order_id, "status": "paid", "last_charge": "2025-10-01"}
# (Optional) Let's include a small rule-based orchestrator
react = SimpleReflexOrchestrator(
condition=lambda utt: "refund" in utt.lower() or "charged twice" in utt.lower(),
instruction=(
"Follow the refund policy. Verify account, apologize briefly, "
"explain next steps clearly, and offer to create a ticket if needed."
),
)
# Now we create the agents
support_agent = Agent(persona=support_persona,
tools=[check_order_status],
name="Support")
simulated_customer = Agent(
persona=customer_persona,
first_utterance="Hi, I was charged twice this month.",
name="Customer",
)
# (Optional) We can attach orchestrators to an agent using pipe-like composition
support_agent = support_agent | react
# Let's generate three dialogs between them! (so we can evaluate them later, see evaluation section)
for ix in range(3):
dialog = simulated_customer.dialog_with(support_agent, context=ctx)
dialog.to_file(f"dialog_{ix}.json")
dialog.print(orchestration=True) # pretty print each dialog
# Finally, let's serve the support agent to interact with real users (OpenAI-compatible API)
# Point Open WebUI or any OpenAI-compatible client to: http://localhost:1333
# Model name will appear as "Support:latest" (AGENT_NAME:latest).
support_agent.serve(1333)
[!NOTE]
- See orchestration tutorial and agents with tools and thoughts.
- Serving agents: more details on the OpenAI/Ollama-compatible API in the docs: Serving Agents.
- Dialogs are rich objects with helper methods (filter, slice, transform, etc.) that can be easily exported and loaded.
- Next: see Loading and saving dialogs and Auto-generating personas and contexts for persistence and controlled diversity.
🧪 Testing remote systems with simulated users
Use SDialog as a controllable test harness for any OpenAI‑compatible system such as vLLM-based ones—role‑play realistic or adversarial users against your deployed system:
- Black‑box functional checks (Does the system follow instructions? Handle edge cases?)
- Persona / use‑case coverage (Different goals, emotions, domains)
- Regression testing (Run the same persona batch each release; diff dialogs)
- Safety / robustness probing (Angry, confused, or noisy users)
- Automated evaluation (Pipe generated dialogs directly into evaluators below)
Core idea: wrap your system as an Agent, talk to it with simulated user Agents, and capture Dialogs you can save, diff, and score.
Below is a minimal example where our simulated customer interacts once with your hypothetical remote endpoint:
# Our remote system (your conversational backend exposing an OpenAI-compatible API)
system = Agent(
model="your/model", # Model name exposed by your server
openai_api_base="http://your-endpoint.com:8000/v1", # Base URL of the service
openai_api_key="EMPTY", # Or a real key if required
name="System"
)
# Let's make the system talk to our simulated customer defined in the example above.
dialog = system.dialog_with(simulated_customer)
dialog.to_file("dialog_0.json")
Next, evaluate these dialogs or orchestrate agents with more complex flows using rule/LLM hybrid orchestrators (see tutorials 3 & 7).
💾 Loading and saving dialogs
Dialogs are JSON‑serializable and can be created from multiple formats. After generating one you can persist it, then reload later for evaluation, transformation, or mixing with real data.
from sdialog import Dialog
# Load from JSON (generated by SDialog using `to_file()`)
dialog = Dialog.from_file("dialog_0.json")
# Load from HuggingFace Hub datasets
dialogs = Dialog.from_huggingface("sdialog/Primock-57")
# Create from plain text files or strings - perfect for converting existing datasets!
dialog_from_txt = Dialog.from_str("""
Alice: Hello there! How are you today?
Bob: I'm doing great, thanks for asking.
Alice: That's wonderful to hear!
""")
# Or, equivalently if the content is in a txt file
dialog_from_txt = Dialog.from_file("conversation.txt")
# Load from CSV files with custom templates
dialog_from_csv = Dialog.from_file("conversation.csv",
csv_speaker_col="speaker",
csv_text_col="value",)
# All Dialog objects have rich manipulation methods
dialog.filter("Alice").rename_speaker("Alice", "Customer").upper().to_file("processed.json")
avg_words_turn = sum(len(turn) for turn in dialog) / len(dialog)
📊 Evaluate and compare
Use built‑in metrics (readability, flow, linguistic features, LLM judges) or easily create new ones, then aggregate and compare datasets via DatasetComparator.
from sdialog.evaluation import LLMJudgeRealDialog, LinguisticFeatureScore
from sdialog.evaluation import FrequencyEvaluator, MeanEvaluator
from sdialog.evaluation import DatasetComparator
reference = [...] # list[Dialog]
candidate = [...] # list[Dialog]
judge = LLMJudgeRealDialog()
flesch = LinguisticFeatureScore(feature="flesch-reading-ease")
comparator = DatasetComparator([
FrequencyEvaluator(judge, name="Realistic dialog rate"),
MeanEvaluator(flesch, name="Mean Flesch Reading Ease"),
])
results = comparator({"reference": reference, "candidate": candidate})
# Plot results for each evaluator
comparator.plot()
[!TIP] See evaluation tutorial.
🧬 Auto-generating personas and contexts
Use generators to fill in (or selectively control) persona/context attributes using LLMs or other data sources (functions, CSV files, inline prompts). The .set() method lets you override how individual attributes are produced.
from sdialog.personas import Doctor, Patient
from sdialog.generators import PersonaGenerator, ContextGenerator
from sdialog import Context
# By default, unspecified attributes are LLM generated
doc = PersonaGenerator(Doctor(specialty="Cardiology")).generate()
pat = PersonaGenerator(Patient(symptoms="chest pain")).generate()
# Optionally specify generation sources per attribute
ctx_gen = ContextGenerator(Context(location="emergency room"))
ctx_gen.set(
objects=get_random_object, # user-defined function
circumstances="{csv:circumstance:./data/circumstances.csv}", # CSV file values
goals="{llm:Suggest a realistic goal for the context}" # targeted LLM instruction
)
ctx = ctx_gen.generate()
[!TIP] 🕹️ 👉 Try the demo notebook to experiment with generators.
🧠 Mechanistic interpretability
Attach Inspectors to capture per‑token activations and optionally steer (add/ablate directions) to analyze or intervene in model behavior.
import sdialog
from sdialog.interpretability import Inspector
from sdialog.agents import Agent
sdialog.config.llm("huggingface:meta-llama/Llama-3.2-3B-Instruct")
agent = Agent(name="Bob")
inspector = Inspector(target="model.layers.16.post_attention_layernorm")
agent = agent | inspector
agent("How are you?")
agent("Cool!")
# Let's get the last response's first token activation vector!
act = inspector[-1][0].act # [response index][token index]
Steering intervention (subtracting a direction):
anger_direction = torch.load("anger_direction.pt") # A direction vector (e.g., PCA / difference-in-mean vector)
agent_steered = agent | inspector - anger_direction # Ablate the anger direction from the target activations
agent_steered("You are an extremely upset assistant") # Agent "can't get angry anymore" :)
[!TIP] See the tutorial on using SDialog to remove the refusal capability from LLaMA 3.2.
🔌 Backends and configuration
Many backends supported, just use "BACKEND:MODEL" string format to either set a global default LLM for all components or pass one to each component:
import sdialog
# Change the default global LLM
sdialog.config.llm("ollama:qwen3:14b")
# Any argument supported by the chosen backend/model can also be given, for example
sdialog.config.llm("ollama:qwen3:14b",
temperature=0.7,
base_url="https://my-ollama-endpoint.com:123") # Remote Ollama server
Any LLM-powered component can also take a specific model and its parameters as argument, to overwrite the default one:
from sdialog.agents import Agent
my_agent = Agent(model="amazon:anthropic.claude-3-5-sonnet-20240620-v1:0",
region_name="us-east-1")
📖 Documentation and tutorials
- Demo notebook
- Tutorials
- API reference
- Documentation
- LLM-friendly docs for AI coding assistants (GitHub Copilot, etc.) following the llm.txt specification, in your chat use:
#fetch https://sdialog.readthedocs.io/en/latest/llm.txt Your prompt to use sdialog here...
🌍 Project Vision & Community Call
To accelerate open, rigorous, and reproducible conversational AI research, SDialog invites the community to collaborate and help shape the future of open dialogue generation.
🤝 How You Can Help
Contributions of any size are welcome and help shape the future of open dialogue generation:
- 🗂️ Dataset Standardization: Help convert existing dialogue datasets to SDialog format. Currently, each dataset stores dialogues in different formats, making cross-dataset analysis and model evaluation challenging. Converted datasets are made available as Hugging Face datasets in the SDialog organization for easy access and integration.
- 🔧 Component Development: Create new personas, orchestrators, evaluators, generators, or backend integrations
- 📊 Evaluation & Benchmarks: Design new metrics, evaluation frameworks, or comparative studies
- 🧠 Interpretability Research: Develop new analysis tools, steering methods, or mechanistic insights
- 📖 Documentation & Tutorials: Improve guides, add examples, or create educational content
- 🐛 Issues & Discussions: Report bugs, request features, or share research ideas and use cases
[!NOTE] Example: Check out Primock-57, a sample dataset already available in SDialog format on Hugging Face.
If you have a dialogue dataset you'd like to convert to SDialog format, need help with the conversion process, or want to contribute in any other way, please open an issue or reach out to us. We're happy to help and collaborate!
💪 Contributing
See CONTRIBUTING.md. We welcome issues, feature requests, and pull requests. If you want to contribute to the project, please open an issue or submit a PR, and help us make SDialog better 👍
This project follows the all-contributors specification. All-contributors list:
Sergio Burdisso 💻 🤔 📖 ✅ |
Labrak Yanis 💻 🤔 |
Séverin 💻 🤔 ✅ |
Ricard Marxer 💻 🤔 |
Thomas Schaaf 💻 |
David Liu 💻 |
ahassoo1 🤔 💻 |
Pawel Cyrta 💻 🤔 |
ABCDEFGHIJKL 💻 |
🙏 Acknowledgments
This work was supported by the European Union Horizon 2020 project ELOQUENCE (grant number 101070558).
The initial development of this project began in preparation for the 2025 Jelinek Memorial Summer Workshop on Speech and Language Technologies (JSALT 2025) as part of the "Play your Part" research group.
📝 License
MIT License
Copyright (c) 2025 Idiap Research Institute
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sdialog-0.3.3.tar.gz.
File metadata
- Download URL: sdialog-0.3.3.tar.gz
- Upload date:
- Size: 1.2 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.20
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0f5326bca28156d27ef75f6e76dbc388c4fc7cf75efba9def7a55d55b7ca6978
|
|
| MD5 |
63abbc12b045a5339bf6de7e76c20783
|
|
| BLAKE2b-256 |
7427c157a3758f7d2f75df98f0ff85abc055825837f338969cdd297155db59f2
|
File details
Details for the file sdialog-0.3.3-py3-none-any.whl.
File metadata
- Download URL: sdialog-0.3.3-py3-none-any.whl
- Upload date:
- Size: 1.3 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.20
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
151cbb2395d6dbffa3eac0f1f952a180ec7e50a79bac89ebefcfc8f2fb01e1a8
|
|
| MD5 |
4d9ecacf9c80ef3d377eb47f8bbe3af6
|
|
| BLAKE2b-256 |
7ee223f734c3fdeba8a8182bf8de745e5ce2c6cc4e70198cfe340bed9eb83790
|