Skip to content

API Reference

TenzinGayche edited this page Dec 17, 2025 · 1 revision

API Reference

Complete API documentation for all functions, classes, and modules in the UCCA Generator.


📦 Module: ucca_generator.models

UCCANode

Pydantic model representing a single node in the UCCA graph.

class UCCANode(BaseModel):
    id: str
    type: str
    text: str
    english_text: str
    implicit: str
    parent_id: str = ""
    children: List[str] = []
    descriptor: str

See Data-Models#uccanode for detailed field documentation.


UCCAGraph

Pydantic model representing a complete UCCA graph.

class UCCAGraph(BaseModel):
    nodes: List[UCCANode]
    root_id: str

Methods:

  • model_dump() - Convert to dictionary
  • model_dump_json() - Convert to JSON string
  • model_json_schema() - Get JSON schema

ActionableSuggestion

Pydantic model for a single improvement suggestion.

class ActionableSuggestion(BaseModel):
    suggestion_type: str
    target_node_ids: Optional[List[str]] = []
    description: str
    relevant_commentary_snippets: Optional[List[str]] = []

StructuredFeedback

Pydantic model for complete evaluation feedback.

class StructuredFeedback(BaseModel):
    grade: Literal["bad", "okay", "good", "great"]
    overall_summary: str
    specific_suggestions: List[ActionableSuggestion] = []

State (Simple Workflow)

TypedDict for simple workflow state.

class State(TypedDict):
    input_text: str
    ucca_graph_json_str: Optional[str]
    ucca_graph: Optional[UCCAGraph]
    error_message: Optional[str]

📦 Module: ucca_generator.workflow

Constants

UCCA_GENERATION_PROMPT_TEMPLATE

Template string for simple UCCA generation. Contains placeholders for:

  • {UCCA_GRAPH_SCHEMA_JSON} - Graph schema
  • {UCCA_NODE_SCHEMA_JSON} - Node schema
  • {{input_text}} - User input (double braces for .format())

llm

LangChain ChatAnthropic instance.

llm = ChatAnthropic(model="claude-3-sonnet-latest", max_tokens=8192)

generate_ucca_graph_step(state: State) -> State

Generates a UCCA graph from input text using the LLM.

Parameters:

Name Type Description
state State Current workflow state with input_text

Returns:

Type Description
State Updated state with ucca_graph or error_message

Process:

  1. Formats prompt with input text
  2. Invokes LLM
  3. Cleans JSON (removes markdown code blocks)
  4. Parses into UCCAGraph
  5. Returns updated state

Example:

from ucca_generator.workflow import generate_ucca_graph_step
from ucca_generator.models import State

state: State = {
    "input_text": "མི་རྟག་པ།",
    "ucca_graph_json_str": None,
    "ucca_graph": None,
    "error_message": None
}

result = generate_ucca_graph_step(state)

📦 Module: ucca_generator.ucca_generator

run_ucca_generation_pipeline(input_text: str) -> State

Main entry point for UCCA generation.

Parameters:

Name Type Description
input_text str Tibetan text to analyze

Returns:

Type Description
State Final state with graph or error

Example:

from ucca_generator.ucca_generator import run_ucca_generation_pipeline

result = run_ucca_generation_pipeline("མི་རྟག་པ་སྒོམ་པ།")

if result['ucca_graph']:
    print(f"Root: {result['ucca_graph'].root_id}")
    for node in result['ucca_graph'].nodes:
        print(f"  {node.id}: {node.type}")
else:
    print(f"Error: {result['error_message']}")

📦 Module: ucca_generator.ucca_agent

Constants

llm

LangChain ChatAnthropic instance for agent workflow.

llm = ChatAnthropic(model="claude-3-7-sonnet-latest", max_tokens=8000)

optimizer_workflow

Compiled LangGraph workflow. Ready to invoke.

optimizer_workflow = optimizer_builder.compile()

State (Agent Workflow)

Extended TypedDict for agent workflow.

class State(TypedDict):
    source: str
    sanskrit: str
    language: str
    feedback_history: List[str]
    commentary1: str
    commentary2: str
    commentary3: str
    itteration: int
    format_iteration: int
    source_ucca: List[UCCAGraph]
    latest_structured_suggestions: List[ActionableSuggestion]
    grade: str

ucca_generator(state: State) -> dict

Generates or refines UCCA graph based on state.

Parameters:

Name Type Description
state State Current workflow state

Returns:

Type Description
dict Partial state update with new graph

Return Keys:

  • source_ucca: Updated list with new graph appended
  • itteration: Updated iteration count

Behavior:

  • First call (no feedback): Uses get_ucca_generation_prompt()
  • Subsequent calls: Uses refinement prompt with latest feedback

ucca_evaluator(state: State) -> dict

Evaluates the latest UCCA graph against commentaries.

Parameters:

Name Type Description
state State Current workflow state with graph

Returns:

Type Description
dict Partial state update with evaluation results

Return Keys:

  • grade: Quality assessment ("bad"/"okay"/"good"/"great")
  • feedback_history: Updated feedback list
  • latest_structured_suggestions: List of ActionableSuggestion
  • itteration: Current iteration count

route_ucca(state: State) -> str

Determines workflow routing based on evaluation.

Parameters:

Name Type Description
state State Current state with grade

Returns:

Type Description
str Route name: "Accepted" or "Rejected + Feedback"

Logic:

if state["grade"] == "great":
    return "Accepted"
elif state["itteration"] >= 1:
    return "Accepted"
else:
    return "Rejected + Feedback"

get_ucca_generation_prompt(text: str, language: str = "Tibetan") -> str

Generates the comprehensive prompt for UCCA graph creation.

Parameters:

Name Type Default Description
text str - Tibetan text to analyze
language str "Tibetan" Language identifier

Returns:

Type Description
str Complete prompt string (~500 lines)

See Prompts#2️⃣-advanced-generation-prompt-ucca_agentpy for full template.


get_source_ucca_refinement_prompt(...) -> str

Generates the evaluation prompt with commentaries.

Parameters:

Name Type Default Description
source_text str - Tibetan source text
current_ucca_analysis UCCAGraph - Graph to evaluate
commentaries list[str] - List of commentary texts
sanskrit str "" Sanskrit reference
language str "Tibetan" Language identifier

Returns:

Type Description
str Complete evaluation prompt

See Prompts#3️⃣-evaluationrefinement-prompt-ucca_agentpy for full template.


ucca_graph_to_text(ucca_graph: UCCAGraph) -> str

Converts a UCCA graph to human-readable text format.

Parameters:

Name Type Description
ucca_graph UCCAGraph Graph to convert

Returns:

Type Description
str Formatted text representation

Example Output:

UCCA Graph (Root ID: 0)
|- [0] Type: Scene - "སྔོན་ཆད་མ་བྱུང་བ་ཡང་འདིར་བརྗོད་མེད། །"
  |- [1] Type: Implicit Participant-Agent - ""
  |- [2] Type: Process - "བརྗོད་མེད"
  |- [3] Type: Participant-Location - "འདིར"

Total nodes: 4

display_ucca_graph(state: State) -> None

Prints the latest UCCA graph from state.

Parameters:

Name Type Description
state State Workflow state

Returns: None (prints to stdout)


🚀 Usage Examples

Simple Pipeline

from ucca_generator.ucca_generator import run_ucca_generation_pipeline

# Single text
result = run_ucca_generation_pipeline("མི་རྟག་པ་སྒོམ་པ།")

if result['ucca_graph']:
    graph = result['ucca_graph']
    print(f"Generated graph with {len(graph.nodes)} nodes")
    
    # Access nodes
    for node in graph.nodes:
        print(f"{node.id}: {node.type} - {node.english_text}")
        
    # Export to JSON
    json_str = graph.model_dump_json(indent=2)

Agent Workflow

from ucca_generator.ucca_agent import optimizer_workflow

# Prepare state with commentaries
state = {
    "source": "མི་རྟག་པ་སྒོམ་པ་ལ་དགོས་པ་ཅི་ཡོད།",
    "sanskrit": "अनित्यता भावना",
    "language": "Tibetan",
    "feedback_history": [],
    "commentary1": "This verse asks about the purpose of meditation on impermanence...",
    "commentary2": "The practitioner should contemplate...",
    "commentary3": "According to Nagarjuna...",
    "itteration": 0,
    "format_iteration": 0,
    "source_ucca": [],
    "latest_structured_suggestions": [],
    "grade": ""
}

# Run workflow
result = optimizer_workflow.invoke(state)

# Get final graph
final_graph = result["source_ucca"][-1]
print(f"Final grade: {result['grade']}")
print(f"Iterations: {len(result['source_ucca'])}")

# Review feedback history
for feedback in result["feedback_history"]:
    print(feedback)

Batch Processing

from ucca_generator.ucca_generator import run_ucca_generation_pipeline
import json

texts = [
    "མི་རྟག་པ།",
    "སྡུག་བསྔལ།",
    "སྟོང་པ་ཉིད།"
]

results = []
for text in texts:
    result = run_ucca_generation_pipeline(text)
    if result['ucca_graph']:
        results.append({
            "input": text,
            "graph": result['ucca_graph'].model_dump()
        })

# Save results
with open("ucca_results.json", "w") as f:
    json.dump(results, f, indent=2, ensure_ascii=False)

Working with Graphs

from ucca_generator.models import UCCAGraph, UCCANode

# Create graph programmatically
graph = UCCAGraph(
    root_id="0",
    nodes=[
        UCCANode(
            id="0",
            type="Scene",
            text="མི་རྟག་པ།",
            english_text="Impermanence",
            implicit="",
            parent_id="",
            children=["1"],
            descriptor="Root scene about impermanence"
        ),
        UCCANode(
            id="1",
            type="State",
            text="མི་རྟག་པ",
            english_text="impermanence",
            implicit="",
            parent_id="0",
            children=[],
            descriptor="The state of being impermanent"
        )
    ]
)

# Validate
print(graph.model_dump_json(indent=2))

# Find specific nodes
processes = [n for n in graph.nodes if n.type == "Process"]
implicit = [n for n in graph.nodes if n.type.startswith("Implicit")]

🔗 Related Pages

Clone this wiki locally