Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

fix StructuredContent

thomashebrard855627790232
diff --git a/API_GUIDE.md b/docs/pages/api/index.md
similarity index 67%
rename from API_GUIDE.md
rename to docs/pages/api/index.md
index e4090fe30..0df19eb23 100644
--- a/API_GUIDE.md
+++ b/docs/pages/api/index.md
@@ -134,16 +134,17 @@ The `inputs` field uses **ImplicitMemory** format - a smart, flexible way to pro
**Case 1: Direct Content** - Provide the value directly (simplest)
- 1.1: String → `"my text"`
- 1.2: List of strings → `["text1", "text2"]`
-- 1.3: StuffContent object → `MyClass(arg1="value")`
- - 1.3a: Regular StuffContent → Infer concept from class name
- - 1.3b: ListContent[StuffContent] → Infer concept from first item's class (subcase)
+- 1.3: StructuredContent object → `MyClass(arg1="value")`
- 1.4: List of StuffContent objects → `[MyClass(...), MyClass(...)]`
+- 1.5: ListContent of StuffContent objects → `ListContent(items=[MyClass(...), MyClass(...)])`
+
+**Note:** Cases 1.3 and 1.5 are at the same level - both handle content types that inherit from `StuffContent`, but for different purposes (custom classes vs. list wrappers).
**Case 2: Explicit Format** - Use `{"concept": "...", "content": "..."}` for control
- 2.1: String with concept → `{"concept": "Text", "content": "my text"}`
- 2.2: List of strings with concept → `{"concept": "Text", "content": ["text1", "text2"]}`
-- 2.3: StuffContent object with concept → `{"concept": "Invoice", "content": InvoiceObject}`
-- 2.4: List of StuffContent objects with concept → `{"concept": "Invoice", "content": [...]}`
+- 2.3: StructuredContent object with concept → `{"concept": "Invoice", "content": InvoiceObject}`
+- 2.4: List of StructuredContent objects with concept → `{"concept": "Invoice", "content": [...]}`
- 2.5: Dictionary (structured data) → `{"concept": "Invoice", "content": {"field": "value"}}`
- 2.6: List of dictionaries → `{"concept": "Invoice", "content": [{...}, {...}]}`
@@ -185,17 +186,25 @@ Provide multiple text items as a list:
**Note:** The concept must be compatible with `native.Text` or an error will be raised.
-### 1.3: StuffContent Object
+### 1.3: StructuredContent Object
Provide a structured object directly (for Python clients):
```python
# Python client example
+from my_project.domain.domain_struct import MyConcept, MySubClass
+
inputs = {
"invoice_data": MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))
}
```
+**What is StructuredContent?**
+- `StructuredContent` is the base class for user-defined data structures in Pipelex
+- You create your own classes by inheriting from `StructuredContent`
+- These classes are defined in your project's Python files
+- Learn more: [Python StructuredContent Classes](../build-reliable-ai-workflows-with-pipelex/define_your_concepts.md#3-python-structuredcontent-classes)
+
**Concept Resolution:**
- The system searches all available domains for a concept matching the class name
- If multiple concepts with the same name exist in different domains → **Error**: Must specify domain
@@ -203,27 +212,30 @@ inputs = {
### 1.4: List of StuffContent Objects
-Provide multiple structured objects:
+Provide multiple content objects in a plain Python list:
```python
# Python client example
inputs = {
"invoice_list": [
MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
- MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))
+ MyConcept(arg1="arg1_2", arg2=2, arg3=MySubClass(arg4="arg4_2"))
]
}
```
+**What it accepts:**
+- Lists of `StructuredContent` objects (user-defined classes)
+- Lists of native content objects (`TextContent`, `ImageContent`, etc.)
+
**Requirements:**
- All items must be of the same type
- Concept resolution follows the same rules as 1.3
+- Creates a new `ListContent` wrapper internally
-### 1.3b: ListContent of StuffContent Objects (Subcase of 1.3)
-
-Since `ListContent` is itself a `StuffContent`, this is a special subcase of 1.3 where the content is inferred from the items inside rather than from the `ListContent` class itself.
+### 1.5: ListContent of StuffContent Objects
-Provide a `ListContent` object containing StuffContent items (Python clients):
+Provide an existing `ListContent` wrapper object (Python clients):
```python
# Python client example
@@ -237,20 +249,21 @@ inputs = {
}
```
-**Key Differences from Case 1.4:**
-- Case 1.4 uses a plain Python list: `[item1, item2]` → Creates a new `ListContent` wrapper
-- Case 1.3b uses an existing `ListContent` wrapper: `ListContent(items=[item1, item2])` → Uses the wrapper directly
+**Key Difference from Case 1.4:**
+- Case 1.4: Plain Python list `[item1, item2]` → **Creates** a new `ListContent` wrapper
+- Case 1.5: Already wrapped `ListContent(items=[item1, item2])` → **Uses** the wrapper directly
-**Why is this a subcase of 1.3?**
-- `ListContent` is a subclass of `StuffContent`
-- But we don't infer the concept from "ListContent" itself
-- Instead, we look inside and infer from the first item's class
+**Why Case 1.5 is Separate from Case 1.3:**
+- `StructuredContent` and `ListContent` are **sibling classes** (both inherit from `StuffContent`)
+- Case 1.3 handles user-defined structured data classes
+- Case 1.5 handles list container wrappers
+- They're at the same inheritance level, not parent-child
**Requirements:**
-- All items within the `ListContent` must be subclasses of `StuffContent`
+- All items within the `ListContent` must be `StuffContent` objects (this includes both `StructuredContent` and native content like `TextContent`, `ImageContent`)
- All items must be of the same type
- The `ListContent` cannot be empty
-- Concept resolution follows Case 1.3 rules (inferred from the first item's class name, not from ListContent)
+- Concept is inferred from the first item's class name (not from "ListContent")
**Use Case:** This format is useful when you already have data wrapped in a `ListContent` object from a previous pipeline execution or when working with Pipelex's internal data structures.
@@ -292,7 +305,7 @@ Use the explicit format `{"concept": "...", "content": "..."}` when you need pre
**Result:** `ListContent` with multiple `TextContent` items
-### 2.3: StuffContent Object with Concept
+### 2.3: Structured Object with Concept
```json
{
@@ -325,7 +338,7 @@ When you specify a concept name without a domain prefix:
This explicitly tells Pipelex to use the `Invoice` concept from the `accounting` domain.
-### 2.4: List of StuffContent Objects
+### 2.4: List of Structured Objects
```json
{
@@ -616,10 +629,221 @@ When you provide `plx_content`:
- `404 Not Found`: Pipeline not found
- `500 Internal Server Error`: Server error
--
+### Common Errors
+
+**Concept Not Found**
+```json
+{
+ "status": "error",
+ "error": "Concept 'UnknownConcept' not found in the library"
+}
+```
+
+**Ambiguous Concept**
+```json
+{
+ "status": "error",
+ "error": "Ambiguous concept: Found 'Invoice' in domains: accounting, billing. Use 'domain.Invoice' format."
+}
+```
+
+**Invalid Input Type**
+```json
+{
+ "status": "error",
+ "error": "Trying to create a Stuff from a list of strings but the items are not of the same type"
+}
+```
+
+---
+
+## Best Practices
+
+### Input Design
+
+1. **Use Direct Format for Simple Inputs**
+ ```json
+ // ✅ Good
+ { "text": "Hello" }
+
+ // ❌ Unnecessary
+ { "text": { "concept": "Text", "content": "Hello" } }
+ ```
+
+2. **Be Explicit with Custom Concepts**
+ ```json
+ // ✅ Good - clear and unambiguous
+ { "invoice": { "concept": "accounting.Invoice", "content": {...} } }
+ ```
+
+3. **Validate Before Sending**
+ - Ensure all required fields are present
+ - Match field types to concept structure
+ - Use domain prefixes when concepts might be ambiguous
+
+### Performance Tips
+
+1. **Batch Processing**: Use list inputs when processing multiple items
+2. **Reuse Connections**: Keep the client instance for multiple requests
+3. **Handle Async Properly**: Use proper async/await patterns in Python
+
+### Security
+
+1. **Protect API Keys**: Never commit API keys to version control
+2. **Use Environment Variables**: Store credentials securely
+ ```python
+ import os
+ api_token = os.getenv("PIPELEX_API_TOKEN")
+ ```
+
+---
+
+## Client Libraries
+
+### Python
+
+#### Installation
+
+```bash
+pip install pipelex
+```
+
+#### Basic Usage (Direct Text Input)
+
+```python
+from pipelex.client import PipelexClient
+
+client = PipelexClient(api_token="YOUR_API_KEY")
+
+# Simple text input - no need for concept/content structure
+response = await client.execute_pipeline(
+ pipe_code="analyze_sentiment",
+ inputs={
+ "text": "This is amazing!"
+ }
+)
+
+print(response.pipe_output.working_memory)
+```
+
+#### Structured Input
+
+```python
+from pipelex.client import PipelexClient
+
+client = PipelexClient(api_token="YOUR_API_KEY")
+
+# Explicit concept and structured content
+response = await client.execute_pipeline(
+ pipe_code="extract_invoice",
+ inputs={
+ "document": {
+ "concept": "PDF",
+ "content": {
+ "url": "https://example.com/invoice.pdf"
+ }
+ }
+ }
+)
+
+# Access the main output
+invoice = response.pipe_output.working_memory.root["invoice"]
+print(f"Invoice Number: {invoice['content']['invoice_number']}")
+```
+
+#### Multiple Inputs with Mixed Formats
+
+```python
+from pipelex.client import PipelexClient
+
+client = PipelexClient(api_token="YOUR_API_KEY")
+
+response = await client.execute_pipeline(
+ pipe_code="contract_analysis",
+ inputs={
+ # Direct text input
+ "contract_text": "This is the contract text...",
+
+ # Structured input with explicit concept
+ "analysis_config": {
+ "concept": "AnalysisConfig",
+ "content": {
+ "priority": "high",
+ "focus_areas": ["liability", "termination"]
+ }
+ },
+
+ # Direct list input
+ "reference_docs": ["doc1", "doc2", "doc3"]
+ }
+)
+
+print(response.pipeline_state)
+print(response.main_stuff_name)
+```
+
+#### Using StructuredContent Objects (Advanced)
+
+```python
+from pipelex.client import PipelexClient
+from my_project.invoices.invoice_struct import Invoice, InvoiceLineItem
+
+client = PipelexClient(api_token="YOUR_API_KEY")
+
+# Create StructuredContent objects directly
+invoice_data = Invoice(
+ invoice_number="INV-001",
+ amount=1250.00,
+ line_items=[
+ InvoiceLineItem(description="Service A", amount=500.00),
+ InvoiceLineItem(description="Service B", amount=750.00)
+ ]
+)
+
+# Pass StructuredContent object directly (Case 1.3)
+response = await client.execute_pipeline(
+ pipe_code="validate_invoice",
+ inputs={
+ "invoice": invoice_data
+ }
+)
+```
+
+#### Using Domain-Prefixed Concepts
+
+```python
+from pipelex.client import PipelexClient
+
+client = PipelexClient(api_token="YOUR_API_KEY")
+
+response = await client.execute_pipeline(
+ pipe_code="multi_domain_processing",
+ inputs={
+ "accounting_invoice": {
+ "concept": "accounting.Invoice", # From accounting domain
+ "content": {
+ "invoice_number": "INV-001",
+ "amount": 1250.00
+ }
+ },
+ "billing_invoice": {
+ "concept": "billing.Invoice", # From billing domain
+ "content": {
+ "customer_id": "CUST-123",
+ "period": "2025-10"
+ }
+ }
+ }
+)
+```
+
+---
+
+## Support
For questions or issues:
-- Discord: https://go.pipelex.com/discord
-- GitHub: https://github.com/pipelex/pipelex
+- **Documentation**: [https://docs.pipelex.ai](https://docs.pipelex.ai)
+- **Discord Community**: [https://go.pipelex.com/discord](https://go.pipelex.com/discord)
+- **GitHub**: [https://github.com/pipelex/pipelex](https://github.com/pipelex/pipelex)
+- **Email**: [[email protected]](mailto:[email protected])
diff --git a/mkdocs.yml b/mkdocs.yml
index a3c58a396..90ce4672c 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -132,6 +132,8 @@ nav:
- LLM Structured Generation: pages/build-reliable-ai-workflows-with-pipelex/llm-structured-generation-config.md
- LLM Prompting Style: pages/build-reliable-ai-workflows-with-pipelex/adapt-to-llm-prompting-style-openai-anthropic-mistral.md
- LLM Providers & Models: pages/configuration/config-technical/inference-backend-config.md
+ - API Reference:
+ - API Guide: pages/api/index.md
- Configuration:
- Overview: pages/configuration/index.md
- Pipeline Validation Configuration:
diff --git a/pipelex/client/implicit_memory.py b/pipelex/client/implicit_memory.py
deleted file mode 100644
index 0d2926414..000000000
--- a/pipelex/client/implicit_memory.py
+++ /dev/null
@@ -1,219 +0,0 @@
-from pipelex.core.concepts.concept_factory import ConceptFactory
-from pipelex.core.concepts.concept_native import NativeConceptCode
-from pipelex.core.stuffs.list_content import ListContent
-from pipelex.core.stuffs.structured_content import StructuredContent
-from pipelex.core.stuffs.stuff import Stuff
-from pipelex.core.stuffs.text_content import TextContent
-
-
-class MySubClass(StructuredContent):
- arg4: str
-
-
-class MyConcept(StructuredContent):
- arg1: str
- arg2: int
- arg3: MySubClass
-
-
-####################################################################################################
-## CASE 1: I have directly the content.
-# Possible solutions:
-# 1.1: stuff_data is a string.
-# 1.2: stuff_data is a list of strings.
-# 1.3: stuff_data is a StuffContent object.
-# 1.3a: Regular StuffContent object
-# 1.3b: ListContent of StuffContent objects (special subcase)
-# 1.4: stuff_data is a list of StuffContent objects.
-####################################################################################################
-
-# 1.1: Content is a string.
-stuff_data11 = "my text"
-
-# Stuff should be
-stuff11 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.TEXT),
- content=TextContent(text="my_text"),
-)
-
-# 1.2: Content is a list of strings
-stuff_data12 = ["test1", "test2", "test3"]
-
-# Concept string needs to be compatible strictly with the concept native.Text. Otherwise it should raise an error.
-
-stuff12 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.TEXT),
- content=ListContent(items=[TextContent(text="test1"), TextContent(text="test2"), TextContent(text="test3")]),
-)
-
-# 1.3: Content is a StuffContent object.
-stuff_data13 = MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))
-
-# It should look in all the library for the concept with the same name.
-# If no search domains are provided and we find 2 or more concepts with the same name, it should raise an error.
-# If no concept is found, it should raise an error.
-
-stuff13 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make(concept_code="MyConcept", domain="domain", description="description", structure_class_name=MyConcept.__name__),
- content=MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
-)
-
-# 1.4: content is a list of StuffContent objects.
-stuff_data14 = [MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")), MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))]
-
-# It should look in all the library for the concept with the same name.
-# If no search domains are provided and we find 2 or more concepts with the same name, it should raise an error.
-# EVERY item of the list should be of the same type. Otherwise it should raise an error.
-# If no concept is found, it should raise an error.
-
-stuff14 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make(concept_code="MyConcept", domain="domain", description="description", structure_class_name=MyConcept.__name__),
- content=ListContent(
- items=[MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")), MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))]
- ),
-)
-
-# 1.3b (formerly 1.5): content is a ListContent of StuffContent objects.
-# This is a special subcase of 1.3 since ListContent is itself a StuffContent.
-stuff_data13b: ListContent[MyConcept] = ListContent(
- items=[MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")), MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))]
-)
-
-# It should check that every item in the list is a subclass of StuffContent.
-# If not, it should raise an error.
-# If every item is of the same type, it should create a Stuff with the concept of the first item (not from ListContent itself).
-# If every item is not of the same type, it should raise an error.
-# If the ListContent is empty, it should raise an error.
-# If no concept is found, it should raise an error. To find the concept, it should look in all the library for the concept with the same name.
-# If no search domains are provided and we find 2 or more concepts with the same name, it should raise an error.
-# If the domain is specified or found, it should check that the structure corresponds with the given content.
-# Otherwise it should raise an error.
-
-stuff13b = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make(concept_code="MyConcept", domain="domain", description="description", structure_class_name=MyConcept.__name__),
- content=ListContent(
- items=[MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")), MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))]
- ),
-)
-
-####################################################################################################
-## CASE 2: Here, we HAVE the key "concept_string" AND the key "content".
-# The value of the "content" key can Either be a:
-# 2.1: a string.
-# 2.2: a list of strings.
-# 2.3: a StuffContent object.
-# 2.4: a list of StuffContent objects.
-# 2.5: a dict (corresponding to the concept right above).
-# 2.6: a list of dict (corresponding to the concept right above).
-####################################################################################################
-
-# 2.1: Content is a string
-
-stuff_data21 = {"concept": "concept_string", "content": "my text"}
-
-# Here, the concept can either be Text, native.Text or any other concept. But if its any other concept,
-# it should be stricly compatible with the concept native.Text.
-
-stuff21 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.TEXT), # Or else
- content=TextContent(text="my text"),
-)
-
-# 2.2: Content is a list of strings
-stuff_data22 = {"concept": "concept_string", "content": ["text1", "text2", "text3"]}
-
-# Here, the concept can either be Text, native.Text or any other concept. But if its any other concept,
-# it should be stricly compatible with the concept native.Text.
-
-stuff22 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.TEXT), # Or else
- content=ListContent(items=[TextContent(text="text1"), TextContent(text="text2"), TextContent(text="text3")]),
-)
-
-# 2.3: Content is a StuffContent object
-stuff_data23 = {"concept": "concept_string", "content": MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))}
-
-# For the concept mentioned: If no domain is specified, it should look in all the library for the concept with the same name.
-# If no search domains are provided and we find 2 or more concepts with the same name, it should raise an error
-# and ask the user to specify the domain.
-# If the domain is specified or found, it should check that the structure corresponds with the given content.
-# Otherwise it should raise an error.
-
-stuff23 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make(concept_code="MyConcept", domain="domain", description="description", structure_class_name=MyConcept.__name__),
- content=MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
-)
-
-# 2.4: Content is a list of StuffContent objects
-stuff_data24 = {
- "concept": "concept_string",
- "content": [MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")), MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))],
-}
-
-stuff24 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make(concept_code="MyConcept", domain="domain", description="description", structure_class_name=MyConcept.__name__),
- content=ListContent(
- items=[MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")), MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4"))]
- ),
-)
-
-# 2.5: Content is a dict
-stuff_data25 = {"concept": "concept_string", "content": {"arg1": "something", "arg2": 1, "arg3": {"arg4": "something else else"}}}
-
-# For the concept mentioned: If no domain is specified, it should look in all the library for the concept with the same name.
-# If no search domains are provided and we find 2 or more concepts with the same name, it should raise an error
-# and ask the user to specify the domain.
-# If the domain is specified or found, it should check that the structure corresponds with the given content by validating the model.
-# Otherwise it should raise an error.
-
-stuff25 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make(concept_code="MyConcept", domain="domain", description="description", structure_class_name=MyConcept.__name__),
- content=MyConcept(arg1="something", arg2=1, arg3=MySubClass(arg4="something else else")),
-)
-
-# 2.6: Content is a list of dict
-stuff_data26 = {
- "concept": "concept_string",
- "content": [
- {"arg1": "something", "arg2": 1, "arg3": {"arg4": "something else else"}},
- {"arg1": "something else", "arg2": 2, "arg3": {"arg4": "something else else else"}},
- ],
-}
-
-# For the concept mentioned: If no domain is specified, it should look in all the library for the concept with the same name.
-# If no search domains are provided and we find 2 or more concepts with the same name, it
-# should raise an error and ask the user to specify the domain.
-# If the domain is specified or found, it should check that the structure corresponds with the given content by validating the model.
-# Otherwise it should raise an error.
-
-stuff26 = Stuff(
- stuff_code="stuff_code",
- stuff_name="stuff_name",
- concept=ConceptFactory.make(concept_code="MyConcept", domain="domain", description="description", structure_class_name=MyConcept.__name__),
- content=ListContent(
- items=[
- MyConcept(arg1="something", arg2=1, arg3=MySubClass(arg4="something else else")),
- MyConcept(arg1="something else", arg2=2, arg3=MySubClass(arg4="something else else else")),
- ]
- ),
-)
diff --git a/pipelex/core/stuffs/stuff_factory.py b/pipelex/core/stuffs/stuff_factory.py
index b64a88ce0..81f32640f 100644
--- a/pipelex/core/stuffs/stuff_factory.py
+++ b/pipelex/core/stuffs/stuff_factory.py
@@ -10,6 +10,7 @@ from pipelex.core.concepts.concept_factory import ConceptFactory
from pipelex.core.concepts.concept_library import ConceptLibraryConceptNotFoundError
from pipelex.core.concepts.concept_native import NativeConceptCode
from pipelex.core.stuffs.list_content import ListContent
+from pipelex.core.stuffs.structured_content import StructuredContent
from pipelex.core.stuffs.stuff import Stuff
from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.core.stuffs.text_content import TextContent
@@ -132,10 +133,12 @@ class StuffFactory:
Case 1: Direct content (no 'concept' key)
1.1: str → TextContent with Text concept
1.2: list[str] → ListContent[TextContent] with Text concept
- 1.3: StuffContent → Use the StuffContent, infer concept from class name
- 1.3a: Regular StuffContent → Infer concept from the class itself
- 1.3b (was 1.5): ListContent[StuffContent] → Infer concept from first item's class
+ 1.3: StructuredContent → Use the StructuredContent, infer concept from class name
1.4: list[StuffContent] → ListContent[StuffContent], infer concept from first item
+ 1.5: ListContent[StuffContent] → Use the ListContent, infer concept from first item
+
+ Note: StructuredContent (1.3) and ListContent (1.5) are separate cases at the same level.
+ Both inherit from StuffContent but handle different content types.
Case 2: Dict with 'concept' AND 'content' keys
2.1/2.1b: {"concept": "Text"/"native.Text", "content": str} → TextContent with Text concept
@@ -159,58 +162,79 @@ class StuffFactory:
code=code,
)
- # Case 1.3: StuffContent object → Infer concept from class name
- if issubclass(type(stuff_content_or_data), StuffContent):
- stuff_content = cast("StuffContent", stuff_content_or_data)
+ # Case 1.5: ListContent[StuffContent] → Use the ListContent, infer concept from first item
+ # Must check BEFORE Case 1.3 because ListContent is also a StuffContent
+ if isinstance(stuff_content_or_data, ListContent):
+ list_content = cast("ListContent[StuffContent]", stuff_content_or_data)
- # Case 1.3b: Special handling for ListContent (subcase of 1.3)
- if isinstance(stuff_content_or_data, ListContent):
- list_content = cast("ListContent[StuffContent]", stuff_content_or_data)
+ if len(list_content.items) == 0:
+ msg = f"Cannot create Stuff '{name}' from empty ListContent"
+ raise StuffFactoryError(msg)
- if len(list_content.items) == 0:
- msg = f"Cannot create Stuff '{name}' from empty ListContent"
- raise StuffFactoryError(msg)
+ first_item = list_content.items[0]
- first_item = list_content.items[0]
+ # Check that items are StuffContent
+ if not isinstance(first_item, StuffContent): # pyright: ignore[reportUnnecessaryIsInstance]
+ msg = (
+ f"Trying to create a Stuff '{name}' from a ListContent but "
+ f"the items are not StuffContent. First item is of type {type(first_item).__name__}. "
+ "ListContent items must be subclasses of StuffContent."
+ )
+ raise StuffFactoryError(msg)
- # Check that items are StuffContent
- if not isinstance(first_item, StuffContent): # pyright: ignore[reportUnnecessaryIsInstance]
+ # Check all items are of the same type
+ for item in list_content.items:
+ if not isinstance(item, type(first_item)):
msg = (
- f"Trying to create a Stuff '{name}' from a ListContent but "
- f"the items are not StuffContent. First item is of type {type(first_item).__name__}. "
- "ListContent items must be subclasses of StuffContent."
+ f"Trying to create a Stuff '{name}' from a ListContent of '{type(first_item).__name__}' "
+ f"but the items are not of the same type. Especially, items {item} is of type {type(item).__name__}. "
+ "Every items of the list should be an identical type."
)
raise StuffFactoryError(msg)
- # Check all items are of the same type
- for item in list_content.items:
- if not isinstance(item, type(first_item)):
- msg = (
- f"Trying to create a Stuff '{name}' from a ListContent of '{type(first_item).__name__}' "
- f"but the items are not of the same type. Especially, items {item} is of type {type(item).__name__}. "
- "Every items of the list should be an identical type."
- )
- raise StuffFactoryError(msg)
+ # Get concept from first item's class name
+ content_class_name = type(first_item).__name__
- # Get concept from first item's class name
- content_class_name = type(first_item).__name__
+ # Check if it's a native concept
+ if "Content" in content_class_name and NativeConceptCode.is_native_concept(concept_code=content_class_name.split("Content")[0]):
+ concept = get_native_concept(native_concept=NativeConceptCode(content_class_name.split("Content")[0]))
else:
- # Case 1.3a: Regular StuffContent → Get concept from the StuffContent class name itself
- content_class_name = stuff_content_or_data.__class__.__name__
+ try:
+ concept = concept_library.get_required_concept_from_concept_string_or_code(
+ concept_string_or_code=content_class_name, search_domains=search_domains
+ )
+ except ConceptLibraryConceptNotFoundError as exc:
+ msg = (
+ f"Trying to create a Stuff '{name}' from a ListContent but "
+ f"the concept of name '{content_class_name}' is not found in the library"
+ )
+ raise StuffFactoryError(msg) from exc
+
+ return cls.make_stuff(
+ concept=concept,
+ content=list_content,
+ name=name,
+ code=code,
+ )
+
+ # Case 1.3: StuffContent object (includes both native and StructuredContent) → Infer concept from class name
+ if isinstance(stuff_content_or_data, StuffContent):
+ stuff_content = stuff_content_or_data
+ content_class_name = stuff_content_or_data.__class__.__name__
# Check if it's a native concept
if "Content" in content_class_name and NativeConceptCode.is_native_concept(concept_code=content_class_name.split("Content")[0]):
# It's a native concept like TextContent, ImageContent, etc.
concept = get_native_concept(native_concept=NativeConceptCode(content_class_name.split("Content")[0]))
else:
+ # It's a StructuredContent, try to find the concept
try:
- # It's a custom StuffContent, try to find the concept
concept = concept_library.get_required_concept_from_concept_string_or_code(
concept_string_or_code=content_class_name, search_domains=search_domains
)
except ConceptLibraryConceptNotFoundError as exc:
msg = (
- f"Trying to create a Stuff '{name}' from a custom StuffContent '{content_class_name}' "
+ f"Trying to create a Stuff '{name}' from a StuffContent '{content_class_name}' "
f"but the concept of name '{content_class_name}' is not found in the library"
)
raise StuffFactoryError(msg) from exc
@@ -272,8 +296,10 @@ class StuffFactory:
concept_string_or_code=content_class_name, search_domains=search_domains
)
except ConceptLibraryConceptNotFoundError as exc:
- msg = f"Trying to create a Stuff '{name}' from a list of StuffContent but"
- "the concept of name '{content_class_name}' is not found in the library"
+ msg = (
+ f"Trying to create a Stuff '{name}' from a list of StuffContent but "
+ f"the concept of name '{content_class_name}' is not found in the library"
+ )
raise StuffFactoryError(msg) from exc
return cls.make_stuff(
@@ -339,8 +365,8 @@ class StuffFactory:
)
raise StuffFactoryError(msg)
- # Case 2.3: content is a StuffContent object
- if isinstance(content, StuffContent):
+ # Case 2.3: content is a StructuredContent object
+ if isinstance(content, StructuredContent):
if concept.structure_class_name != content.__class__.__name__:
msg = (
f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData "
@@ -404,12 +430,12 @@ class StuffFactory:
msg = f"Concept '{concept_string}' is not compatible with list of text content"
raise StuffFactoryError(msg)
- # Case 2.4: list[StuffContent]
- if isinstance(first_item, StuffContent):
+ # Case 2.4: list[StructuredContent]
+ if isinstance(first_item, StructuredContent):
for item in list_content_2:
if not isinstance(item, type(first_item)):
msg = (
- f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a list of StuffContent "
+ f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a list of StructuredContent "
"but the items are not of the same type. Every items of the list should be a identical type. "
f"If its a '{type(first_item).__name__}', everything should be a '{type(first_item).__name__}'."
)
@@ -417,7 +443,7 @@ class StuffFactory:
return cls.make_stuff(
concept=concept,
- content=ListContent(items=cast("list[StuffContent]", list_content_2)),
+ content=ListContent(items=cast("list[StructuredContent]", list_content_2)),
name=name,
code=code,
)