Skip to content

Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.

feat: add Earnings Call Transcripts templates - EarningsCallSummary (AutoModel) - call overview - ManagementGuidanceList (AutoList) - forward guidance - AnalystQAGraph (AutoGraph) - Q&A interactions - CallSentimentHypergraph (AutoHypergraph) - topic-sentiment

yuxizheb718b3d019e2
diff --git a/hyperextract/templates/en/finance/analyst_qa_graph.py b/hyperextract/templates/en/finance/analyst_qa_graph.py
new file mode 100644
index 0000000..13fa20b
--- /dev/null
+++ b/hyperextract/templates/en/finance/analyst_qa_graph.py
@@ -0,0 +1,200 @@
+"""Analyst Q&A Graph - Maps analyst questions to management responses.
+
+Extracts the question-and-answer interactions from earnings call Q&A sessions,
+capturing concerns raised and commitments made for analyst focus analysis.
+"""
+
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoGraph
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class QAParticipant(BaseModel):
+ """
+ A participant in the earnings call Q&A session.
+ """
+
+ name: str = Field(
+ description="Name of the participant (e.g., analyst name, CEO, CFO)."
+ )
+ role: str = Field(
+ description="Role: 'Analyst', 'CEO', 'CFO', 'COO', 'CTO', 'IR Head', 'Other Management'."
+ )
+ firm: Optional[str] = Field(
+ None,
+ description="Firm affiliation (e.g., 'JPMorgan', 'Goldman Sachs') for analysts.",
+ )
+
+
+class QAInteraction(BaseModel):
+ """
+ A question-answer interaction between analyst and management.
+ """
+
+ source: str = Field(description="The questioner's name (analyst).")
+ target: str = Field(description="The responder's name (management).")
+ topic: str = Field(
+ description="Topic of the question (e.g., 'Margin outlook', 'AI strategy', 'Capital allocation')."
+ )
+ question_summary: str = Field(
+ description="Concise summary of the analyst's question."
+ )
+ answer_summary: str = Field(
+ description="Concise summary of management's response."
+ )
+ sentiment: Optional[str] = Field(
+ None,
+ description="Tone of the exchange: 'Constructive', 'Pressing', 'Reassuring', 'Evasive', 'Direct'.",
+ )
+ commitment_made: Optional[str] = Field(
+ None,
+ description="Any specific commitment from management (e.g., 'will provide update next quarter').",
+ )
+ follow_up: Optional[bool] = Field(
+ None,
+ description="Whether the analyst asked a follow-up question on the same topic.",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an earnings call analyst. Extract the Q&A interactions between analysts and management "
+ "from this earnings call transcript.\n\n"
+ "Rules:\n"
+ "- Identify each analyst and management participant.\n"
+ "- Summarize each question and its corresponding answer.\n"
+ "- Capture the topic and sentiment of each exchange.\n"
+ "- Note any commitments management makes.\n"
+ "- Track follow-up questions on the same topic."
+)
+
+_NODE_PROMPT = (
+ "You are an earnings call analyst. Extract all Q&A participants (Nodes).\n\n"
+ "Extraction Rules:\n"
+ "- Identify analysts by name and firm.\n"
+ "- Identify management participants by name and role.\n"
+ "- DO NOT extract Q&A interactions at this stage."
+)
+
+_EDGE_PROMPT = (
+ "You are an earnings call analyst. Given the participants, extract Q&A interactions (Edges).\n\n"
+ "Extraction Rules:\n"
+ "- Connect each analyst question to the management response.\n"
+ "- Summarize both the question and answer concisely.\n"
+ "- Capture the topic, sentiment, and any commitments.\n"
+ "- Only create edges between nodes that exist in the provided lists."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class AnalystQAGraph(AutoGraph[QAParticipant, QAInteraction]):
+ """
+ Applicable to: Earnings Call Transcripts (Q&A section), Investor Day Q&A,
+ Annual Meeting Q&A, Analyst Day Transcripts.
+
+ Template for mapping analyst questions to management responses in earnings calls.
+ Enables analyst focus analysis, commitment tracking, and identification of
+ key concerns across the analyst community.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> qa = AnalystQAGraph(llm_client=llm, embedder=embedder)
+ >>> transcript = "Analyst: Can you discuss your margin outlook? CEO: We expect margins to..."
+ >>> qa.feed_text(transcript)
+ >>> qa.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Analyst Q&A Graph template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for Q&A extraction.
+ embedder (Embeddings): Embedding model for deduplication.
+ extraction_mode (str): "one_stage" or "two_stage".
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoGraph.
+ """
+ super().__init__(
+ node_schema=QAParticipant,
+ edge_schema=QAInteraction,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip().lower()}|{x.topic.lower()}|{x.target.strip().lower()}"
+ ),
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """
+ Visualize the analyst Q&A graph using OntoSight.
+
+ Args:
+ top_k_nodes_for_search (int): Number of participants to retrieve. Default 3.
+ top_k_edges_for_search (int): Number of Q&A interactions to retrieve. Default 3.
+ top_k_nodes_for_chat (int): Participants for chat context. Default 3.
+ top_k_edges_for_chat (int): Interactions for chat context. Default 3.
+ """
+
+ def node_label_extractor(node: QAParticipant) -> str:
+ firm = f" @ {node.firm}" if node.firm else ""
+ return f"{node.name} ({node.role}{firm})"
+
+ def edge_label_extractor(edge: QAInteraction) -> str:
+ sentiment = f" [{edge.sentiment}]" if edge.sentiment else ""
+ return f"{edge.topic}{sentiment}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/en/finance/call_sentiment_hypergraph.py b/hyperextract/templates/en/finance/call_sentiment_hypergraph.py
new file mode 100644
index 0000000..3670793
--- /dev/null
+++ b/hyperextract/templates/en/finance/call_sentiment_hypergraph.py
@@ -0,0 +1,198 @@
+"""Call Sentiment Hypergraph - Models topic-sentiment analysis across earnings calls.
+
+Models multi-dimensional sentiment: {Topic, Speaker, Sentiment, Driving Factor}
+across the call for sentiment-driven trading signals and tone shift detection.
+"""
+
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoHypergraph
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class CallTopic(BaseModel):
+ """
+ A topic, speaker, or sentiment driver discussed in an earnings call.
+ """
+
+ name: str = Field(
+ description="Name of the topic element (e.g., 'Revenue Growth', 'CEO Tim Cook', 'AI Investment Cycle', 'Cautious')."
+ )
+ element_type: str = Field(
+ description="Type: 'Topic', 'Speaker', 'Sentiment', 'Driving Factor'."
+ )
+ description: Optional[str] = Field(
+ None, description="Context or explanation for this element."
+ )
+
+
+class SentimentCluster(BaseModel):
+ """
+ A multi-dimensional sentiment cluster connecting topic, speaker, sentiment, and driver.
+ """
+
+ cluster_name: str = Field(
+ description="Descriptive name (e.g., 'CEO Positive on AI Revenue', 'CFO Cautious on Margins')."
+ )
+ participating_elements: List[str] = Field(
+ description="Names of all elements in this sentiment cluster (topic + speaker + sentiment + driver)."
+ )
+ sentiment_polarity: str = Field(
+ description="Overall sentiment: 'Bullish', 'Bearish', 'Neutral', 'Mixed'."
+ )
+ intensity: str = Field(
+ description="Sentiment intensity: 'Strong', 'Moderate', 'Mild'."
+ )
+ evidence: Optional[str] = Field(
+ None,
+ description="Key quote or paraphrase supporting the sentiment assessment.",
+ )
+ shift_from_prior: Optional[str] = Field(
+ None,
+ description="Change from prior quarter's tone if notable (e.g., 'More cautious than Q2', 'Upgraded from neutral').",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a sentiment analysis specialist for earnings calls. Extract topics, speakers, "
+ "sentiment signals, and their multi-dimensional relationships.\n\n"
+ "Rules:\n"
+ "- Identify key topics discussed (revenue, margins, guidance, strategy).\n"
+ "- Identify speakers and their roles.\n"
+ "- Assess sentiment polarity and intensity for each topic-speaker combination.\n"
+ "- A hyperedge connects a Topic + Speaker + Sentiment + Driving Factor.\n"
+ "- Note shifts from prior quarter's tone."
+)
+
+_NODE_PROMPT = (
+ "You are a sentiment analysis specialist. Extract all topics, speakers, sentiments, "
+ "and driving factors (Nodes) from the earnings call.\n\n"
+ "Extraction Rules:\n"
+ "- Identify financial topics discussed.\n"
+ "- Identify speakers (analysts, management).\n"
+ "- Identify sentiment labels and driving factors.\n"
+ "- DO NOT create sentiment clusters at this stage."
+)
+
+_EDGE_PROMPT = (
+ "You are a sentiment analysis specialist. Given the elements, create multi-dimensional "
+ "sentiment clusters (Hyperedges).\n\n"
+ "Extraction Rules:\n"
+ "- Each cluster connects a Topic + Speaker + Sentiment + Driving Factor.\n"
+ "- Assess overall polarity and intensity.\n"
+ "- Capture supporting evidence.\n"
+ "- Note tone shifts from prior quarters.\n"
+ "- Only reference elements that exist in the provided lists."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class CallSentimentHypergraph(AutoHypergraph[CallTopic, SentimentCluster]):
+ """
+ Applicable to: Earnings Call Transcripts, Investor Day Transcripts,
+ Management Presentations, Conference Transcripts.
+
+ Template for multi-dimensional sentiment analysis of earnings calls. Uses
+ hyperedges to model {Topic, Speaker, Sentiment, Driving Factor} clusters,
+ enabling sentiment-driven trading signals and tone shift detection.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> sentiment = CallSentimentHypergraph(llm_client=llm, embedder=embedder)
+ >>> transcript = "CEO: We are very excited about AI revenue growth..."
+ >>> sentiment.feed_text(transcript)
+ >>> sentiment.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Call Sentiment Hypergraph template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for sentiment extraction.
+ embedder (Embeddings): Embedding model for deduplication.
+ extraction_mode (str): "one_stage" or "two_stage".
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoHypergraph.
+ """
+ super().__init__(
+ node_schema=CallTopic,
+ edge_schema=SentimentCluster,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: x.cluster_name.strip().lower(),
+ nodes_in_edge_extractor=lambda x: tuple(
+ e.strip().lower() for e in x.participating_elements
+ ),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """
+ Visualize the call sentiment hypergraph using OntoSight.
+
+ Args:
+ top_k_nodes_for_search (int): Number of elements to retrieve. Default 3.
+ top_k_edges_for_search (int): Number of sentiment clusters to retrieve. Default 3.
+ top_k_nodes_for_chat (int): Elements for chat context. Default 3.
+ top_k_edges_for_chat (int): Clusters for chat context. Default 3.
+ """
+
+ def node_label_extractor(node: CallTopic) -> str:
+ return f"{node.name} [{node.element_type}]"
+
+ def edge_label_extractor(edge: SentimentCluster) -> str:
+ return f"[{edge.sentiment_polarity}/{edge.intensity}] {edge.cluster_name}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/en/finance/earnings_call_summary.py b/hyperextract/templates/en/finance/earnings_call_summary.py
new file mode 100644
index 0000000..e904323
--- /dev/null
+++ b/hyperextract/templates/en/finance/earnings_call_summary.py
@@ -0,0 +1,154 @@
+"""Earnings Call Summary - Extracts key metrics and tone from earnings calls.
+
+Extracts reported metrics (Revenue, EPS), management guidance, and overall call
+tone from quarterly conference call transcripts for review dashboards.
+"""
+
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from ontomem.merger import MergeStrategy
+from hyperextract.types import AutoModel
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class EarningsCallSummarySchema(BaseModel):
+ """
+ Structured summary of an earnings conference call.
+ """
+
+ company_name: Optional[str] = Field(
+ None, description="Name of the company."
+ )
+ ticker: Optional[str] = Field(
+ None, description="Stock ticker symbol."
+ )
+ quarter: Optional[str] = Field(
+ None, description="Reporting quarter (e.g., 'Q3 FY2024', 'Q4 2024')."
+ )
+ call_date: Optional[str] = Field(
+ None, description="Date of the earnings call."
+ )
+ reported_revenue: Optional[str] = Field(
+ None, description="Reported revenue for the quarter (e.g., '$94.8 billion')."
+ )
+ revenue_vs_consensus: Optional[str] = Field(
+ None,
+ description="Revenue vs. consensus (e.g., 'beat by $1.2B', 'in-line', 'missed by $500M').",
+ )
+ reported_eps: Optional[str] = Field(
+ None, description="Reported diluted EPS (e.g., '$1.46')."
+ )
+ eps_vs_consensus: Optional[str] = Field(
+ None, description="EPS vs. consensus (e.g., 'beat by $0.05')."
+ )
+ guidance_revenue: Optional[str] = Field(
+ None,
+ description="Forward revenue guidance (e.g., '$95-97B for Q4', 'FY2025 revenue $380-390B').",
+ )
+ guidance_eps: Optional[str] = Field(
+ None, description="Forward EPS guidance if provided."
+ )
+ overall_tone: Optional[str] = Field(
+ None,
+ description="Overall tone of the call: 'Positive', 'Cautiously Optimistic', 'Neutral', 'Cautious', 'Negative'.",
+ )
+ key_highlights: Optional[List[str]] = Field(
+ None,
+ description="Top 3-5 highlights from management's prepared remarks.",
+ )
+ key_concerns: Optional[List[str]] = Field(
+ None,
+ description="Top concerns raised by management or analysts during Q&A.",
+ )
+ strategic_priorities: Optional[List[str]] = Field(
+ None,
+ description="Strategic priorities emphasized by management.",
+ )
+ ceo_name: Optional[str] = Field(
+ None, description="CEO or primary presenter name."
+ )
+ cfo_name: Optional[str] = Field(
+ None, description="CFO name."
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a buy-side analyst reviewing an earnings call transcript. "
+ "Extract the key financial metrics, guidance, and overall tone.\n\n"
+ "Rules:\n"
+ "- Extract exact reported figures (Revenue, EPS) and compare to consensus.\n"
+ "- Capture forward guidance for revenue and earnings.\n"
+ "- Assess the overall tone of the call (management's language, analyst reactions).\n"
+ "- List key highlights from prepared remarks and concerns from Q&A.\n"
+ "- Identify strategic priorities management emphasized.\n\n"
+ "### Source Text:\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class EarningsCallSummary(AutoModel[EarningsCallSummarySchema]):
+ """
+ Applicable to: Quarterly Earnings Call Transcripts, Earnings Press Releases,
+ Investor Day Transcripts, Annual Meeting Transcripts.
+
+ Template for extracting a structured summary from earnings call transcripts.
+ Produces a single consolidated view of reported metrics, guidance, tone, and
+ key themes for quarterly review dashboards and consensus tracking.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> summary = EarningsCallSummary(llm_client=llm, embedder=embedder)
+ >>> transcript = "Good afternoon. Q3 revenue was $94.8 billion, beating consensus..."
+ >>> summary.feed_text(transcript)
+ >>> print(summary.data)
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Earnings Call Summary template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for transcript extraction.
+ embedder (Embeddings): Embedding model for indexing.
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoModel.
+ """
+ super().__init__(
+ data_schema=EarningsCallSummarySchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ strategy_or_merger=MergeStrategy.LLM.BALANCED,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
diff --git a/hyperextract/templates/en/finance/management_guidance_list.py b/hyperextract/templates/en/finance/management_guidance_list.py
new file mode 100644
index 0000000..c451b8b
--- /dev/null
+++ b/hyperextract/templates/en/finance/management_guidance_list.py
@@ -0,0 +1,153 @@
+"""Management Guidance List - Extracts forward-looking statements from earnings calls.
+
+Extracts projected figures, strategic priorities, and qualitative outlook from
+management's forward guidance for tracking and expectation management.
+"""
+
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoList
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class GuidanceItem(BaseModel):
+ """
+ A single forward-looking guidance statement from management.
+ """
+
+ guidance_topic: str = Field(
+ description="Topic of the guidance (e.g., 'Q4 Revenue', 'FY2025 CapEx', 'Gross Margin Outlook', 'Hiring Plans')."
+ )
+ guidance_type: str = Field(
+ description="Type: 'Quantitative', 'Qualitative', 'Strategic', 'Operational'."
+ )
+ guidance_value: str = Field(
+ description="The guidance statement or projected value (e.g., '$95-97B', 'expanding into 5 new markets', "
+ "'expect margin improvement in H2')."
+ )
+ prior_guidance: Optional[str] = Field(
+ None,
+ description="Previous guidance for the same metric if revised (e.g., '$90-93B').",
+ )
+ direction: Optional[str] = Field(
+ None,
+ description="Direction vs prior guidance or consensus: 'Raised', 'Lowered', 'Maintained', 'Initiated'.",
+ )
+ time_period: Optional[str] = Field(
+ None,
+ description="Period the guidance covers (e.g., 'Q4 2024', 'FY2025', 'Next 12 months').",
+ )
+ confidence_language: Optional[str] = Field(
+ None,
+ description="Management's conviction language (e.g., 'we expect', 'we are confident', 'we anticipate').",
+ )
+ speaker: Optional[str] = Field(
+ None,
+ description="Who provided the guidance (e.g., 'CEO', 'CFO', 'COO').",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an analyst tracking management guidance from earnings calls. "
+ "Extract all forward-looking statements and guidance from this transcript.\n\n"
+ "Rules:\n"
+ "- Extract every distinct guidance item (quantitative figures, strategic plans, outlook statements).\n"
+ "- Note if guidance was raised, lowered, or maintained vs. prior.\n"
+ "- Capture the time period each guidance covers.\n"
+ "- Preserve management's confidence language.\n"
+ "- Identify who provided each guidance item.\n"
+ "- Extract EVERY guidance statement independently.\n\n"
+ "### Source Text:\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class ManagementGuidanceList(AutoList[GuidanceItem]):
+ """
+ Applicable to: Earnings Call Transcripts, Investor Day Presentations,
+ Guidance Updates, Management Commentary sections.
+
+ Template for extracting forward-looking guidance from earnings calls and
+ management presentations. Each guidance item is captured independently
+ for tracking revisions and managing expectations.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> guidance = ManagementGuidanceList(llm_client=llm, embedder=embedder)
+ >>> transcript = "For Q4, we expect revenue in the range of $95-97 billion..."
+ >>> guidance.feed_text(transcript)
+ >>> guidance.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Management Guidance List template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for guidance extraction.
+ embedder (Embeddings): Embedding model for indexing.
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoList.
+ """
+ super().__init__(
+ item_schema=GuidanceItem,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """
+ Visualize the management guidance list.
+
+ Args:
+ top_k_for_search (int): Items for search. Default 3.
+ top_k_for_chat (int): Items for chat context. Default 3.
+ """
+
+ def label_extractor(item: GuidanceItem) -> str:
+ direction = f" [{item.direction}]" if item.direction else ""
+ return f"{item.guidance_topic}{direction}: {item.guidance_value[:50]}"
+
+ super().show(
+ item_label_extractor=label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/finance/analyst_qa_graph.py b/hyperextract/templates/zh/finance/analyst_qa_graph.py
new file mode 100644
index 0000000..9e657a5
--- /dev/null
+++ b/hyperextract/templates/zh/finance/analyst_qa_graph.py
@@ -0,0 +1,192 @@
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoGraph
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class QAParticipant(BaseModel):
+ """
+ 财报电话会议问答环节的参与者。
+ """
+
+ name: str = Field(
+ description="参与者姓名(例如分析师姓名、CEO、CFO)。"
+ )
+ role: str = Field(
+ description='角色:"分析师"、"CEO"、"CFO"、"COO"、"CTO"、"IR 负责人"、"其他管理层"。'
+ )
+ firm: Optional[str] = Field(
+ None,
+ description="所属机构(例如'摩根大通'、'高盛'),适用于分析师。",
+ )
+
+
+class QAInteraction(BaseModel):
+ """
+ 分析师与管理层之间的问答互动。
+ """
+
+ source: str = Field(description="提问者姓名(分析师)。")
+ target: str = Field(description="回答者姓名(管理层)。")
+ topic: str = Field(
+ description="问题主题(例如'利润率展望'、'AI 战略'、'资本配置')。"
+ )
+ question_summary: str = Field(
+ description="分析师问题的简要概述。"
+ )
+ answer_summary: str = Field(
+ description="管理层回答的简要概述。"
+ )
+ sentiment: Optional[str] = Field(
+ None,
+ description="互动基调:'建设性'、'追问式'、'安抚性'、'回避性'、'直接'。",
+ )
+ commitment_made: Optional[str] = Field(
+ None,
+ description="管理层作出的具体承诺(例如'将在下季度提供更新')。",
+ )
+ follow_up: Optional[bool] = Field(
+ None,
+ description="分析师是否就同一主题提出了追问。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是财报电话会议分析师。从本财报电话会议记录中提取分析师与管理层之间的问答互动。\n\n"
+ "规则:\n"
+ "- 识别每位分析师和管理层参与者。\n"
+ "- 概述每个问题及其对应的回答。\n"
+ "- 捕捉每次互动的主题和基调。\n"
+ "- 记录管理层作出的任何承诺。\n"
+ "- 跟踪针对同一主题的追问。"
+)
+
+_NODE_PROMPT = (
+ "你是财报电话会议分析师。提取所有问答参与者(节点)。\n\n"
+ "提取规则:\n"
+ "- 按姓名和所属机构识别分析师。\n"
+ "- 按姓名和职务识别管理层参与者。\n"
+ "- 此阶段不提取问答互动。"
+)
+
+_EDGE_PROMPT = (
+ "你是财报电话会议分析师。在获得参与者清单的基础上,提取问答互动(边)。\n\n"
+ "提取规则:\n"
+ "- 将每位分析师的问题连接到管理层的回答。\n"
+ "- 简要概述问题和回答。\n"
+ "- 捕捉主题、基调和任何承诺。\n"
+ "- 仅在提供的列表中存在的节点之间创建边。"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class AnalystQAGraph(AutoGraph[QAParticipant, QAInteraction]):
+ """
+ 适用文档: 财报电话会议记录(问答部分)、投资者日问答、
+ 年度股东大会问答、分析师日活动记录。
+
+ 模板用于将分析师问题映射到管理层回答。支持分析师关注点分析、
+ 承诺跟踪以及识别分析师群体中的核心关切。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> qa = AnalystQAGraph(llm_client=llm, embedder=embedder)
+ >>> transcript = "分析师:能否讨论一下利润率展望?CEO:我们预计利润率将..."
+ >>> qa.feed_text(transcript)
+ >>> qa.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化分析师问答图谱模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于问答提取的 LLM。
+ embedder (Embeddings): 用于去重的嵌入模型。
+ extraction_mode (str): "one_stage" 或 "two_stage"。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoGraph 的其他参数。
+ """
+ super().__init__(
+ node_schema=QAParticipant,
+ edge_schema=QAInteraction,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip().lower()}|{x.topic.lower()}|{x.target.strip().lower()}"
+ ),
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """
+ 使用 OntoSight 可视化分析师问答图。
+
+ Args:
+ top_k_nodes_for_search (int): 检索的参与者数。默认 3。
+ top_k_edges_for_search (int): 检索的问答互动数。默认 3。
+ top_k_nodes_for_chat (int): 对话上下文中的参与者数。默认 3。
+ top_k_edges_for_chat (int): 对话上下文中的互动数。默认 3。
+ """
+
+ def node_label_extractor(node: QAParticipant) -> str:
+ firm = f" @ {node.firm}" if node.firm else ""
+ return f"{node.name} ({node.role}{firm})"
+
+ def edge_label_extractor(edge: QAInteraction) -> str:
+ sentiment = f" [{edge.sentiment}]" if edge.sentiment else ""
+ return f"{edge.topic}{sentiment}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py b/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py
new file mode 100644
index 0000000..0e31e4a
--- /dev/null
+++ b/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py
@@ -0,0 +1,191 @@
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoHypergraph
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class CallTopic(BaseModel):
+ """
+ 财报电话会议中讨论的主题、发言人或情绪驱动因素。
+ """
+
+ name: str = Field(
+ description="主题元素名称(例如'收入增长'、'CEO 蒂姆·库克'、'AI 投资周期'、'谨慎')。"
+ )
+ element_type: str = Field(
+ description='类型:"主题"、"发言人"、"情绪"、"驱动因素"。'
+ )
+ description: Optional[str] = Field(
+ None, description="该元素的上下文或说明。"
+ )
+
+
+class SentimentCluster(BaseModel):
+ """
+ 连接主题、发言人、情绪和驱动因素的多维情绪聚类。
+ """
+
+ cluster_name: str = Field(
+ description="描述性名称(例如'CEO 看好 AI 收入'、'CFO 对利润率持谨慎态度')。"
+ )
+ participating_elements: List[str] = Field(
+ description="此情绪聚类中所有元素的名称(主题 + 发言人 + 情绪 + 驱动因素)。"
+ )
+ sentiment_polarity: str = Field(
+ description='整体情绪方向:"看多"、"看空"、"中性"、"混合"。'
+ )
+ intensity: str = Field(
+ description='情绪强度:"强"、"中等"、"轻微"。'
+ )
+ evidence: Optional[str] = Field(
+ None,
+ description="支持情绪判断的关键引述或意译。",
+ )
+ shift_from_prior: Optional[str] = Field(
+ None,
+ description="与前一季度基调的变化(如显著,例如'比第二季度更为谨慎'、'从中性上调')。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是财报电话会议情绪分析专家。提取主题、发言人、"
+ "情绪信号及其多维关系。\n\n"
+ "规则:\n"
+ "- 识别讨论的关键主题(收入、利润率、指引、战略)。\n"
+ "- 识别发言人及其角色。\n"
+ "- 评估每个主题-发言人组合的情绪方向和强度。\n"
+ "- 超边连接 主题 + 发言人 + 情绪 + 驱动因素。\n"
+ "- 记录与前一季度基调的变化。"
+)
+
+_NODE_PROMPT = (
+ "你是情绪分析专家。从财报电话会议中提取所有主题、发言人、情绪和"
+ "驱动因素(节点)。\n\n"
+ "提取规则:\n"
+ "- 识别讨论的财务主题。\n"
+ "- 识别发言人(分析师、管理层)。\n"
+ "- 识别情绪标签和驱动因素。\n"
+ "- 此阶段不创建情绪聚类。"
+)
+
+_EDGE_PROMPT = (
+ "你是情绪分析专家。在获得元素清单的基础上,创建多维"
+ "情绪聚类(超边)。\n\n"
+ "提取规则:\n"
+ "- 每个聚类连接 主题 + 发言人 + 情绪 + 驱动因素。\n"
+ "- 评估整体情绪方向和强度。\n"
+ "- 捕捉支撑证据。\n"
+ "- 记录与前几个季度的基调变化。\n"
+ "- 仅引用提供列表中存在的元素。"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class CallSentimentHypergraph(AutoHypergraph[CallTopic, SentimentCluster]):
+ """
+ 适用文档: 财报电话会议记录、投资者日活动记录、
+ 管理层报告、行业会议记录。
+
+ 模板用于财报电话会议的多维情绪分析。使用超边建模
+ {主题, 发言人, 情绪, 驱动因素} 聚类,支持情绪驱动的交易信号和基调变化检测。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> sentiment = CallSentimentHypergraph(llm_client=llm, embedder=embedder)
+ >>> transcript = "CEO:我们对 AI 收入增长感到非常兴奋..."
+ >>> sentiment.feed_text(transcript)
+ >>> sentiment.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化电话会议情绪超图模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于情绪提取的 LLM。
+ embedder (Embeddings): 用于去重的嵌入模型。
+ extraction_mode (str): "one_stage" 或 "two_stage"。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoHypergraph 的其他参数。
+ """
+ super().__init__(
+ node_schema=CallTopic,
+ edge_schema=SentimentCluster,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: x.cluster_name.strip().lower(),
+ nodes_in_edge_extractor=lambda x: tuple(
+ e.strip().lower() for e in x.participating_elements
+ ),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """
+ 使用 OntoSight 可视化电话会议情绪超图。
+
+ Args:
+ top_k_nodes_for_search (int): 检索的元素数。默认 3。
+ top_k_edges_for_search (int): 检索的情绪聚类数。默认 3。
+ top_k_nodes_for_chat (int): 对话上下文中的元素数。默认 3。
+ top_k_edges_for_chat (int): 对话上下文中的聚类数。默认 3。
+ """
+
+ def node_label_extractor(node: CallTopic) -> str:
+ return f"{node.name} [{node.element_type}]"
+
+ def edge_label_extractor(edge: SentimentCluster) -> str:
+ return f"[{edge.sentiment_polarity}/{edge.intensity}] {edge.cluster_name}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/zh/finance/earnings_call_summary.py b/hyperextract/templates/zh/finance/earnings_call_summary.py
new file mode 100644
index 0000000..f3a5fd9
--- /dev/null
+++ b/hyperextract/templates/zh/finance/earnings_call_summary.py
@@ -0,0 +1,147 @@
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from ontomem.merger import MergeStrategy
+from hyperextract.types import AutoModel
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class EarningsCallSummarySchema(BaseModel):
+ """
+ 财报电话会议的结构化摘要。
+ """
+
+ company_name: Optional[str] = Field(
+ None, description="公司名称。"
+ )
+ ticker: Optional[str] = Field(
+ None, description="股票代码。"
+ )
+ quarter: Optional[str] = Field(
+ None, description="报告季度(例如'Q3 FY2024'、'2024 年第四季度')。"
+ )
+ call_date: Optional[str] = Field(
+ None, description="财报电话会议日期。"
+ )
+ reported_revenue: Optional[str] = Field(
+ None, description="本季度报告收入(例如'948 亿美元')。"
+ )
+ revenue_vs_consensus: Optional[str] = Field(
+ None,
+ description="收入与市场一致预期对比(例如'超出 12 亿美元'、'符合预期'、'低于预期 5 亿美元')。",
+ )
+ reported_eps: Optional[str] = Field(
+ None, description="报告的稀释每股收益(例如'1.46 美元')。"
+ )
+ eps_vs_consensus: Optional[str] = Field(
+ None, description="每股收益与一致预期对比(例如'超出 0.05 美元')。"
+ )
+ guidance_revenue: Optional[str] = Field(
+ None,
+ description="前瞻性收入指引(例如'第四季度 950-970 亿美元'、'2025 财年收入 3800-3900 亿美元')。",
+ )
+ guidance_eps: Optional[str] = Field(
+ None, description="前瞻性每股收益指引(如有提供)。"
+ )
+ overall_tone: Optional[str] = Field(
+ None,
+ description="电话会议整体基调:'积极'、'审慎乐观'、'中性'、'谨慎'、'消极'。",
+ )
+ key_highlights: Optional[List[str]] = Field(
+ None,
+ description="管理层准备发言中的 3-5 项核心亮点。",
+ )
+ key_concerns: Optional[List[str]] = Field(
+ None,
+ description="管理层或分析师在问答环节提出的主要关切。",
+ )
+ strategic_priorities: Optional[List[str]] = Field(
+ None,
+ description="管理层强调的战略重点。",
+ )
+ ceo_name: Optional[str] = Field(
+ None, description="CEO 或主要发言人姓名。"
+ )
+ cfo_name: Optional[str] = Field(
+ None, description="CFO 姓名。"
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是买方分析师,正在审阅财报电话会议记录。"
+ "提取关键财务指标、业绩指引和整体基调。\n\n"
+ "规则:\n"
+ "- 提取确切的报告数据(收入、每股收益)并与一致预期进行对比。\n"
+ "- 捕捉收入和盈利的前瞻性指引。\n"
+ "- 评估电话会议的整体基调(管理层措辞、分析师反应)。\n"
+ "- 列出准备发言中的核心亮点和问答环节中的主要关切。\n"
+ "- 识别管理层强调的战略重点。\n\n"
+ "### 原文:\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class EarningsCallSummary(AutoModel[EarningsCallSummarySchema]):
+ """
+ 适用文档: 季度财报电话会议记录、业绩新闻稿、
+ 投资者日活动记录、年度股东大会记录。
+
+ 模板用于从财报电话会议记录中提取结构化摘要。生成已报告指标、业绩指引、
+ 基调和核心主题的统一视图,便于季度复盘仪表板和一致预期跟踪。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> summary = EarningsCallSummary(llm_client=llm, embedder=embedder)
+ >>> transcript = "下午好。第三季度收入为 948 亿美元,超出一致预期..."
+ >>> summary.feed_text(transcript)
+ >>> print(summary.data)
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化财报电话会议摘要模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于会议记录提取的 LLM。
+ embedder (Embeddings): 用于索引的嵌入模型。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoModel 的其他参数。
+ """
+ super().__init__(
+ data_schema=EarningsCallSummarySchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ strategy_or_merger=MergeStrategy.LLM.BALANCED,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
diff --git a/hyperextract/templates/zh/finance/management_guidance_list.py b/hyperextract/templates/zh/finance/management_guidance_list.py
new file mode 100644
index 0000000..b8515f7
--- /dev/null
+++ b/hyperextract/templates/zh/finance/management_guidance_list.py
@@ -0,0 +1,146 @@
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoList
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class GuidanceItem(BaseModel):
+ """
+ 管理层的单项前瞻性指引声明。
+ """
+
+ guidance_topic: str = Field(
+ description="指引主题(例如'第四季度收入'、'2025 财年资本支出'、'毛利率展望'、'招聘计划')。"
+ )
+ guidance_type: str = Field(
+ description='类型:"定量"、"定性"、"战略"、"运营"。'
+ )
+ guidance_value: str = Field(
+ description="指引内容或预测值(例如'950-970 亿美元'、'将拓展 5 个新市场'、"
+ "'预计下半年利润率改善')。"
+ )
+ prior_guidance: Optional[str] = Field(
+ None,
+ description="同一指标的前次指引(如有修订,例如'900-930 亿美元')。",
+ )
+ direction: Optional[str] = Field(
+ None,
+ description="相对前次指引或一致预期的方向:'上调'、'下调'、'维持'、'首次发布'。",
+ )
+ time_period: Optional[str] = Field(
+ None,
+ description="指引覆盖的时间段(例如'2024 年第四季度'、'2025 财年'、'未来 12 个月')。",
+ )
+ confidence_language: Optional[str] = Field(
+ None,
+ description="管理层的确信程度措辞(例如'我们预计'、'我们有信心'、'我们预期')。",
+ )
+ speaker: Optional[str] = Field(
+ None,
+ description="指引发布者(例如'CEO'、'CFO'、'COO')。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是跟踪财报电话会议管理层指引的分析师。"
+ "从本会议记录中提取所有前瞻性声明和业绩指引。\n\n"
+ "规则:\n"
+ "- 提取每一项指引条目(定量数据、战略规划、展望声明)。\n"
+ "- 注明指引相较前次是上调、下调还是维持不变。\n"
+ "- 捕捉每项指引覆盖的时间段。\n"
+ "- 保留管理层的确信程度措辞。\n"
+ "- 识别每项指引的发布者。\n"
+ "- 将每项指引声明作为独立条目提取。\n\n"
+ "### 原文:\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class ManagementGuidanceList(AutoList[GuidanceItem]):
+ """
+ 适用文档: 财报电话会议记录、投资者日演示材料、
+ 业绩指引更新、管理层评论部分。
+
+ 模板用于从财报电话会议和管理层报告中提取前瞻性指引。每项指引条目
+ 独立捕捉,便于跟踪修订和管理预期。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> guidance = ManagementGuidanceList(llm_client=llm, embedder=embedder)
+ >>> transcript = "对于第四季度,我们预计收入在 950 至 970 亿美元之间..."
+ >>> guidance.feed_text(transcript)
+ >>> guidance.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化管理层指引列表模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于指引提取的 LLM。
+ embedder (Embeddings): 用于索引的嵌入模型。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoList 的其他参数。
+ """
+ super().__init__(
+ item_schema=GuidanceItem,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """
+ 可视化管理层指引列表。
+
+ Args:
+ top_k_for_search (int): 检索的条目数。默认 3。
+ top_k_for_chat (int): 对话上下文中的条目数。默认 3。
+ """
+
+ def label_extractor(item: GuidanceItem) -> str:
+ direction = f" [{item.direction}]" if item.direction else ""
+ return f"{item.guidance_topic}{direction}: {item.guidance_value[:50]}"
+
+ super().show(
+ item_label_extractor=label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )