From 6231882c24b8d59eda992230dd14387db773e134 Mon Sep 17 00:00:00 2001 From: Igor Ilic Date: Mon, 8 Sep 2025 12:55:33 +0200 Subject: [PATCH] refactor: Add baml client changes --- .../baml/baml_client/__init__.py | 2 +- .../baml/baml_client/async_client.py | 185 ++++++++++++------ .../baml/baml_client/inlinedbaml.py | 2 +- .../baml/baml_client/runtime.py | 78 ++++++++ .../baml/baml_client/sync_client.py | 179 +++++++++++------ .../baml/baml_client/type_builder.py | 27 ++- 6 files changed, 344 insertions(+), 129 deletions(-) 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 e25104d0b..1f3cf9932 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 @@ -10,7 +10,7 @@ # BAML files and re-generate this code using: baml-cli generate # baml-cli is available with the baml package. -__version__ = "0.201.0" +__version__ = "0.206.1" try: from baml_py.safe_import import EnsureBamlPyImport 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 35f810729..ac35cd1b1 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 @@ -44,6 +44,7 @@ class BamlAsyncClient: typing.Union[baml_py.baml_py.Collector, typing.List[baml_py.baml_py.Collector]] ] = None, env: typing.Optional[typing.Dict[str, typing.Optional[str]]] = None, + on_tick: typing.Optional[typing.Callable[[str, baml_py.baml_py.FunctionLog], None]] = None, ) -> "BamlAsyncClient": options: BamlCallOptions = {} if tb is not None: @@ -54,6 +55,8 @@ class BamlAsyncClient: options["collector"] = collector if env is not None: options["env"] = env + if on_tick is not None: + options["on_tick"] = on_tick return BamlAsyncClient(self.__options.merge_options(options)) @property @@ -83,33 +86,52 @@ class BamlAsyncClient: 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__) - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + # Use streaming internally when on_tick is provided + stream = self.stream.AcreateStructuredOutput( + content=content, + system_prompt=system_prompt, + user_prompt=user_prompt, + baml_options=baml_options, + ) + return await stream.get_final_response() + else: + # Original non-streaming code + 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, baml_options: BamlCallOptions = {}, ) -> types.DefaultContentPrediction: - result = await self.__options.merge_options(baml_options).call_function_async( - function_name="ExtractCategories", - args={ - "content": content, - }, - ) - return typing.cast( - types.DefaultContentPrediction, - result.cast_to(types, types, stream_types, False, __runtime__), - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + # Use streaming internally when on_tick is provided + stream = self.stream.ExtractCategories(content=content, baml_options=baml_options) + return await stream.get_final_response() + else: + # Original non-streaming code + result = await self.__options.merge_options(baml_options).call_function_async( + function_name="ExtractCategories", + args={ + "content": content, + }, + ) + return typing.cast( + types.DefaultContentPrediction, + result.cast_to(types, types, stream_types, False, __runtime__), + ) async def ExtractContentGraphGeneric( self, @@ -126,17 +148,29 @@ class BamlAsyncClient: custom_prompt_content: typing.Optional[str] = None, baml_options: BamlCallOptions = {}, ) -> types.KnowledgeGraph: - result = await self.__options.merge_options(baml_options).call_function_async( - function_name="ExtractContentGraphGeneric", - args={ - "content": content, - "mode": mode, - "custom_prompt_content": custom_prompt_content, - }, - ) - return typing.cast( - types.KnowledgeGraph, result.cast_to(types, types, stream_types, False, __runtime__) - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + # Use streaming internally when on_tick is provided + stream = self.stream.ExtractContentGraphGeneric( + content=content, + mode=mode, + custom_prompt_content=custom_prompt_content, + baml_options=baml_options, + ) + return await stream.get_final_response() + else: + # Original non-streaming code + result = await self.__options.merge_options(baml_options).call_function_async( + function_name="ExtractContentGraphGeneric", + args={ + "content": content, + "mode": mode, + "custom_prompt_content": custom_prompt_content, + }, + ) + return typing.cast( + types.KnowledgeGraph, result.cast_to(types, types, stream_types, False, __runtime__) + ) async def ExtractDynamicContentGraph( self, @@ -153,48 +187,75 @@ class BamlAsyncClient: custom_prompt_content: typing.Optional[str] = None, baml_options: BamlCallOptions = {}, ) -> types.DynamicKnowledgeGraph: - result = await self.__options.merge_options(baml_options).call_function_async( - function_name="ExtractDynamicContentGraph", - args={ - "content": content, - "mode": mode, - "custom_prompt_content": custom_prompt_content, - }, - ) - return typing.cast( - types.DynamicKnowledgeGraph, - result.cast_to(types, types, stream_types, False, __runtime__), - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + # Use streaming internally when on_tick is provided + stream = self.stream.ExtractDynamicContentGraph( + content=content, + mode=mode, + custom_prompt_content=custom_prompt_content, + baml_options=baml_options, + ) + return await stream.get_final_response() + else: + # Original non-streaming code + result = await self.__options.merge_options(baml_options).call_function_async( + function_name="ExtractDynamicContentGraph", + args={ + "content": content, + "mode": mode, + "custom_prompt_content": custom_prompt_content, + }, + ) + return typing.cast( + types.DynamicKnowledgeGraph, + result.cast_to(types, types, stream_types, False, __runtime__), + ) async def SummarizeCode( self, content: str, baml_options: BamlCallOptions = {}, ) -> types.SummarizedCode: - result = await self.__options.merge_options(baml_options).call_function_async( - function_name="SummarizeCode", - args={ - "content": content, - }, - ) - return typing.cast( - types.SummarizedCode, result.cast_to(types, types, stream_types, False, __runtime__) - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + # Use streaming internally when on_tick is provided + stream = self.stream.SummarizeCode(content=content, baml_options=baml_options) + return await stream.get_final_response() + else: + # Original non-streaming code + result = await self.__options.merge_options(baml_options).call_function_async( + function_name="SummarizeCode", + args={ + "content": content, + }, + ) + return typing.cast( + types.SummarizedCode, result.cast_to(types, types, stream_types, False, __runtime__) + ) async def SummarizeContent( self, content: str, baml_options: BamlCallOptions = {}, ) -> types.SummarizedContent: - result = await self.__options.merge_options(baml_options).call_function_async( - function_name="SummarizeContent", - args={ - "content": content, - }, - ) - return typing.cast( - types.SummarizedContent, result.cast_to(types, types, stream_types, False, __runtime__) - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + # Use streaming internally when on_tick is provided + stream = self.stream.SummarizeContent(content=content, baml_options=baml_options) + return await stream.get_final_response() + else: + # Original non-streaming code + result = await self.__options.merge_options(baml_options).call_function_async( + function_name="SummarizeContent", + args={ + "content": content, + }, + ) + return typing.cast( + types.SummarizedContent, + result.cast_to(types, types, stream_types, False, __runtime__), + ) class BamlStreamClient: 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 17745b6d8..12b61094f 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,7 +11,7 @@ # 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}", + "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}\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}\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/runtime.py b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/runtime.py index 1955e5c14..3d042bd50 100644 --- a/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/runtime.py +++ b/cognee/infrastructure/llm/structured_output_framework/baml/baml_client/runtime.py @@ -30,6 +30,10 @@ class BamlCallOptions(typing.TypedDict, total=False): collector: typing_extensions.NotRequired[ typing.Union[baml_py.baml_py.Collector, typing.List[baml_py.baml_py.Collector]] ] + abort_controller: typing_extensions.NotRequired[baml_py.baml_py.AbortController] + on_tick: typing_extensions.NotRequired[ + typing.Callable[[str, baml_py.baml_py.FunctionLog], None] + ] class _ResolvedBamlOptions: @@ -37,6 +41,8 @@ class _ResolvedBamlOptions: client_registry: typing.Optional[baml_py.baml_py.ClientRegistry] collectors: typing.List[baml_py.baml_py.Collector] env_vars: typing.Dict[str, str] + abort_controller: typing.Optional[baml_py.baml_py.AbortController] + on_tick: typing.Optional[typing.Callable[[], None]] def __init__( self, @@ -44,11 +50,15 @@ class _ResolvedBamlOptions: client_registry: typing.Optional[baml_py.baml_py.ClientRegistry], collectors: typing.List[baml_py.baml_py.Collector], env_vars: typing.Dict[str, str], + abort_controller: typing.Optional[baml_py.baml_py.AbortController], + on_tick: typing.Optional[typing.Callable[[], None]], ): self.tb = tb self.client_registry = client_registry self.collectors = collectors self.env_vars = env_vars + self.abort_controller = abort_controller + self.on_tick = on_tick class DoNotUseDirectlyCallManager: @@ -85,11 +95,27 @@ class DoNotUseDirectlyCallManager: else: env_vars.pop(k, None) + abort_controller = self.__baml_options.get("abort_controller") + + on_tick = self.__baml_options.get("on_tick") + if on_tick is not None: + collector = baml_py.baml_py.Collector("on-tick-collector") + collectors_as_list.append(collector) + + def on_tick_wrapper(): + log = collector.last + if log is not None: + on_tick("Unknown", log) + else: + on_tick_wrapper = None + return _ResolvedBamlOptions( baml_tb, client_registry, collectors_as_list, env_vars, + abort_controller, + on_tick_wrapper, ) def merge_options(self, options: BamlCallOptions) -> "DoNotUseDirectlyCallManager": @@ -99,6 +125,14 @@ class DoNotUseDirectlyCallManager: self, *, function_name: str, args: typing.Dict[str, typing.Any] ) -> baml_py.baml_py.FunctionResult: resolved_options = self.__resolve() + + # Check if already aborted + if ( + resolved_options.abort_controller is not None + and resolved_options.abort_controller.aborted + ): + raise Exception("BamlAbortError: Operation was aborted") + return await __runtime__.call_function( function_name, args, @@ -112,12 +146,22 @@ class DoNotUseDirectlyCallManager: resolved_options.collectors, # env_vars resolved_options.env_vars, + # abort_controller + resolved_options.abort_controller, ) def call_function_sync( self, *, function_name: str, args: typing.Dict[str, typing.Any] ) -> baml_py.baml_py.FunctionResult: resolved_options = self.__resolve() + + # Check if already aborted + if ( + resolved_options.abort_controller is not None + and resolved_options.abort_controller.aborted + ): + raise Exception("BamlAbortError: Operation was aborted") + ctx = __ctx__manager__.get() return __runtime__.call_function_sync( function_name, @@ -132,6 +176,8 @@ class DoNotUseDirectlyCallManager: resolved_options.collectors, # env_vars resolved_options.env_vars, + # abort_controller + resolved_options.abort_controller, ) def create_async_stream( @@ -158,6 +204,8 @@ class DoNotUseDirectlyCallManager: resolved_options.collectors, # env_vars resolved_options.env_vars, + # on_tick + resolved_options.on_tick, ) return ctx, result @@ -170,6 +218,10 @@ class DoNotUseDirectlyCallManager: baml_py.baml_py.RuntimeContextManager, baml_py.baml_py.SyncFunctionResultStream ]: resolved_options = self.__resolve() + if resolved_options.on_tick is not None: + raise ValueError( + "on_tick is not supported for sync streams. Please use async streams instead." + ) ctx = __ctx__manager__.get() result = __runtime__.stream_function_sync( function_name, @@ -187,6 +239,9 @@ class DoNotUseDirectlyCallManager: resolved_options.collectors, # env_vars resolved_options.env_vars, + # on_tick + # always None! sync streams don't support on_tick + None, ) return ctx, result @@ -264,3 +319,26 @@ class DoNotUseDirectlyCallManager: # env_vars resolved_options.env_vars, ) + + +def disassemble(function: typing.Callable) -> None: + import inspect + from . import b + + if not callable(function): + print(f"disassemble: object {function} is not a Baml function") + return + + is_client_method = False + + for method_name, _ in inspect.getmembers(b, predicate=inspect.ismethod): + if method_name == function.__name__: + is_client_method = True + break + + if not is_client_method: + print(f"disassemble: function {function.__name__} is not a Baml function") + return + + print(f"----- function {function.__name__} -----") + __runtime__.disassemble(function.__name__) 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 6c7669d5d..3af7f5741 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 @@ -57,6 +57,7 @@ class BamlSyncClient: typing.Union[baml_py.baml_py.Collector, typing.List[baml_py.baml_py.Collector]] ] = None, env: typing.Optional[typing.Dict[str, typing.Optional[str]]] = None, + on_tick: typing.Optional[typing.Callable[[str, baml_py.baml_py.FunctionLog], None]] = None, ) -> "BamlSyncClient": options: BamlCallOptions = {} if tb is not None: @@ -67,6 +68,8 @@ class BamlSyncClient: options["collector"] = collector if env is not None: options["env"] = env + if on_tick is not None: + options["on_tick"] = on_tick return BamlSyncClient(self.__options.merge_options(options)) @property @@ -96,33 +99,50 @@ class BamlSyncClient: 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__) - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + stream = self.stream.AcreateStructuredOutput( + content=content, + system_prompt=system_prompt, + user_prompt=user_prompt, + baml_options=baml_options, + ) + return stream.get_final_response() + else: + # Original non-streaming code + 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, baml_options: BamlCallOptions = {}, ) -> types.DefaultContentPrediction: - result = self.__options.merge_options(baml_options).call_function_sync( - function_name="ExtractCategories", - args={ - "content": content, - }, - ) - return typing.cast( - types.DefaultContentPrediction, - result.cast_to(types, types, stream_types, False, __runtime__), - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + stream = self.stream.ExtractCategories(content=content, baml_options=baml_options) + return stream.get_final_response() + else: + # Original non-streaming code + result = self.__options.merge_options(baml_options).call_function_sync( + function_name="ExtractCategories", + args={ + "content": content, + }, + ) + return typing.cast( + types.DefaultContentPrediction, + result.cast_to(types, types, stream_types, False, __runtime__), + ) def ExtractContentGraphGeneric( self, @@ -139,17 +159,28 @@ class BamlSyncClient: custom_prompt_content: typing.Optional[str] = None, baml_options: BamlCallOptions = {}, ) -> types.KnowledgeGraph: - result = self.__options.merge_options(baml_options).call_function_sync( - function_name="ExtractContentGraphGeneric", - args={ - "content": content, - "mode": mode, - "custom_prompt_content": custom_prompt_content, - }, - ) - return typing.cast( - types.KnowledgeGraph, result.cast_to(types, types, stream_types, False, __runtime__) - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + stream = self.stream.ExtractContentGraphGeneric( + content=content, + mode=mode, + custom_prompt_content=custom_prompt_content, + baml_options=baml_options, + ) + return stream.get_final_response() + else: + # Original non-streaming code + result = self.__options.merge_options(baml_options).call_function_sync( + function_name="ExtractContentGraphGeneric", + args={ + "content": content, + "mode": mode, + "custom_prompt_content": custom_prompt_content, + }, + ) + return typing.cast( + types.KnowledgeGraph, result.cast_to(types, types, stream_types, False, __runtime__) + ) def ExtractDynamicContentGraph( self, @@ -166,48 +197,72 @@ class BamlSyncClient: custom_prompt_content: typing.Optional[str] = None, baml_options: BamlCallOptions = {}, ) -> types.DynamicKnowledgeGraph: - result = self.__options.merge_options(baml_options).call_function_sync( - function_name="ExtractDynamicContentGraph", - args={ - "content": content, - "mode": mode, - "custom_prompt_content": custom_prompt_content, - }, - ) - return typing.cast( - types.DynamicKnowledgeGraph, - result.cast_to(types, types, stream_types, False, __runtime__), - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + stream = self.stream.ExtractDynamicContentGraph( + content=content, + mode=mode, + custom_prompt_content=custom_prompt_content, + baml_options=baml_options, + ) + return stream.get_final_response() + else: + # Original non-streaming code + result = self.__options.merge_options(baml_options).call_function_sync( + function_name="ExtractDynamicContentGraph", + args={ + "content": content, + "mode": mode, + "custom_prompt_content": custom_prompt_content, + }, + ) + return typing.cast( + types.DynamicKnowledgeGraph, + result.cast_to(types, types, stream_types, False, __runtime__), + ) def SummarizeCode( self, content: str, baml_options: BamlCallOptions = {}, ) -> types.SummarizedCode: - result = self.__options.merge_options(baml_options).call_function_sync( - function_name="SummarizeCode", - args={ - "content": content, - }, - ) - return typing.cast( - types.SummarizedCode, result.cast_to(types, types, stream_types, False, __runtime__) - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + stream = self.stream.SummarizeCode(content=content, baml_options=baml_options) + return stream.get_final_response() + else: + # Original non-streaming code + result = self.__options.merge_options(baml_options).call_function_sync( + function_name="SummarizeCode", + args={ + "content": content, + }, + ) + return typing.cast( + types.SummarizedCode, result.cast_to(types, types, stream_types, False, __runtime__) + ) def SummarizeContent( self, content: str, baml_options: BamlCallOptions = {}, ) -> types.SummarizedContent: - result = self.__options.merge_options(baml_options).call_function_sync( - function_name="SummarizeContent", - args={ - "content": content, - }, - ) - return typing.cast( - types.SummarizedContent, result.cast_to(types, types, stream_types, False, __runtime__) - ) + # Check if on_tick is provided + if "on_tick" in baml_options: + stream = self.stream.SummarizeContent(content=content, baml_options=baml_options) + return stream.get_final_response() + else: + # Original non-streaming code + result = self.__options.merge_options(baml_options).call_function_sync( + function_name="SummarizeContent", + args={ + "content": content, + }, + ) + return typing.cast( + types.SummarizedContent, + result.cast_to(types, types, stream_types, False, __runtime__), + ) class BamlStreamClient: 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 00b977bc9..c4a6a10ca 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 @@ -13,6 +13,9 @@ import typing from baml_py import type_builder from baml_py import baml_py + +# These are exports, not used here, hence the linter is disabled +from baml_py.baml_py import FieldType, EnumValueBuilder, EnumBuilder, ClassBuilder # noqa: F401 # pylint: disable=unused-import from .globals import DO_NOT_USE_DIRECTLY_UNLESS_YOU_KNOW_WHAT_YOURE_DOING_RUNTIME @@ -296,7 +299,13 @@ class DynamicKnowledgeGraphBuilder(DynamicKnowledgeGraphAst): 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] + return self._bldr.list_properties() + + def remove_property(self, name: str) -> None: + self._bldr.remove_property(name) + + def reset(self) -> None: + self._bldr.reset() class DynamicKnowledgeGraphProperties: @@ -339,7 +348,13 @@ class DynamicModelBuilder(DynamicModelAst): 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] + return self._bldr.list_properties() + + def remove_property(self, name: str) -> None: + self._bldr.remove_property(name) + + def reset(self) -> None: + self._bldr.reset() class DynamicModelProperties: @@ -619,7 +634,13 @@ class NodeBuilder(NodeAst): 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] + return self._bldr.list_properties() + + def remove_property(self, name: str) -> None: + self._bldr.remove_property(name) + + def reset(self) -> None: + self._bldr.reset() class NodeProperties: