From 7c27546951a4303e851f8e925e21e8af41da2fab Mon Sep 17 00:00:00 2001 From: Igor Ilic Date: Mon, 8 Sep 2025 11:33:15 +0200 Subject: [PATCH] refactor: Initial baml refactor commit --- cognee/infrastructure/llm/LLMGateway.py | 11 +++ .../baml/baml_client/__init__.py | 2 +- .../baml/baml_client/async_client.py | 81 +++++++++++++++++++ .../baml/baml_client/inlinedbaml.py | 5 +- .../baml/baml_client/parser.py | 20 +++++ .../baml/baml_client/stream_types.py | 7 +- .../baml/baml_client/sync_client.py | 81 +++++++++++++++++++ .../baml/baml_client/type_builder.py | 56 ++++++++++++- .../baml/baml_client/type_map.py | 2 + .../baml/baml_client/types.py | 7 +- .../baml_src/acreate_structured_output.baml | 20 +++++ .../baml/baml_src/extraction/__init__.py | 1 + .../extraction/acreate_structured_output.py | 46 +++++++++++ .../baml/baml_src/generators.baml | 6 +- 14 files changed, 335 insertions(+), 10 deletions(-) create mode 100644 cognee/infrastructure/llm/structured_output_framework/baml/baml_src/acreate_structured_output.baml create mode 100644 cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/acreate_structured_output.py diff --git a/cognee/infrastructure/llm/LLMGateway.py b/cognee/infrastructure/llm/LLMGateway.py index 863bfade2..02cc25c48 100644 --- a/cognee/infrastructure/llm/LLMGateway.py +++ b/cognee/infrastructure/llm/LLMGateway.py @@ -19,6 +19,17 @@ class LLMGateway: def acreate_structured_output( text_input: str, system_prompt: str, response_model: Type[BaseModel] ) -> Coroutine: + llm_config = get_llm_config() + if llm_config.structured_output_framework.upper() == "BAML": + from cognee.infrastructure.llm.structured_output_framework.baml.baml_src.extraction import ( + acreate_structured_output, + ) + + return acreate_structured_output( + content=text_input, + system_prompt=system_prompt, + response_model=response_model, + ) from cognee.infrastructure.llm.structured_output_framework.litellm_instructor.llm.get_llm_client import ( get_llm_client, ) diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/__init__.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/__init__.py index 85dfab90c..e25104d0b 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/__init__.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/__init__.py @@ -39,7 +39,7 @@ with EnsureBamlPyImport(__version__) as e: from . import config from .config import reset_baml_env_vars - from .sync_client import b + from .async_client import b # FOR LEGACY COMPATIBILITY, expose "partial_types" as an alias for "stream_types" diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/async_client.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/async_client.py index faf00c836..35f810729 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/async_client.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/async_client.py @@ -76,6 +76,25 @@ class BamlAsyncClient: def parse_stream(self): return self.__llm_stream_parser + async def AcreateStructuredOutput( + self, + content: str, + system_prompt: str, + user_prompt: str, + baml_options: BamlCallOptions = {}, + ) -> types.DynamicModel: + result = await self.__options.merge_options(baml_options).call_function_async( + function_name="AcreateStructuredOutput", + args={ + "content": content, + "system_prompt": system_prompt, + "user_prompt": user_prompt, + }, + ) + return typing.cast( + types.DynamicModel, result.cast_to(types, types, stream_types, False, __runtime__) + ) + async def ExtractCategories( self, content: str, @@ -184,6 +203,32 @@ class BamlStreamClient: def __init__(self, options: DoNotUseDirectlyCallManager): self.__options = options + def AcreateStructuredOutput( + self, + content: str, + system_prompt: str, + user_prompt: str, + baml_options: BamlCallOptions = {}, + ) -> baml_py.BamlStream[stream_types.DynamicModel, types.DynamicModel]: + ctx, result = self.__options.merge_options(baml_options).create_async_stream( + function_name="AcreateStructuredOutput", + args={ + "content": content, + "system_prompt": system_prompt, + "user_prompt": user_prompt, + }, + ) + return baml_py.BamlStream[stream_types.DynamicModel, types.DynamicModel]( + result, + lambda x: typing.cast( + stream_types.DynamicModel, x.cast_to(types, types, stream_types, True, __runtime__) + ), + lambda x: typing.cast( + types.DynamicModel, x.cast_to(types, types, stream_types, False, __runtime__) + ), + ctx, + ) + def ExtractCategories( self, content: str, @@ -334,6 +379,24 @@ class BamlHttpRequestClient: def __init__(self, options: DoNotUseDirectlyCallManager): self.__options = options + async def AcreateStructuredOutput( + self, + content: str, + system_prompt: str, + user_prompt: str, + baml_options: BamlCallOptions = {}, + ) -> baml_py.baml_py.HTTPRequest: + result = await self.__options.merge_options(baml_options).create_http_request_async( + function_name="AcreateStructuredOutput", + args={ + "content": content, + "system_prompt": system_prompt, + "user_prompt": user_prompt, + }, + mode="request", + ) + return result + async def ExtractCategories( self, content: str, @@ -435,6 +498,24 @@ class BamlHttpStreamRequestClient: def __init__(self, options: DoNotUseDirectlyCallManager): self.__options = options + async def AcreateStructuredOutput( + self, + content: str, + system_prompt: str, + user_prompt: str, + baml_options: BamlCallOptions = {}, + ) -> baml_py.baml_py.HTTPRequest: + result = await self.__options.merge_options(baml_options).create_http_request_async( + function_name="AcreateStructuredOutput", + args={ + "content": content, + "system_prompt": system_prompt, + "user_prompt": user_prompt, + }, + mode="stream", + ) + return result + async def ExtractCategories( self, content: str, diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/inlinedbaml.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/inlinedbaml.py index a03afa95d..17745b6d8 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/inlinedbaml.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/inlinedbaml.py @@ -11,9 +11,10 @@ # baml-cli is available with the baml package. _file_map = { + "acreate_structured_output.baml": "class DynamicModel {\n test string\n @@dynamic\n}\n\nfunction AcreateStructuredOutput(\n content: string,\n system_prompt: string,\n user_prompt: string,\n) -> DynamicModel {\n client OpenAI\n\n prompt #\"\n {{ system_prompt }}\n {{ ctx.output_format }}\n {{ _.role('user') }}\n {{ user_prompt }}\n {{ content }}\n \"#\n}", "extract_categories.baml": '// Content classification data models - matching shared/data_models.py\nclass TextContent {\n type string\n subclass string[]\n}\n\nclass AudioContent {\n type string\n subclass string[]\n}\n\nclass ImageContent {\n type string\n subclass string[]\n}\n\nclass VideoContent {\n type string\n subclass string[]\n}\n\nclass MultimediaContent {\n type string\n subclass string[]\n}\n\nclass Model3DContent {\n type string\n subclass string[]\n}\n\nclass ProceduralContent {\n type string\n subclass string[]\n}\n\nclass ContentLabel {\n content_type "text" | "audio" | "image" | "video" | "multimedia" | "3d_model" | "procedural"\n type string\n subclass string[]\n}\n\nclass DefaultContentPrediction {\n label ContentLabel\n}\n\n// Content classification prompt template\ntemplate_string ClassifyContentPrompt() #"\n You are a classification engine and should classify content. Make sure to use one of the existing classification options and not invent your own.\n\n Classify the content into one of these main categories and their relevant subclasses:\n\n **TEXT CONTENT** (content_type: "text"):\n - type: "TEXTUAL_DOCUMENTS_USED_FOR_GENERAL_PURPOSES"\n - subclass options: ["Articles, essays, and reports", "Books and manuscripts", "News stories and blog posts", "Research papers and academic publications", "Social media posts and comments", "Website content and product descriptions", "Personal narratives and stories", "Spreadsheets and tables", "Forms and surveys", "Databases and CSV files", "Source code in various programming languages", "Shell commands and scripts", "Markup languages (HTML, XML)", "Stylesheets (CSS) and configuration files (YAML, JSON, INI)", "Chat transcripts and messaging history", "Customer service logs and interactions", "Conversational AI training data", "Textbook content and lecture notes", "Exam questions and academic exercises", "E-learning course materials", "Poetry and prose", "Scripts for plays, movies, and television", "Song lyrics", "Manuals and user guides", "Technical specifications and API documentation", "Helpdesk articles and FAQs", "Contracts and agreements", "Laws, regulations, and legal case documents", "Policy documents and compliance materials", "Clinical trial reports", "Patient records and case notes", "Scientific journal articles", "Financial reports and statements", "Business plans and proposals", "Market research and analysis reports", "Ad copies and marketing slogans", "Product catalogs and brochures", "Press releases and promotional content", "Professional and formal correspondence", "Personal emails and letters", "Image and video captions", "Annotations and metadata for various media", "Vocabulary lists and grammar rules", "Language exercises and quizzes", "Other types of text data"]\n\n **AUDIO CONTENT** (content_type: "audio"):\n - type: "AUDIO_DOCUMENTS_USED_FOR_GENERAL_PURPOSES"\n - subclass options: ["Music tracks and albums", "Podcasts and radio broadcasts", "Audiobooks and audio guides", "Recorded interviews and speeches", "Sound effects and ambient sounds", "Other types of audio recordings"]\n\n **IMAGE CONTENT** (content_type: "image"):\n - type: "IMAGE_DOCUMENTS_USED_FOR_GENERAL_PURPOSES"\n - subclass options: ["Photographs and digital images", "Illustrations, diagrams, and charts", "Infographics and visual data representations", "Artwork and paintings", "Screenshots and graphical user interfaces", "Other types of images"]\n\n **VIDEO CONTENT** (content_type: "video"):\n - type: "VIDEO_DOCUMENTS_USED_FOR_GENERAL_PURPOSES"\n - subclass options: ["Movies and short films", "Documentaries and educational videos", "Video tutorials and how-to guides", "Animated features and cartoons", "Live event recordings and sports broadcasts", "Other types of video content"]\n\n **MULTIMEDIA CONTENT** (content_type: "multimedia"):\n - type: "MULTIMEDIA_DOCUMENTS_USED_FOR_GENERAL_PURPOSES"\n - subclass options: ["Interactive web content and games", "Virtual reality (VR) and augmented reality (AR) experiences", "Mixed media presentations and slide decks", "E-learning modules with integrated multimedia", "Digital exhibitions and virtual tours", "Other types of multimedia content"]\n\n **3D MODEL CONTENT** (content_type: "3d_model"):\n - type: "3D_MODEL_DOCUMENTS_USED_FOR_GENERAL_PURPOSES"\n - subclass options: ["Architectural renderings and building plans", "Product design models and prototypes", "3D animations and character models", "Scientific simulations and visualizations", "Virtual objects for AR/VR applications", "Other types of 3D models"]\n\n **PROCEDURAL CONTENT** (content_type: "procedural"):\n - type: "PROCEDURAL_DOCUMENTS_USED_FOR_GENERAL_PURPOSES"\n - subclass options: ["Tutorials and step-by-step guides", "Workflow and process descriptions", "Simulation and training exercises", "Recipes and crafting instructions", "Other types of procedural content"]\n\n Select the most appropriate content_type, type, and relevant subclasses.\n"#\n\n// OpenAI client defined once for all BAML files\n\n// Classification function\nfunction ExtractCategories(content: string) -> DefaultContentPrediction {\n client OpenAI\n\n prompt #"\n {{ ClassifyContentPrompt() }}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\n// Test case for classification\ntest ExtractCategoriesExample {\n functions [ExtractCategories]\n args {\n content #"\n Natural language processing (NLP) is an interdisciplinary subfield of computer science and information retrieval.\n It deals with the interaction between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data.\n "#\n }\n}\n', - "extract_content_graph.baml": 'class Node {\n id string\n name string\n type string\n description string\n @@dynamic\n}\n\n/// doc string for edge\nclass Edge {\n /// doc string for source_node_id\n source_node_id string\n target_node_id string\n relationship_name string\n}\n\nclass KnowledgeGraph {\n nodes (Node @stream.done)[]\n edges Edge[]\n}\n\n// Summarization classes\nclass SummarizedContent {\n summary string\n description string\n}\n\nclass SummarizedFunction {\n name string\n description string\n inputs string[]?\n outputs string[]?\n decorators string[]?\n}\n\nclass SummarizedClass {\n name string\n description string\n methods SummarizedFunction[]?\n decorators string[]?\n}\n\nclass SummarizedCode {\n high_level_summary string\n key_features string[]\n imports string[]\n constants string[]\n classes SummarizedClass[]\n functions SummarizedFunction[]\n workflow_description string?\n}\n\nclass DynamicKnowledgeGraph {\n @@dynamic\n}\n\n\n// Simple template for basic extraction (fast, good quality)\ntemplate_string ExtractContentGraphPrompt() #"\n You are an advanced algorithm that extracts structured data into a knowledge graph.\n\n - **Nodes**: Entities/concepts (like Wikipedia articles).\n - **Edges**: Relationships (like Wikipedia links). Use snake_case (e.g., `acted_in`).\n\n **Rules:**\n\n 1. **Node Labeling & IDs**\n - Use basic types only (e.g., "Person", "Date", "Organization").\n - Avoid overly specific or generic terms (e.g., no "Mathematician" or "Entity").\n - Node IDs must be human-readable names from the text (no numbers).\n\n 2. **Dates & Numbers**\n - Label dates as **"Date"** in "YYYY-MM-DD" format (use available parts if incomplete).\n - Properties are key-value pairs; do not use escaped quotes.\n\n 3. **Coreference Resolution**\n - Use a single, complete identifier for each entity (e.g., always "John Doe" not "Joe" or "he").\n\n 4. **Relationship Labels**:\n - Use descriptive, lowercase, snake_case names for edges.\n - *Example*: born_in, married_to, invented_by.\n - Avoid vague or generic labels like isA, relatesTo, has.\n - Avoid duplicated relationships like produces, produced by.\n\n 5. **Strict Compliance**\n - Follow these rules exactly. Non-compliance results in termination.\n"#\n\n// Summarization prompt template\ntemplate_string SummarizeContentPrompt() #"\n You are a top-tier summarization engine. Your task is to summarize text and make it versatile.\n Be brief and concise, but keep the important information and the subject.\n Use synonym words where possible in order to change the wording but keep the meaning.\n"#\n\n// Code summarization prompt template\ntemplate_string SummarizeCodePrompt() #"\n You are an expert code analyst. Analyze the provided source code and extract key information:\n\n 1. Provide a high-level summary of what the code does\n 2. List key features and functionality\n 3. Identify imports and dependencies\n 4. List constants and global variables\n 5. Summarize classes with their methods\n 6. Summarize standalone functions\n 7. Describe the overall workflow if applicable\n\n Be precise and technical while remaining clear and concise.\n"#\n\n// Detailed template for complex extraction (slower, higher quality)\ntemplate_string DetailedExtractContentGraphPrompt() #"\n You are a top-tier algorithm designed for extracting information in structured formats to build a knowledge graph.\n **Nodes** represent entities and concepts. They\'re akin to Wikipedia nodes.\n **Edges** represent relationships between concepts. They\'re akin to Wikipedia links.\n\n The aim is to achieve simplicity and clarity in the knowledge graph.\n\n # 1. Labeling Nodes\n **Consistency**: Ensure you use basic or elementary types for node labels.\n - For example, when you identify an entity representing a person, always label it as **"Person"**.\n - Avoid using more specific terms like "Mathematician" or "Scientist", keep those as "profession" property.\n - Don\'t use too generic terms like "Entity".\n **Node IDs**: Never utilize integers as node IDs.\n - Node IDs should be names or human-readable identifiers found in the text.\n\n # 2. Handling Numerical Data and Dates\n - For example, when you identify an entity representing a date, make sure it has type **"Date"**.\n - Extract the date in the format "YYYY-MM-DD"\n - If not possible to extract the whole date, extract month or year, or both if available.\n - **Property Format**: Properties must be in a key-value format.\n - **Quotation Marks**: Never use escaped single or double quotes within property values.\n - **Naming Convention**: Use snake_case for relationship names, e.g., `acted_in`.\n\n # 3. Coreference Resolution\n - **Maintain Entity Consistency**: When extracting entities, it\'s vital to ensure consistency.\n If an entity, such as "John Doe", is mentioned multiple times in the text but is referred to by different names or pronouns (e.g., "Joe", "he"),\n always use the most complete identifier for that entity throughout the knowledge graph. In this example, use "John Doe" as the Person\'s ID.\n Remember, the knowledge graph should be coherent and easily understandable, so maintaining consistency in entity references is crucial.\n\n # 4. Strict Compliance\n Adhere to the rules strictly. Non-compliance will result in termination.\n"#\n\n// Guided template with step-by-step instructions\ntemplate_string GuidedExtractContentGraphPrompt() #"\n You are an advanced algorithm designed to extract structured information to build a clean, consistent, and human-readable knowledge graph.\n\n **Objective**:\n - Nodes represent entities and concepts, similar to Wikipedia articles.\n - Edges represent typed relationships between nodes, similar to Wikipedia hyperlinks.\n - The graph must be clear, minimal, consistent, and semantically precise.\n\n **Node Guidelines**:\n\n 1. **Label Consistency**:\n - Use consistent, basic types for all node labels.\n - Do not switch between granular or vague labels for the same kind of entity.\n - Pick one label for each category and apply it uniformly.\n - Each entity type should be in a singular form and in a case of multiple words separated by whitespaces\n\n 2. **Node Identifiers**:\n - Node IDs must be human-readable and derived directly from the text.\n - Prefer full names and canonical terms.\n - Never use integers or autogenerated IDs.\n - *Example*: Use "Marie Curie", "Theory of Evolution", "Google".\n\n 3. **Coreference Resolution**:\n - Maintain one consistent node ID for each real-world entity.\n - Resolve aliases, acronyms, and pronouns to the most complete form.\n - *Example*: Always use "John Doe" even if later referred to as "Doe" or "he".\n\n **Edge Guidelines**:\n\n 4. **Relationship Labels**:\n - Use descriptive, lowercase, snake_case names for edges.\n - *Example*: born_in, married_to, invented_by.\n - Avoid vague or generic labels like isA, relatesTo, has.\n\n 5. **Relationship Direction**:\n - Edges must be directional and logically consistent.\n - *Example*:\n - "Marie Curie" —[born_in]→ "Warsaw"\n - "Radioactivity" —[discovered_by]→ "Marie Curie"\n\n **Compliance**:\n Strict adherence to these guidelines is required. Any deviation will result in immediate termination of the task.\n"#\n\n// Strict template with zero-tolerance rules\ntemplate_string StrictExtractContentGraphPrompt() #"\n You are a top-tier algorithm for **extracting structured information** from unstructured text to build a **knowledge graph**.\n\n Your primary goal is to extract:\n - **Nodes**: Representing **entities** and **concepts** (like Wikipedia nodes).\n - **Edges**: Representing **relationships** between those concepts (like Wikipedia links).\n\n The resulting knowledge graph must be **simple, consistent, and human-readable**.\n\n ## 1. Node Labeling and Identification\n\n ### Node Types\n Use **basic atomic types** for node labels. Always prefer general types over specific roles or professions:\n - "Person" for any human.\n - "Organization" for companies, institutions, etc.\n - "Location" for geographic or place entities.\n - "Date" for any temporal expression.\n - "Event" for historical or scheduled occurrences.\n - "Work" for books, films, artworks, or research papers.\n - "Concept" for abstract notions or ideas.\n\n ### Node IDs\n - Always assign **human-readable and unambiguous identifiers**.\n - Never use numeric or autogenerated IDs.\n - Prioritize **most complete form** of entity names for consistency.\n\n ## 2. Relationship Handling\n - Use **snake_case** for all relationship (edge) types.\n - Keep relationship types semantically clear and consistent.\n - Avoid vague relation names like "related_to" unless no better alternative exists.\n\n ## 3. Strict Compliance\n Follow all rules exactly. Any deviation may lead to rejection or incorrect graph construction.\n"#\n\n// OpenAI client with environment model selection\nclient OpenAI {\n provider openai\n options {\n model client_registry.model\n api_key client_registry.api_key\n }\n}\n\n\n\n// Function that returns raw structured output (for custom objects - to be handled in Python)\nfunction ExtractContentGraphGeneric(\n content: string,\n mode: "simple" | "base" | "guided" | "strict" | "custom"?,\n custom_prompt_content: string?\n) -> KnowledgeGraph {\n client OpenAI\n\n prompt #"\n {% if mode == "base" %}\n {{ DetailedExtractContentGraphPrompt() }}\n {% elif mode == "guided" %}\n {{ GuidedExtractContentGraphPrompt() }}\n {% elif mode == "strict" %}\n {{ StrictExtractContentGraphPrompt() }}\n {% elif mode == "custom" and custom_prompt_content %}\n {{ custom_prompt_content }}\n {% else %}\n {{ ExtractContentGraphPrompt() }}\n {% endif %}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n Before answering, briefly describe what you\'ll extract from the text, then provide the structured output.\n\n Example format:\n I\'ll extract the main entities and their relationships from this text...\n\n { ... }\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\n// Backward-compatible function specifically for KnowledgeGraph\nfunction ExtractDynamicContentGraph(\n content: string,\n mode: "simple" | "base" | "guided" | "strict" | "custom"?,\n custom_prompt_content: string?\n) -> DynamicKnowledgeGraph {\n client OpenAI\n\n prompt #"\n {% if mode == "base" %}\n {{ DetailedExtractContentGraphPrompt() }}\n {% elif mode == "guided" %}\n {{ GuidedExtractContentGraphPrompt() }}\n {% elif mode == "strict" %}\n {{ StrictExtractContentGraphPrompt() }}\n {% elif mode == "custom" and custom_prompt_content %}\n {{ custom_prompt_content }}\n {% else %}\n {{ ExtractContentGraphPrompt() }}\n {% endif %}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n Before answering, briefly describe what you\'ll extract from the text, then provide the structured output.\n\n Example format:\n I\'ll extract the main entities and their relationships from this text...\n\n { ... }\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\n\n// Summarization functions\nfunction SummarizeContent(content: string) -> SummarizedContent {\n client OpenAI\n\n prompt #"\n {{ SummarizeContentPrompt() }}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\nfunction SummarizeCode(content: string) -> SummarizedCode {\n client OpenAI\n\n prompt #"\n {{ SummarizeCodePrompt() }}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\ntest ExtractStrictExample {\n functions [ExtractContentGraphGeneric]\n args {\n content #"\n The Python programming language was created by Guido van Rossum in 1991.\n "#\n mode "strict"\n }\n}', - "generators.baml": '// This helps use auto generate libraries you can use in the language of\n// your choice. You can have multiple generators if you use multiple languages.\n// Just ensure that the output_dir is different for each generator.\ngenerator target {\n // Valid values: "python/pydantic", "typescript", "ruby/sorbet", "rest/openapi"\n output_type "python/pydantic"\n\n // Where the generated code will be saved (relative to baml_src/)\n output_dir "../baml/"\n\n // The version of the BAML package you have installed (e.g. same version as your baml-py or @boundaryml/baml).\n // The BAML VSCode extension version should also match this version.\n version "0.201.0"\n\n // Valid values: "sync", "async"\n // This controls what `b.FunctionName()` will be (sync or async).\n default_client_mode sync\n}\n', + "extract_content_graph.baml": 'class Node {\n id string\n name string\n type string\n description string\n @@dynamic\n}\n\n/// doc string for edge\nclass Edge {\n /// doc string for source_node_id\n source_node_id string\n target_node_id string\n relationship_name string\n}\n\nclass KnowledgeGraph {\n nodes (Node @stream.done)[]\n edges Edge[]\n}\n\n// Summarization classes\nclass SummarizedContent {\n summary string\n description string\n}\n\nclass SummarizedFunction {\n name string\n description string\n inputs string[]?\n outputs string[]?\n decorators string[]?\n}\n\nclass SummarizedClass {\n name string\n description string\n methods SummarizedFunction[]?\n decorators string[]?\n}\n\nclass SummarizedCode {\n high_level_summary string\n key_features string[]\n imports string[]\n constants string[]\n classes SummarizedClass[]\n functions SummarizedFunction[]\n workflow_description string?\n}\n\nclass DynamicKnowledgeGraph {\n @@dynamic\n}\n\n\n// Simple template for basic extraction (fast, good quality)\ntemplate_string ExtractContentGraphPrompt() #"\n You are an advanced algorithm that extracts structured data into a knowledge graph.\n\n - **Nodes**: Entities/concepts (like Wikipedia articles).\n - **Edges**: Relationships (like Wikipedia links). Use snake_case (e.g., `acted_in`).\n\n **Rules:**\n\n 1. **Node Labeling & IDs**\n - Use basic types only (e.g., "Person", "Date", "Organization").\n - Avoid overly specific or generic terms (e.g., no "Mathematician" or "Entity").\n - Node IDs must be human-readable names from the text (no numbers).\n\n 2. **Dates & Numbers**\n - Label dates as **"Date"** in "YYYY-MM-DD" format (use available parts if incomplete).\n - Properties are key-value pairs; do not use escaped quotes.\n\n 3. **Coreference Resolution**\n - Use a single, complete identifier for each entity (e.g., always "John Doe" not "Joe" or "he").\n\n 4. **Relationship Labels**:\n - Use descriptive, lowercase, snake_case names for edges.\n - *Example*: born_in, married_to, invented_by.\n - Avoid vague or generic labels like isA, relatesTo, has.\n - Avoid duplicated relationships like produces, produced by.\n\n 5. **Strict Compliance**\n - Follow these rules exactly. Non-compliance results in termination.\n"#\n\n// Summarization prompt template\ntemplate_string SummarizeContentPrompt() #"\n You are a top-tier summarization engine. Your task is to summarize text and make it versatile.\n Be brief and concise, but keep the important information and the subject.\n Use synonym words where possible in order to change the wording but keep the meaning.\n"#\n\n// Code summarization prompt template\ntemplate_string SummarizeCodePrompt() #"\n You are an expert code analyst. Analyze the provided source code and extract key information:\n\n 1. Provide a high-level summary of what the code does\n 2. List key features and functionality\n 3. Identify imports and dependencies\n 4. List constants and global variables\n 5. Summarize classes with their methods\n 6. Summarize standalone functions\n 7. Describe the overall workflow if applicable\n\n Be precise and technical while remaining clear and concise.\n"#\n\n// Detailed template for complex extraction (slower, higher quality)\ntemplate_string DetailedExtractContentGraphPrompt() #"\n You are a top-tier algorithm designed for extracting information in structured formats to build a knowledge graph.\n **Nodes** represent entities and concepts. They\'re akin to Wikipedia nodes.\n **Edges** represent relationships between concepts. They\'re akin to Wikipedia links.\n\n The aim is to achieve simplicity and clarity in the knowledge graph.\n\n # 1. Labeling Nodes\n **Consistency**: Ensure you use basic or elementary types for node labels.\n - For example, when you identify an entity representing a person, always label it as **"Person"**.\n - Avoid using more specific terms like "Mathematician" or "Scientist", keep those as "profession" property.\n - Don\'t use too generic terms like "Entity".\n **Node IDs**: Never utilize integers as node IDs.\n - Node IDs should be names or human-readable identifiers found in the text.\n\n # 2. Handling Numerical Data and Dates\n - For example, when you identify an entity representing a date, make sure it has type **"Date"**.\n - Extract the date in the format "YYYY-MM-DD"\n - If not possible to extract the whole date, extract month or year, or both if available.\n - **Property Format**: Properties must be in a key-value format.\n - **Quotation Marks**: Never use escaped single or double quotes within property values.\n - **Naming Convention**: Use snake_case for relationship names, e.g., `acted_in`.\n\n # 3. Coreference Resolution\n - **Maintain Entity Consistency**: When extracting entities, it\'s vital to ensure consistency.\n If an entity, such as "John Doe", is mentioned multiple times in the text but is referred to by different names or pronouns (e.g., "Joe", "he"),\n always use the most complete identifier for that entity throughout the knowledge graph. In this example, use "John Doe" as the Person\'s ID.\n Remember, the knowledge graph should be coherent and easily understandable, so maintaining consistency in entity references is crucial.\n\n # 4. Strict Compliance\n Adhere to the rules strictly. Non-compliance will result in termination.\n"#\n\n// Guided template with step-by-step instructions\ntemplate_string GuidedExtractContentGraphPrompt() #"\n You are an advanced algorithm designed to extract structured information to build a clean, consistent, and human-readable knowledge graph.\n\n **Objective**:\n - Nodes represent entities and concepts, similar to Wikipedia articles.\n - Edges represent typed relationships between nodes, similar to Wikipedia hyperlinks.\n - The graph must be clear, minimal, consistent, and semantically precise.\n\n **Node Guidelines**:\n\n 1. **Label Consistency**:\n - Use consistent, basic types for all node labels.\n - Do not switch between granular or vague labels for the same kind of entity.\n - Pick one label for each category and apply it uniformly.\n - Each entity type should be in a singular form and in a case of multiple words separated by whitespaces\n\n 2. **Node Identifiers**:\n - Node IDs must be human-readable and derived directly from the text.\n - Prefer full names and canonical terms.\n - Never use integers or autogenerated IDs.\n - *Example*: Use "Marie Curie", "Theory of Evolution", "Google".\n\n 3. **Coreference Resolution**:\n - Maintain one consistent node ID for each real-world entity.\n - Resolve aliases, acronyms, and pronouns to the most complete form.\n - *Example*: Always use "John Doe" even if later referred to as "Doe" or "he".\n\n **Edge Guidelines**:\n\n 4. **Relationship Labels**:\n - Use descriptive, lowercase, snake_case names for edges.\n - *Example*: born_in, married_to, invented_by.\n - Avoid vague or generic labels like isA, relatesTo, has.\n\n 5. **Relationship Direction**:\n - Edges must be directional and logically consistent.\n - *Example*:\n - "Marie Curie" —[born_in]→ "Warsaw"\n - "Radioactivity" —[discovered_by]→ "Marie Curie"\n\n **Compliance**:\n Strict adherence to these guidelines is required. Any deviation will result in immediate termination of the task.\n"#\n\n// Strict template with zero-tolerance rules\ntemplate_string StrictExtractContentGraphPrompt() #"\n You are a top-tier algorithm for **extracting structured information** from unstructured text to build a **knowledge graph**.\n\n Your primary goal is to extract:\n - **Nodes**: Representing **entities** and **concepts** (like Wikipedia nodes).\n - **Edges**: Representing **relationships** between those concepts (like Wikipedia links).\n\n The resulting knowledge graph must be **simple, consistent, and human-readable**.\n\n ## 1. Node Labeling and Identification\n\n ### Node Types\n Use **basic atomic types** for node labels. Always prefer general types over specific roles or professions:\n - "Person" for any human.\n - "Organization" for companies, institutions, etc.\n - "Location" for geographic or place entities.\n - "Date" for any temporal expression.\n - "Event" for historical or scheduled occurrences.\n - "Work" for books, films, artworks, or research papers.\n - "Concept" for abstract notions or ideas.\n\n ### Node IDs\n - Always assign **human-readable and unambiguous identifiers**.\n - Never use numeric or autogenerated IDs.\n - Prioritize **most complete form** of entity names for consistency.\n\n ## 2. Relationship Handling\n - Use **snake_case** for all relationship (edge) types.\n - Keep relationship types semantically clear and consistent.\n - Avoid vague relation names like "related_to" unless no better alternative exists.\n\n ## 3. Strict Compliance\n Follow all rules exactly. Any deviation may lead to rejection or incorrect graph construction.\n"#\n\n// OpenAI client with environment model selection\nclient OpenAI {\n provider openai\n options {\n model client_registry.model\n api_key client_registry.api_key\n }\n}\n\n\n\n// Function that returns raw structured output (for custom objects - to be handled in Python)\nfunction ExtractContentGraphGeneric(\n content: string,\n mode: "simple" | "base" | "guided" | "strict" | "custom"?,\n custom_prompt_content: string?\n) -> KnowledgeGraph {\n client OpenAI\n\n prompt #"\n {% if mode == "base" %}\n {{ DetailedExtractContentGraphPrompt() }}\n {% elif mode == "guided" %}\n {{ GuidedExtractContentGraphPrompt() }}\n {% elif mode == "strict" %}\n {{ StrictExtractContentGraphPrompt() }}\n {% elif mode == "custom" and custom_prompt_content %}\n {{ custom_prompt_content }}\n {% else %}\n {{ ExtractContentGraphPrompt() }}\n {% endif %}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n Before answering, briefly describe what you\'ll extract from the text, then provide the structured output.\n\n Example format:\n I\'ll extract the main entities and their relationships from this text...\n\n { ... }\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\n// Backward-compatible function specifically for KnowledgeGraph\nfunction ExtractDynamicContentGraph(\n content: string,\n mode: "simple" | "base" | "guided" | "strict" | "custom"?,\n custom_prompt_content: string?\n) -> DynamicKnowledgeGraph {\n client OpenAI\n\n prompt #"\n {% if mode == "base" %}\n {{ DetailedExtractContentGraphPrompt() }}\n {% elif mode == "guided" %}\n {{ GuidedExtractContentGraphPrompt() }}\n {% elif mode == "strict" %}\n {{ StrictExtractContentGraphPrompt() }}\n {% elif mode == "custom" and custom_prompt_content %}\n {{ custom_prompt_content }}\n {% else %}\n {{ ExtractContentGraphPrompt() }}\n {% endif %}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n Before answering, briefly describe what you\'ll extract from the text, then provide the structured output.\n\n Example format:\n I\'ll extract the main entities and their relationships from this text...\n\n { ... }\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\n\n// Summarization functions\nfunction SummarizeContent(content: string) -> SummarizedContent {\n client OpenAI\n\n prompt #"\n {{ SummarizeContentPrompt() }}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\nfunction SummarizeCode(content: string) -> SummarizedCode {\n client OpenAI\n\n prompt #"\n {{ SummarizeCodePrompt() }}\n\n {{ ctx.output_format(prefix="Answer in this schema:\\n") }}\n\n {{ _.role(\'user\') }}\n {{ content }}\n "#\n}\n\ntest ExtractStrictExample {\n functions [ExtractContentGraphGeneric]\n args {\n content #"\n The Python programming language was created by Guido van Rossum in 1991.\n "#\n mode "strict"\n }\n}\n', + "generators.baml": '// This helps use auto generate libraries you can use in the language of\n// your choice. You can have multiple generators if you use multiple languages.\n// Just ensure that the output_dir is different for each generator.\ngenerator target {\n // Valid values: "python/pydantic", "typescript", "ruby/sorbet", "rest/openapi"\n output_type "python/pydantic"\n\n // Where the generated code will be saved (relative to baml_src/)\n output_dir "../"\n\n // The version of the BAML package you have installed (e.g. same version as your baml-py or @boundaryml/baml).\n // The BAML VSCode extension version should also match this version.\n version "0.206.0"\n\n // Valid values: "sync", "async"\n // This controls what `b.FunctionName()` will be (sync or async).\n default_client_mode async\n}\n', } diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/parser.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/parser.py index d98844e9e..a5535994a 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/parser.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/parser.py @@ -23,6 +23,16 @@ class LlmResponseParser: def __init__(self, options: DoNotUseDirectlyCallManager): self.__options = options + def AcreateStructuredOutput( + self, + llm_response: str, + baml_options: BamlCallOptions = {}, + ) -> types.DynamicModel: + result = self.__options.merge_options(baml_options).parse_response( + function_name="AcreateStructuredOutput", llm_response=llm_response, mode="request" + ) + return typing.cast(types.DynamicModel, result) + def ExtractCategories( self, llm_response: str, @@ -80,6 +90,16 @@ class LlmStreamParser: def __init__(self, options: DoNotUseDirectlyCallManager): self.__options = options + def AcreateStructuredOutput( + self, + llm_response: str, + baml_options: BamlCallOptions = {}, + ) -> stream_types.DynamicModel: + result = self.__options.merge_options(baml_options).parse_response( + function_name="AcreateStructuredOutput", llm_response=llm_response, mode="stream" + ) + return typing.cast(stream_types.DynamicModel, result) + def ExtractCategories( self, llm_response: str, diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/stream_types.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/stream_types.py index 81ad00adc..8c6f12f09 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/stream_types.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/stream_types.py @@ -27,7 +27,7 @@ class StreamState(BaseModel, typing.Generic[StreamStateValueT]): # ######################################################################### -# Generated classes (17) +# Generated classes (18) # ######################################################################### @@ -50,6 +50,11 @@ class DynamicKnowledgeGraph(BaseModel): model_config = ConfigDict(extra="allow") +class DynamicModel(BaseModel): + model_config = ConfigDict(extra="allow") + test: typing.Optional[str] = None + + class Edge(BaseModel): # doc string for edge # doc string for source_node_id diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/sync_client.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/sync_client.py index 854df2d05..6c7669d5d 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/sync_client.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/sync_client.py @@ -89,6 +89,25 @@ class BamlSyncClient: def parse_stream(self): return self.__llm_stream_parser + def AcreateStructuredOutput( + self, + content: str, + system_prompt: str, + user_prompt: str, + baml_options: BamlCallOptions = {}, + ) -> types.DynamicModel: + result = self.__options.merge_options(baml_options).call_function_sync( + function_name="AcreateStructuredOutput", + args={ + "content": content, + "system_prompt": system_prompt, + "user_prompt": user_prompt, + }, + ) + return typing.cast( + types.DynamicModel, result.cast_to(types, types, stream_types, False, __runtime__) + ) + def ExtractCategories( self, content: str, @@ -197,6 +216,32 @@ class BamlStreamClient: def __init__(self, options: DoNotUseDirectlyCallManager): self.__options = options + def AcreateStructuredOutput( + self, + content: str, + system_prompt: str, + user_prompt: str, + baml_options: BamlCallOptions = {}, + ) -> baml_py.BamlSyncStream[stream_types.DynamicModel, types.DynamicModel]: + ctx, result = self.__options.merge_options(baml_options).create_sync_stream( + function_name="AcreateStructuredOutput", + args={ + "content": content, + "system_prompt": system_prompt, + "user_prompt": user_prompt, + }, + ) + return baml_py.BamlSyncStream[stream_types.DynamicModel, types.DynamicModel]( + result, + lambda x: typing.cast( + stream_types.DynamicModel, x.cast_to(types, types, stream_types, True, __runtime__) + ), + lambda x: typing.cast( + types.DynamicModel, x.cast_to(types, types, stream_types, False, __runtime__) + ), + ctx, + ) + def ExtractCategories( self, content: str, @@ -351,6 +396,24 @@ class BamlHttpRequestClient: def __init__(self, options: DoNotUseDirectlyCallManager): self.__options = options + def AcreateStructuredOutput( + self, + content: str, + system_prompt: str, + user_prompt: str, + baml_options: BamlCallOptions = {}, + ) -> baml_py.baml_py.HTTPRequest: + result = self.__options.merge_options(baml_options).create_http_request_sync( + function_name="AcreateStructuredOutput", + args={ + "content": content, + "system_prompt": system_prompt, + "user_prompt": user_prompt, + }, + mode="request", + ) + return result + def ExtractCategories( self, content: str, @@ -452,6 +515,24 @@ class BamlHttpStreamRequestClient: def __init__(self, options: DoNotUseDirectlyCallManager): self.__options = options + def AcreateStructuredOutput( + self, + content: str, + system_prompt: str, + user_prompt: str, + baml_options: BamlCallOptions = {}, + ) -> baml_py.baml_py.HTTPRequest: + result = self.__options.merge_options(baml_options).create_http_request_sync( + function_name="AcreateStructuredOutput", + args={ + "content": content, + "system_prompt": system_prompt, + "user_prompt": user_prompt, + }, + mode="stream", + ) + return result + def ExtractCategories( self, content: str, diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/type_builder.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/type_builder.py index c90cd96cd..00b977bc9 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/type_builder.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/type_builder.py @@ -25,6 +25,7 @@ class TypeBuilder(type_builder.TypeBuilder): "ContentLabel", "DefaultContentPrediction", "DynamicKnowledgeGraph", + "DynamicModel", "Edge", "ImageContent", "KnowledgeGraph", @@ -49,7 +50,7 @@ class TypeBuilder(type_builder.TypeBuilder): # ######################################################################### # ######################################################################### - # Generated classes 17 + # Generated classes 18 # ######################################################################### @property @@ -68,6 +69,10 @@ class TypeBuilder(type_builder.TypeBuilder): def DynamicKnowledgeGraph(self) -> "DynamicKnowledgeGraphBuilder": return DynamicKnowledgeGraphBuilder(self) + @property + def DynamicModel(self) -> "DynamicModelBuilder": + return DynamicModelBuilder(self) + @property def Edge(self) -> "EdgeViewer": return EdgeViewer(self) @@ -127,7 +132,7 @@ class TypeBuilder(type_builder.TypeBuilder): # ######################################################################### -# Generated classes 17 +# Generated classes 18 # ######################################################################### @@ -305,6 +310,53 @@ class DynamicKnowledgeGraphProperties: return self.__bldr.property(name) +class DynamicModelAst: + def __init__(self, tb: type_builder.TypeBuilder): + _tb = tb._tb # type: ignore (we know how to use this private attribute) + self._bldr = _tb.class_("DynamicModel") + self._properties: typing.Set[str] = set( + [ + "test", + ] + ) + self._props = DynamicModelProperties(self._bldr, self._properties) + + def type(self) -> baml_py.FieldType: + return self._bldr.field() + + @property + def props(self) -> "DynamicModelProperties": + return self._props + + +class DynamicModelBuilder(DynamicModelAst): + def __init__(self, tb: type_builder.TypeBuilder): + super().__init__(tb) + + def add_property(self, name: str, type: baml_py.FieldType) -> baml_py.ClassPropertyBuilder: + if name in self._properties: + raise ValueError(f"Property {name} already exists.") + return self._bldr.property(name).type(type) + + def list_properties(self) -> typing.List[typing.Tuple[str, baml_py.ClassPropertyBuilder]]: + return [(name, self._bldr.property(name)) for name in self._properties] + + +class DynamicModelProperties: + def __init__(self, bldr: baml_py.ClassBuilder, properties: typing.Set[str]): + self.__bldr = bldr + self.__properties = properties # type: ignore (we know how to use this private attribute) # noqa: F821 + + def __getattr__(self, name: str) -> baml_py.ClassPropertyBuilder: + if name not in self.__properties: + raise AttributeError(f"Property {name} not found.") + return self.__bldr.property(name) + + @property + def test(self) -> baml_py.ClassPropertyBuilder: + return self.__bldr.property("test") + + class EdgeAst: def __init__(self, tb: type_builder.TypeBuilder): _tb = tb._tb # type: ignore (we know how to use this private attribute) diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/type_map.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/type_map.py index d8188a7b3..d56e660a7 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/type_map.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/type_map.py @@ -23,6 +23,8 @@ type_map = { "stream_types.DefaultContentPrediction": stream_types.DefaultContentPrediction, "types.DynamicKnowledgeGraph": types.DynamicKnowledgeGraph, "stream_types.DynamicKnowledgeGraph": stream_types.DynamicKnowledgeGraph, + "types.DynamicModel": types.DynamicModel, + "stream_types.DynamicModel": stream_types.DynamicModel, "types.Edge": types.Edge, "stream_types.Edge": stream_types.Edge, "types.ImageContent": types.ImageContent, diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/types.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/types.py index 7b965d889..f2c51ed89 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/types.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/types.py @@ -48,7 +48,7 @@ def all_succeeded(checks: typing.Dict[CheckName, Check]) -> bool: # ######################################################################### # ######################################################################### -# Generated classes (17) +# Generated classes (18) # ######################################################################### @@ -79,6 +79,11 @@ class DynamicKnowledgeGraph(BaseModel): model_config = ConfigDict(extra="allow") +class DynamicModel(BaseModel): + model_config = ConfigDict(extra="allow") + test: str + + class Edge(BaseModel): # doc string for edge # doc string for source_node_id diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/acreate_structured_output.baml b/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/acreate_structured_output.baml new file mode 100644 index 000000000..b826d9be1 --- /dev/null +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/acreate_structured_output.baml @@ -0,0 +1,20 @@ +class DynamicModel { + test string + @@dynamic +} + +function AcreateStructuredOutput( + content: string, + system_prompt: string, + user_prompt: string, +) -> DynamicModel { + client OpenAI + + prompt #" + {{ system_prompt }} + {{ ctx.output_format }} + {{ _.role('user') }} + {{ user_prompt }} + {{ content }} + "# +} diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/__init__.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/__init__.py index 157cbe7e7..3e32feec1 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/__init__.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/__init__.py @@ -1,2 +1,3 @@ from .knowledge_graph.extract_content_graph import extract_content_graph from .extract_summary import extract_summary, extract_code_summary +from .acreate_structured_output import acreate_structured_output diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/acreate_structured_output.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/acreate_structured_output.py new file mode 100644 index 000000000..e9e8b8b6b --- /dev/null +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/acreate_structured_output.py @@ -0,0 +1,46 @@ +import os +import asyncio +from typing import Type +from pydantic import BaseModel +from cognee.shared.logging_utils import get_logger +from cognee.shared.data_models import SummarizedCode +from cognee.infrastructure.llm.structured_output_framework.baml.baml_client.async_client import b +from cognee.infrastructure.llm.config import get_llm_config + + +logger = get_logger("extract_summary_baml") + + +async def acreate_structured_output( + content: str, system_prompt: str, user_prompt: str, response_model: Type[BaseModel] +): + """ + Extract summary using BAML framework. + + Args: + content: The content to summarize + response_model: The Pydantic model type for the response + + Returns: + BaseModel: The summarized content in the specified format + """ + config = get_llm_config() + + # Use BAML's SummarizeContent function + result = await b.AcreateStructuredOutput( + content=content, + system_prompt=system_prompt, + user_prompt=user_prompt, + baml_options={"client_registry": config.baml_registry}, + ) + + return result + + +if __name__ == "__main__": + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + loop.run_until_complete(acreate_structured_output("TEST", SummarizedCode)) + finally: + loop.run_until_complete(loop.shutdown_asyncgens()) diff --git a/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/generators.baml b/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/generators.baml index ac4f08efb..a0cd44f56 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/generators.baml +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_src/generators.baml @@ -6,13 +6,13 @@ generator target { output_type "python/pydantic" // Where the generated code will be saved (relative to baml_src/) - output_dir "../baml/" + output_dir "../" // The version of the BAML package you have installed (e.g. same version as your baml-py or @boundaryml/baml). // The BAML VSCode extension version should also match this version. - version "0.201.0" + version "0.206.0" // Valid values: "sync", "async" // This controls what `b.FunctionName()` will be (sync or async). - default_client_mode sync + default_client_mode async }