API Reference¶
This section provides detailed API reference documentation for the Kura package, automatically generated from the source code using mkdocstrings.
How to Use This Reference¶
The API reference is organized by module, with each module containing related classes and functions. For each class, you'll find:
- Constructor parameters and their descriptions
- Instance methods with parameter details and return types
- Properties and attributes
To use these classes in your code, import them from their specific modules:
# Import functions from their specific modules
from kura.summarisation import summarise_conversations, SummaryModel
from kura.cluster import generate_base_clusters_from_conversation_summaries, ClusterDescriptionModel
from kura.meta_cluster import reduce_clusters_from_base_clusters, MetaClusterModel
from kura.dimensionality import reduce_dimensionality_from_clusters, HDBUMAP
from kura.visualization import visualise_pipeline_results
from kura.types import Conversation
from kura.checkpoints import JSONLCheckpointManager
from kura.cache import DiskCacheStrategy
Core Classes¶
Procedural API¶
The procedural API provides a functional approach to conversation analysis with composable pipeline functions.
Pipeline Functions¶
kura.summarisation.summarise_conversations(conversations: list[Conversation], *, model: BaseSummaryModel, response_schema: Type[T] = GeneratedSummary, prompt: str = DEFAULT_SUMMARY_PROMPT, temperature: float = 0.2, checkpoint_manager: Optional[BaseCheckpointManager] = None, **kwargs) -> list[ConversationSummary]
async
¶
Generate summaries for a list of conversations using the CLIO framework.
This is a pure function that takes conversations and a summary model, and returns conversation summaries with automatic extensibility. Optionally uses checkpointing for efficient re-runs.
The function works with any model that implements BaseSummaryModel, supporting heterogeneous backends (OpenAI, vLLM, Hugging Face, etc.) through polymorphism.
Extensibility Features: - Custom Fields: Extend GeneratedSummary to add custom analysis fields - Prompt Modification: Use prompt to modify CLIO analysis - Automatic Mapping: Extended fields are automatically placed in metadata
Parameters:
Name | Type | Description | Default |
---|---|---|---|
conversations | list[Conversation] | List of conversations to summarize | required |
model | BaseSummaryModel | Model to use for summarization (OpenAI, vLLM, local, etc.) | required |
response_schema | Type[T] | Pydantic model class for LLM output. Extend GeneratedSummary to add custom fields that will appear in metadata | GeneratedSummary |
prompt | str | Custom prompt to modify the CLIO analysis | DEFAULT_SUMMARY_PROMPT |
temperature | float | LLM temperature for generation | 0.2 |
checkpoint_manager | Optional[BaseCheckpointManager] | Optional checkpoint manager for caching | None |
Returns:
Type | Description |
---|---|
list[ConversationSummary] | List of ConversationSummary objects with core CLIO fields and any |
list[ConversationSummary] | additional fields from extended schemas in metadata |
Example - Basic Usage
model = SummaryModel() summaries = await summarise_conversations( ... conversations=my_conversations, ... model=model ... )
Example - Custom Analysis
class DetailedSummary(GeneratedSummary): ... sentiment: str ... technical_depth: int
summaries = await summarise_conversations( ... conversations=my_conversations, ... model=model, ... response_schema=DetailedSummary, ... prompt="Analyze sentiment and rate technical depth 1-10" ... )
Custom fields available in metadata¶
print(summaries[0].metadata["sentiment"])
Source code in kura/summarisation.py
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 |
|
kura.cluster.generate_base_clusters_from_conversation_summaries(summaries: List[ConversationSummary], embedding_model: Optional[BaseEmbeddingModel] = None, clustering_method: Optional[BaseClusteringMethod] = None, clustering_model: Optional[BaseClusterDescriptionModel] = None, checkpoint_manager: Optional[BaseCheckpointManager] = None, max_contrastive_examples: int = 10, prompt: str = DEFAULT_CLUSTER_PROMPT, **kwargs) -> List[Cluster]
async
¶
Cluster conversation summaries using embeddings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
summaries | List[ConversationSummary] | List of conversation summaries to cluster | required |
embedding_model | Optional[BaseEmbeddingModel] | Model for generating embeddings (defaults to OpenAI) | None |
clustering_method | Optional[BaseClusteringMethod] | Clustering algorithm (defaults to K-means) | None |
clustering_model | Optional[BaseClusterDescriptionModel] | Model for generating cluster descriptions | None |
checkpoint_manager | Optional[BaseCheckpointManager] | Optional checkpoint manager for caching | None |
max_contrastive_examples | int | Number of contrastive examples to use | 10 |
prompt | str | Custom prompt for cluster generation | DEFAULT_CLUSTER_PROMPT |
**kwargs | Additional parameters for clustering model | {} |
Returns:
Type | Description |
---|---|
List[Cluster] | List of clusters with generated names and descriptions |
Source code in kura/cluster.py
kura.meta_cluster.reduce_clusters_from_base_clusters(clusters: list[Cluster], *, model: BaseMetaClusterModel, checkpoint_manager: Optional[BaseCheckpointManager] = None) -> list[Cluster]
async
¶
Reduce clusters into a hierarchical structure.
Iteratively combines similar clusters until the number of root clusters is less than or equal to the model's max_clusters setting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
clusters | list[Cluster] | List of initial clusters to reduce | required |
model | BaseMetaClusterModel | Meta-clustering model to use for reduction | required |
checkpoint_manager | Optional[BaseCheckpointManager] | Optional checkpoint manager for caching | None |
Returns:
Type | Description |
---|---|
list[Cluster] | List of clusters with hierarchical structure |
Example
meta_model = MetaClusterModel(max_clusters=5) reduced = await reduce_clusters( ... clusters=base_clusters, ... model=meta_model, ... checkpoint_manager=checkpoint_mgr ... )
Source code in kura/meta_cluster.py
kura.dimensionality.reduce_dimensionality_from_clusters(clusters: list[Cluster], *, model: BaseDimensionalityReduction, checkpoint_manager: Optional[BaseCheckpointManager] = None) -> list[ProjectedCluster]
async
¶
Reduce dimensions of clusters for visualization.
Projects clusters to 2D space using the provided dimensionality reduction model. Supports different algorithms (UMAP, t-SNE, PCA, etc.) through the model interface.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
clusters | list[Cluster] | List of clusters to project | required |
model | BaseDimensionalityReduction | Dimensionality reduction model to use (UMAP, t-SNE, etc.) | required |
checkpoint_manager | Optional[BaseCheckpointManager] | Optional checkpoint manager for caching | None |
Returns:
Type | Description |
---|---|
list[ProjectedCluster] | List of projected clusters with 2D coordinates |
Example
dim_model = HDBUMAP(n_components=2) projected = await reduce_dimensionality( ... clusters=hierarchical_clusters, ... model=dim_model, ... checkpoint_manager=checkpoint_mgr ... )
Source code in kura/dimensionality.py
Checkpoint Management¶
kura.checkpoint.CheckpointManager
¶
Bases: BaseCheckpointManager
Handles checkpoint loading and saving for pipeline steps.
Source code in kura/checkpoint.py
__init__(checkpoint_dir: str, *, enabled: bool = True)
¶
Initialize checkpoint manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
checkpoint_dir | str | Directory for saving checkpoints | required |
enabled | bool | Whether checkpointing is enabled | True |
Source code in kura/checkpoint.py
delete_checkpoint(filename: str) -> bool
¶
Delete a checkpoint file.
Source code in kura/checkpoint.py
get_checkpoint_path(filename: str) -> Path
¶
Get full path for a checkpoint file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename | str | Name of the checkpoint file | required |
Returns:
Type | Description |
---|---|
Path | Path object for the checkpoint file |
list_checkpoints() -> List[str]
¶
List all available checkpoint files.
load_checkpoint(filename: str, model_class: type[T], **kwargs) -> Optional[List[T]]
¶
Load data from a checkpoint file if it exists.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename | str | Name of the checkpoint file | required |
model_class | type[T] | Pydantic model class for deserializing the data | required |
**kwargs | Additional arguments (for compatibility with base class) | {} |
Returns:
Type | Description |
---|---|
Optional[List[T]] | List of model instances if checkpoint exists, None otherwise |
Source code in kura/checkpoint.py
save_checkpoint(filename: str, data: List[T], **kwargs) -> None
¶
Save data to a checkpoint file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename | str | Name of the checkpoint file | required |
data | List[T] | List of model instances to save | required |
**kwargs | Additional arguments (for compatibility with base class) | {} |
Source code in kura/checkpoint.py
setup_checkpoint_dir() -> None
¶
Create checkpoint directory if it doesn't exist.
Source code in kura/checkpoint.py
Implementation Classes¶
Embedding Models¶
kura.embedding
¶
logger = logging.getLogger(__name__)
module-attribute
¶
CohereEmbeddingModel
¶
Bases: BaseEmbeddingModel
Source code in kura/embedding.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
|
client = AsyncClient(api_key=api_key)
instance-attribute
¶
input_type = input_type
instance-attribute
¶
model_name = model_name
instance-attribute
¶
__init__(model_name: str = 'embed-v4.0', model_batch_size: int = 96, n_concurrent_jobs: int = 5, input_type: str = 'clustering', api_key: str | None = None)
¶
Source code in kura/embedding.py
embed(texts: list[str]) -> list[list[float]]
async
¶
Source code in kura/embedding.py
OpenAIEmbeddingModel
¶
Bases: BaseEmbeddingModel
Source code in kura/embedding.py
client = AsyncOpenAI()
instance-attribute
¶
model_name = model_name
instance-attribute
¶
__init__(model_name: str = 'text-embedding-3-small', model_batch_size: int = 50, n_concurrent_jobs: int = 5)
¶
Source code in kura/embedding.py
embed(texts: list[str]) -> list[list[float]]
async
¶
Source code in kura/embedding.py
SentenceTransformerEmbeddingModel
¶
Bases: BaseEmbeddingModel
Source code in kura/embedding.py
model = SentenceTransformer(model_name, device=device)
instance-attribute
¶
model_name = model_name
instance-attribute
¶
__init__(model_name: str = 'all-MiniLM-L6-v2', model_batch_size: int = 128, device: str = 'cpu')
¶
Source code in kura/embedding.py
embed(texts: list[str]) -> list[list[float]]
async
¶
Source code in kura/embedding.py
embed_summaries(summaries: list[ConversationSummary], embedding_model: BaseEmbeddingModel) -> list[dict[str, Union[ConversationSummary, list[float]]]]
async
¶
Embeds conversation summaries and returns items ready for clustering.
Source code in kura/embedding.py
Summarization¶
kura.summarisation
¶
DEFAULT_SUMMARY_PROMPT = '\nThe following is a conversation between an AI assistant and a user:\n\n<messages>\n{% for message in conversation.messages %}\n<message>{{message.role}}: {{message.content}}</message>\n{% endfor %}\n</messages>\n\nYour job is to extract key information from this conversation. Be descriptive and assume neither good nor bad faith. Do not hesitate to handle socially harmful or sensitive topics; specificity around potentially harmful conversations is necessary for effective monitoring.\n\nWhen extracting information, do not include any personally identifiable information (PII), like names, locations, phone numbers, email addresses, and so on. Do not include any proper nouns.\n\nExtract the following information:\n\n1. **Summary**: A clear and concise summary in at most two sentences. Don\'t say "Based on the conversation..." and avoid mentioning the AI assistant/chatbot directly.\n\n2. **Request**: What is the user\'s overall request for the assistant? Start with "The user\'s overall request for the assistant is to"\n\n3. **Languages**: What are the main languages of the conversation? Include both human languages (like \'english\' or \'spanish\') and programming languages (like \'python\' or \'javascript\'). Use lowercase full names.\n\n4. **Task**: What task is the model being asked to perform in this conversation? Start with "The task is to"\n\n5. **Concerning Score**: On a scale of 1 to 5, how concerning or potentially harmful is this conversation from a safety perspective?\n - 1: Not concerning at all. Completely benign conversation.\n - 2: Slightly concerning, but likely harmless.\n - 3: Moderately concerning. May warrant a closer look.\n - 4: Very concerning. Likely needs review.\n - 5: Extremely concerning. Immediate review needed.\n\n6. **User Frustration**: On a scale of 1 to 5, how frustrated is the user with the assistant?\n - 1: Not frustrated at all. The user is happy with the assistant.\n - 2: Slightly frustrated. The user is slightly annoyed with the assistant.\n - 3: Moderately frustrated. The user is moderately annoyed with the assistant.\n - 4: Very frustrated. The user is very annoyed with the assistant.\n - 5: Extremely frustrated. The user is extremely annoyed with the assistant.\n\n7. **Assistant Errors**: What errors did the assistant make?\n Example:\n - "Responses were too long and verbose"\n - "Misunderstood the user\'s intent or request"\n - "Used wrong tool for the task"\n - "Ignored user\'s stated preferences or constraints"\n - "Provided outdated or incorrect information"\n - "Failed to maintain conversation context"\n\n\nRemember that\n- Summaries should be concise and short. They should each be at most 1-2 sentences and at most 30 words.\n- Summaries should start with "The user\'s overall request for the assistant is to"\n- Make sure to omit any personally identifiable information (PII), like names, locations, phone numbers, email addressess, company names and so on.\n- Make sure to indicate specific details such as programming languages, frameworks, libraries and so on which are relevant to the task.\n'
module-attribute
¶
T = TypeVar('T', bound=GeneratedSummary)
module-attribute
¶
logger = logging.getLogger(__name__)
module-attribute
¶
SummaryModel
¶
Bases: BaseSummaryModel
Instructor-based summary model for conversation analysis.
Example - Custom Schema
class CustomSummary(GeneratedSummary): ... sentiment: str ... complexity: int
summaries = await model.summarise( ... conversations, ... response_schema=CustomSummary ... )
sentiment & complexity will be in summaries[0].metadata¶
Example - Custom Prompt
summaries = await model.summarise( ... conversations, ... prompt="Also assess the technical complexity on a scale of 1-10." ... )
Source code in kura/summarisation.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
|
cache = cache
instance-attribute
¶
checkpoint_filename: str
property
¶
Return the filename to use for checkpointing this model's output.
console = console
instance-attribute
¶
max_concurrent_requests = max_concurrent_requests
instance-attribute
¶
model = model
instance-attribute
¶
__init__(model: Union[str, KnownModelName] = 'openai/gpt-4o-mini', max_concurrent_requests: int = 50, checkpoint_filename: str = 'summaries', console: Optional[Console] = None, cache: Optional[CacheStrategy] = None)
¶
Initialize SummaryModel with core configuration.
Per-use configuration (schemas, prompts, temperature) are method parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model | Union[str, KnownModelName] | model identifier (e.g., "openai/gpt-4o-mini") | 'openai/gpt-4o-mini' |
max_concurrent_requests | int | Maximum concurrent API requests | 50 |
cache | Optional[CacheStrategy] | Caching strategy to use (optional) | None |
Source code in kura/summarisation.py
summarise(conversations: list[Conversation], prompt: str = DEFAULT_SUMMARY_PROMPT, *, response_schema: Type[T] = GeneratedSummary, temperature: float = 0.2, **kwargs) -> list[ConversationSummary]
async
¶
Summarise conversations with configurable parameters.
This method uses the CLIO conversation analysis framework, with automatic extensibility for custom fields and prompt modifications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
conversations | list[Conversation] | List of conversations to summarize | required |
response_schema | Type[T] | Pydantic model class for structured LLM output. Extend GeneratedSummary to add custom fields that will automatically be included in ConversationSummary.metadata | GeneratedSummary |
prompt | str | Custom prompt for CLIO analysis | DEFAULT_SUMMARY_PROMPT |
temperature | float | LLM temperature for generation | 0.2 |
Returns:
Type | Description |
---|---|
list[ConversationSummary] | List of ConversationSummary objects with core fields populated and |
list[ConversationSummary] | any additional fields from extended schemas in metadata |
Example
class CustomSummary(GeneratedSummary): ... sentiment: str ... technical_complexity: int
summaries = await model.summarise( ... conversations, ... response_schema=CustomSummary, ... prompt="Rate sentiment and technical complexity 1-10" ... )
Access core fields¶
print(summaries[0].summary)
Access custom fields in metadata¶
print(summaries[0].metadata["sentiment"])
Source code in kura/summarisation.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
|
summarise_conversations(conversations: list[Conversation], *, model: BaseSummaryModel, response_schema: Type[T] = GeneratedSummary, prompt: str = DEFAULT_SUMMARY_PROMPT, temperature: float = 0.2, checkpoint_manager: Optional[BaseCheckpointManager] = None, **kwargs) -> list[ConversationSummary]
async
¶
Generate summaries for a list of conversations using the CLIO framework.
This is a pure function that takes conversations and a summary model, and returns conversation summaries with automatic extensibility. Optionally uses checkpointing for efficient re-runs.
The function works with any model that implements BaseSummaryModel, supporting heterogeneous backends (OpenAI, vLLM, Hugging Face, etc.) through polymorphism.
Extensibility Features: - Custom Fields: Extend GeneratedSummary to add custom analysis fields - Prompt Modification: Use prompt to modify CLIO analysis - Automatic Mapping: Extended fields are automatically placed in metadata
Parameters:
Name | Type | Description | Default |
---|---|---|---|
conversations | list[Conversation] | List of conversations to summarize | required |
model | BaseSummaryModel | Model to use for summarization (OpenAI, vLLM, local, etc.) | required |
response_schema | Type[T] | Pydantic model class for LLM output. Extend GeneratedSummary to add custom fields that will appear in metadata | GeneratedSummary |
prompt | str | Custom prompt to modify the CLIO analysis | DEFAULT_SUMMARY_PROMPT |
temperature | float | LLM temperature for generation | 0.2 |
checkpoint_manager | Optional[BaseCheckpointManager] | Optional checkpoint manager for caching | None |
Returns:
Type | Description |
---|---|
list[ConversationSummary] | List of ConversationSummary objects with core CLIO fields and any |
list[ConversationSummary] | additional fields from extended schemas in metadata |
Example - Basic Usage
model = SummaryModel() summaries = await summarise_conversations( ... conversations=my_conversations, ... model=model ... )
Example - Custom Analysis
class DetailedSummary(GeneratedSummary): ... sentiment: str ... technical_depth: int
summaries = await summarise_conversations( ... conversations=my_conversations, ... model=model, ... response_schema=DetailedSummary, ... prompt="Analyze sentiment and rate technical depth 1-10" ... )
Custom fields available in metadata¶
print(summaries[0].metadata["sentiment"])
Source code in kura/summarisation.py
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 |
|
Clustering¶
kura.cluster
¶
DEFAULT_CLUSTER_PROMPT = '\nYou are tasked with summarizing a group of related statements into a short, precise, and accurate description and name. Your goal is to create a concise summary that captures the essence of these statements and distinguishes them from other similar groups of statements.\n\nSummarize all the statements into a clear, precise, two-sentence description in the past tense. Your summary should be specific to this group and distinguish it from the contrastive answers of the other groups.\n\nAfter creating the summary, generate a short name for the group of statements. This name should be at most ten words long (perhaps less) and be specific but also reflective of most of the statements (rather than reflecting only one or two).\n\nThe name should distinguish this group from the contrastive examples. For instance, "Write fantasy sexual roleplay with octopi and monsters", "Generate blog spam for gambling websites", or "Assist with high school math homework" would be better and more actionable than general terms like "Write erotic content" or "Help with homework". Be as descriptive as possible and assume neither good nor bad faith. Do not hesitate to identify and describe socially harmful or sensitive topics specifically; specificity is necessary for monitoring.\n\nPresent your output in the following format:\n<summary> [Insert your two-sentence summary here] </summary>\n<name> [Insert your generated short name here] </name>\n\nThe names you propose must follow these requirements:\n- The cluster name should be a sentence in the imperative that captures the user\'s request. For example, \'Brainstorm ideas for a birthday party\' or \'Help me find a new job.\'\n- Create names that are specific enough to be meaningful, but not so specific that they can\'t meaningfully represent many different statements.\n- Avoid overly general or vague terms, and do not hesitate to describe socially harmful or sensitive topics (in fact, clusters that clearly describe harmful behavior are slightly preferred); specificity is necessary for observability and enforcement.\n- Ensure that the cluster name is distinct from the contrastive examples.\n- Use clear, concise, and descriptive language for the cluster name.\n\nBelow are the related statements:\n<positive_examples>\n{% for item in positive_examples %}{{ item }}\n{% endfor %}\n</positive_examples>\n\nFor context, here are statements from nearby groups that are NOT part of the group you\'re summarizing:\n<contrastive_examples>\n{% for item in contrastive_examples %}{{ item }}\n{% endfor %}\n</contrastive_examples>\n\nDo not elaborate beyond what you say in the tags. Remember to analyze both the statements and the contrastive statements carefully to ensure your summary and name accurately represent the specific group while distinguishing it from others. The cluster name should be a sentence in the imperative that captures the user\'s request. For example, \'Brainstorm ideas for a birthday party\' or \'Help me find a new job.\'\n'
module-attribute
¶
logger = logging.getLogger(__name__)
module-attribute
¶
ClusterDescriptionModel
¶
Bases: BaseClusterDescriptionModel
Model for generating cluster descriptions using LLMs.
Similar to SummaryModel, this handles the LLM interaction for generating cluster names and descriptions with configurable parameters.
Source code in kura/cluster.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
|
checkpoint_filename: str
property
¶
Return the filename to use for checkpointing this model's output.
console = console
instance-attribute
¶
max_concurrent_requests = max_concurrent_requests
instance-attribute
¶
model = model
instance-attribute
¶
temperature = temperature
instance-attribute
¶
__init__(model: Union[str, KnownModelName] = 'openai/gpt-4o-mini', max_concurrent_requests: int = 50, temperature: float = 0.2, checkpoint_filename: str = 'clusters', console: Optional[Console] = None)
¶
Initialize ClusterModel with core configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model | Union[str, KnownModelName] | model identifier (e.g., "openai/gpt-4o-mini") | 'openai/gpt-4o-mini' |
max_concurrent_requests | int | Maximum concurrent API requests | 50 |
temperature | float | LLM temperature for generation | 0.2 |
checkpoint_filename | str | Filename for checkpointing | 'clusters' |
console | Optional[Console] | Rich console for progress tracking | None |
Source code in kura/cluster.py
generate_cluster_description(summaries: List[ConversationSummary], contrastive_examples: List[ConversationSummary], semaphore: Semaphore, client: AsyncInstructor, prompt: str = DEFAULT_CLUSTER_PROMPT) -> Cluster
async
¶
Generate a cluster description from summaries with contrastive examples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
summaries | List[ConversationSummary] | Summaries in this cluster | required |
contrastive_examples | List[ConversationSummary] | Examples from other clusters for contrast | required |
Returns:
Type | Description |
---|---|
Cluster | Cluster with generated name and description |
Source code in kura/cluster.py
generate_clusters(cluster_id_to_summaries: Dict[int, List[ConversationSummary]], prompt: str = DEFAULT_CLUSTER_PROMPT, max_contrastive_examples: int = 10) -> List[Cluster]
async
¶
Generate clusters from a mapping of cluster IDs to summaries.
Source code in kura/cluster.py
KmeansClusteringModel
¶
Bases: BaseClusteringMethod
Source code in kura/cluster.py
clusters_per_group = clusters_per_group
instance-attribute
¶
__init__(clusters_per_group: int = 10)
¶
cluster(items: list[dict[str, Union[ConversationSummary, list[float]]]]) -> dict[int, list[ConversationSummary]]
¶
We perform a clustering here using an embedding defined on each individual item.
We assume that the item is passed in as a dictionary with
- its relevant embedding stored in the "embedding" key.
- the item itself stored in the "item" key.
{ "embedding": list[float], "item": any, }
Source code in kura/cluster.py
generate_base_clusters_from_conversation_summaries(summaries: List[ConversationSummary], embedding_model: Optional[BaseEmbeddingModel] = None, clustering_method: Optional[BaseClusteringMethod] = None, clustering_model: Optional[BaseClusterDescriptionModel] = None, checkpoint_manager: Optional[BaseCheckpointManager] = None, max_contrastive_examples: int = 10, prompt: str = DEFAULT_CLUSTER_PROMPT, **kwargs) -> List[Cluster]
async
¶
Cluster conversation summaries using embeddings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
summaries | List[ConversationSummary] | List of conversation summaries to cluster | required |
embedding_model | Optional[BaseEmbeddingModel] | Model for generating embeddings (defaults to OpenAI) | None |
clustering_method | Optional[BaseClusteringMethod] | Clustering algorithm (defaults to K-means) | None |
clustering_model | Optional[BaseClusterDescriptionModel] | Model for generating cluster descriptions | None |
checkpoint_manager | Optional[BaseCheckpointManager] | Optional checkpoint manager for caching | None |
max_contrastive_examples | int | Number of contrastive examples to use | 10 |
prompt | str | Custom prompt for cluster generation | DEFAULT_CLUSTER_PROMPT |
**kwargs | Additional parameters for clustering model | {} |
Returns:
Type | Description |
---|---|
List[Cluster] | List of clusters with generated names and descriptions |
Source code in kura/cluster.py
get_contrastive_examples(cluster_id: int, cluster_id_to_summaries: Dict[int, List[ConversationSummary]], max_contrastive_examples: int = 10) -> List[ConversationSummary]
¶
Get contrastive examples from other clusters to help distinguish this cluster.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cluster_id | int | The id of the cluster to get contrastive examples for | required |
cluster_id_to_summaries | Dict[int, List[ConversationSummary]] | A dictionary of cluster ids to their summaries | required |
max_contrastive_examples | int | The number of contrastive examples to return. Defaults to 10. | 10 |
Returns:
Type | Description |
---|---|
List[ConversationSummary] | List of contrastive examples from other clusters |
Source code in kura/cluster.py
Meta-Clustering¶
kura.meta_cluster
¶
logger = logging.getLogger(__name__)
module-attribute
¶
CandidateClusters
¶
Bases: BaseModel
Source code in kura/meta_cluster.py
candidate_cluster_names: list[str]
instance-attribute
¶
validate_candidate_cluster_names(v: list[str]) -> list[str]
¶
Source code in kura/meta_cluster.py
ClusterLabel
¶
Bases: BaseModel
Source code in kura/meta_cluster.py
higher_level_cluster: str
instance-attribute
¶
validate_higher_level_cluster(v: str, info: ValidationInfo) -> str
¶
Source code in kura/meta_cluster.py
MetaClusterModel
¶
Bases: BaseMetaClusterModel
Source code in kura/meta_cluster.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 |
|
checkpoint_filename: str
property
¶
The filename to use for checkpointing this model's output.
client = instructor.from_provider(model, async_client=True)
instance-attribute
¶
clustering_model = clustering_model
instance-attribute
¶
console = console
instance-attribute
¶
embedding_model = embedding_model
instance-attribute
¶
max_clusters = max_clusters
instance-attribute
¶
max_concurrent_requests = max_concurrent_requests
instance-attribute
¶
model = model
instance-attribute
¶
sem = Semaphore(max_concurrent_requests)
instance-attribute
¶
__init__(max_concurrent_requests: int = 50, model: str = 'openai/gpt-4o-mini', embedding_model: Optional[BaseEmbeddingModel] = None, clustering_model: Union[BaseClusteringMethod, None] = None, max_clusters: int = 10, console: Optional['Console'] = None, **kwargs)
¶
Source code in kura/meta_cluster.py
generate_candidate_clusters(clusters: list[Cluster], sem: Semaphore) -> list[str]
async
¶
Source code in kura/meta_cluster.py
generate_meta_clusters(clusters: list[Cluster], show_preview: bool = True) -> list[Cluster]
async
¶
Source code in kura/meta_cluster.py
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 |
|
label_cluster(cluster: Cluster, candidate_clusters: list[str])
async
¶
Source code in kura/meta_cluster.py
reduce_clusters(clusters: list[Cluster]) -> list[Cluster]
async
¶
This takes in a list of existing clusters and generates a few higher order clusters that are more general. This represents a single iteration of the meta clustering process.
In the event that we have a single cluster, we will just return a new higher level cluster which has the same name as the original cluster. ( This is an edge case which we should definitely handle better )
Source code in kura/meta_cluster.py
rename_cluster_group(clusters: list[Cluster]) -> list[Cluster]
async
¶
Source code in kura/meta_cluster.py
reduce_clusters_from_base_clusters(clusters: list[Cluster], *, model: BaseMetaClusterModel, checkpoint_manager: Optional[BaseCheckpointManager] = None) -> list[Cluster]
async
¶
Reduce clusters into a hierarchical structure.
Iteratively combines similar clusters until the number of root clusters is less than or equal to the model's max_clusters setting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
clusters | list[Cluster] | List of initial clusters to reduce | required |
model | BaseMetaClusterModel | Meta-clustering model to use for reduction | required |
checkpoint_manager | Optional[BaseCheckpointManager] | Optional checkpoint manager for caching | None |
Returns:
Type | Description |
---|---|
list[Cluster] | List of clusters with hierarchical structure |
Example
meta_model = MetaClusterModel(max_clusters=5) reduced = await reduce_clusters( ... clusters=base_clusters, ... model=meta_model, ... checkpoint_manager=checkpoint_mgr ... )
Source code in kura/meta_cluster.py
Dimensionality Reduction¶
kura.dimensionality
¶
logger = logging.getLogger(__name__)
module-attribute
¶
HDBUMAP
¶
Bases: BaseDimensionalityReduction
Source code in kura/dimensionality.py
checkpoint_filename: str
property
¶
The filename to use for checkpointing this model's output.
embedding_model = embedding_model
instance-attribute
¶
metric = metric
instance-attribute
¶
min_dist = min_dist
instance-attribute
¶
n_components = n_components
instance-attribute
¶
n_neighbors = n_neighbors
instance-attribute
¶
__init__(embedding_model: BaseEmbeddingModel = OpenAIEmbeddingModel(), n_components: int = 2, min_dist: float = 0.1, metric: str = 'cosine', n_neighbors: Union[int, None] = None)
¶
Source code in kura/dimensionality.py
reduce_dimensionality(clusters: list[Cluster]) -> list[ProjectedCluster]
async
¶
Source code in kura/dimensionality.py
reduce_dimensionality_from_clusters(clusters: list[Cluster], *, model: BaseDimensionalityReduction, checkpoint_manager: Optional[BaseCheckpointManager] = None) -> list[ProjectedCluster]
async
¶
Reduce dimensions of clusters for visualization.
Projects clusters to 2D space using the provided dimensionality reduction model. Supports different algorithms (UMAP, t-SNE, PCA, etc.) through the model interface.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
clusters | list[Cluster] | List of clusters to project | required |
model | BaseDimensionalityReduction | Dimensionality reduction model to use (UMAP, t-SNE, etc.) | required |
checkpoint_manager | Optional[BaseCheckpointManager] | Optional checkpoint manager for caching | None |
Returns:
Type | Description |
---|---|
list[ProjectedCluster] | List of projected clusters with 2D coordinates |
Example
dim_model = HDBUMAP(n_components=2) projected = await reduce_dimensionality( ... clusters=hierarchical_clusters, ... model=dim_model, ... checkpoint_manager=checkpoint_mgr ... )