### Python: Quick Start with FileDataProvider Source: https://github.com/burhan-q/proompt/blob/main/README.md Illustrates a basic usage of Proompt by reading content from a file using `FileDataProvider` and preparing it for LLM analysis. ```python from proompt.data import FileDataProvider # Read a file and inject it into your prompt provider = FileDataProvider("data.txt") content = provider.run() # Returns file contents as string print(f"Analyze the data:\n{content}") ``` -------------------------------- ### Quarterly Business Review Example (Python) Source: https://context7.com/burhan-q/proompt/llms.txt This comprehensive example demonstrates the complete workflow of generating a quarterly business review using the proompt framework. It includes custom data providers, contexts, tool contexts, prompt sections, and a complete prompt, showcasing the flexibility and power of the framework. ```python from proompt.base.context import Context, ToolContext from proompt.base.prompt import BasePrompt, PromptSection from proompt.base.provider import BaseProvider from proompt.data import CsvDataProvider from datetime import datetime from textwrap import dedent, indent import random # Custom Data Provider class MetricsProvider(BaseProvider[dict]): def __init__(self, quarter: str): self.quarter = quarter @property def name(self) -> str: return f"Metrics for {self.quarter}" @property def provider_ctx(self) -> str: return f"Business metrics for {self.quarter}" def run(self) -> dict: return { "quarter": self.quarter, "revenue": random.randint(1000000, 2000000), "users": random.randint(50000, 100000), "growth": round(random.uniform(0.05, 0.15), 3), } # Custom Context class ReviewContext(Context): def __init__(self, company: str, quarter: str): self.company = company self.quarter = quarter def render(self) -> str: return f"Review for {self.company} - {self.quarter}" # Analysis Tool def calculate_growth(current: float, previous: float) -> dict: """Calculate growth rate between periods.""" rate = (current - previous) / previous if previous else 0 return {"rate": f"{rate:.1%}", "trend": "up" if rate > 0 else "down"} # Custom Prompt Section class MetricsSection(PromptSection): def _format_metrics(self, metrics: dict) -> str: return dedent(f"""\ ## {metrics[\"quarter\"]} Metrics - Revenue: ${metrics[\"revenue\"]:,} - Users: {metrics[\"users\"]:,} - Growth: {metrics[\"growth\"]:.1%}“”").strip() def formatter(self) -> str: data_parts = [] for provider in self.providers: if isinstance(provider, MetricsProvider): data_parts.append(self._format_metrics(provider.run())) data = "\n\n".join(data_parts) tools = ", ".join(t.tool_name for t in self.tools) return dedent(f"""\ ## QUARTERLY ANALYSIS ### Data: {indent(data, \" \")} ### Tools: {tools} Analyze metrics and provide recommendations. “”").strip() def render(self) -> str: return self.formatter() # Complete Prompt class QuarterlyPrompt(BasePrompt): def __init__(self, company: str, quarter: str, *sections: PromptSection): super().__init__(*sections) self.company = company self.quarter = quarter def render(self) -> str: header = f"# {self.company} - {self.quarter} Review\n\n" content = "\n\n---\n\n".join(s.render() for s in self.sections) footer = f"\n\n---\nGenerated: {datetime.now().strftime('%Y-%m-%d')}" return header + content + footer # Build and render provider = MetricsProvider("Q3 2024") context = ReviewContext("TechCorp", "Q3 2024") tool = ToolContext(calculate_growth) section = MetricsSection(context, [tool], provider) prompt = QuarterlyPrompt("TechCorp", "Q3 2024", section) final_prompt = prompt.render() print(final_prompt) print(f"\nStats: {len(final_prompt):,} chars, {len(final_prompt.split()):,} words") ``` -------------------------------- ### Bash: Installing Proompt Source: https://github.com/burhan-q/proompt/blob/main/README.md Provides the command to install the Proompt library using `uv pip`, a fast Python package installer and resolver. ```bash uv pip install proompt ``` -------------------------------- ### Object-Oriented Prompt Composition Example Source: https://github.com/burhan-q/proompt/blob/main/README.md Illustrates composing prompts using organized, testable objects instead of giant strings. This promotes better organization, easier testing, and reusable prompt components. ```python # Instead of managing giant prompt strings SYSTEM_PROMPT = """You are an assistant...""" DATA_SECTION = """Here is the data: {data}""" TOOL_SECTION = """Available tools: {tools}""" # Compose from organized, testable objects prompt = ChatPrompt( SystemSection("You are an assistant..."), DataSection(providers=[csv_provider, db_provider]), ToolSection(tools=[calculator, parser]) ) ``` -------------------------------- ### Create Custom Data Provider with Proompt Source: https://context7.com/burhan-q/proompt/llms.txt Shows how to create custom data providers by extending `BaseProvider`. This example includes `MetricsAPIProvider` for fetching business metrics and `LogAnalysisProvider` for analyzing system logs. These providers can be integrated into prompts to supply dynamic data. ```python from proompt.base.provider import BaseProvider from proompt.data import TableData import random from datetime import datetime class MetricsAPIProvider(BaseProvider[dict]): """Provider that simulates fetching business metrics from an API.""" def __init__(self, quarter: str, department: str = "all"): self.quarter = quarter self.department = department @property def name(self) -> str: return f"Business Metrics API for {self.quarter} ({self.department})" @property def provider_ctx(self) -> str: return f"Fetches key business metrics for {self.quarter} including revenue, growth, and KPIs." def run(self) -> dict: """Fetch and return business metrics.""" return { "quarter": self.quarter, "department": self.department, "revenue": random.randint(2500000, 3500000), "user_growth_rate": round(random.uniform(0.08, 0.25), 3), "active_users": random.randint(125000, 180000), "churn_rate": round(random.uniform(0.02, 0.08), 3), "net_promoter_score": random.randint(65, 85), "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M"), } class LogAnalysisProvider(BaseProvider[str]): """Provider that analyzes system logs and returns performance report.""" def __init__(self, log_period: str, service_name: str = "web-api"): self.log_period = log_period self.service_name = service_name @property def name(self) -> str: return f"Log Analysis for {self.service_name} ({self.log_period})" @property def provider_ctx(self) -> str: return f"Analyzes {self.service_name} logs over {self.log_period} for performance insights." def run(self) -> str: """Analyze logs and return formatted report.""" total_requests = random.randint(2500000, 4200000) error_rate = round(random.uniform(0.005, 0.025), 4) avg_response = random.randint(125, 350) return f"""## System Performance - {self.log_period} **Service:** {self.service_name} ### Metrics - **Total Requests:** {total_requests:,} - **Error Rate:** {error_rate:.2%} - **Avg Response Time:** {avg_response}ms ### Summary System handled {total_requests:,} requests with {error_rate:.2%} error rate.""" # Usage metrics = MetricsAPIProvider("Q3 2024", "engineering") print(metrics.run()) # Output: dict with business metrics logs = LogAnalysisProvider("September 2024", "web-api") print(logs.run()) # Output: Formatted performance report string ``` -------------------------------- ### Create Custom API Provider Source: https://github.com/burhan-q/proompt/blob/main/README.md Demonstrates how to create a custom data provider by extending `BaseProvider`. This example fetches data from a REST API using the `requests` library and returns JSON. ```python from proompt.base.provider import BaseProvider import requests class ApiProvider(BaseProvider, str): def __init__(self, url: str, api_key: str): self.url = url self.api_key = api_key @property def name(self) -> str: return f"API Provider for {self.url}" @property def provider_ctx(self) -> str: return f"Fetches data from REST API at {self.url}" # NOTE: would be useful to include available endpoints def run(self, endpoint: str) -> str: response = requests.get( f"{self.url}/{endpoint}", headers={"Authorization": f"Bearer {self.api_key}"} ) return response.json() # Use your custom provider api = ApiProvider("https://api.example.com", "your-key") data = api.run("users") ``` -------------------------------- ### Python: Composing Prompts with PromptSection Source: https://github.com/burhan-q/proompt/blob/main/README.md Illustrates how to create custom `PromptSection` classes to compose complex prompts by combining data providers and tool contexts. The example shows a `DataAnalysisSection` that formats instructions, data, and tools for LLM consumption. ```python from textwrap import dedent from proompt.base.prompt import PromptSection class DataAnalysisSection(PromptSection): def formatter(self, instruction: str) -> str: data = "\n\n".join(p.run() for p in self.providers) tools = "\n\n".join(str(t) for t in self.tools) return dedent(f""" {instruction} Available Data Providers: {data} Available Tools: {tools} """) def render(self) -> str: return self.formatter("Analyze the provided data") # Use it section = DataAnalysisSection( context=context, # Use Context to pass dynamic info tools=[ToolContext(calculate_tax)], CsvDataProvider("metrics.csv"), # accepts any number of Providers ) prompt = str(section) # Ready for your LLM ``` -------------------------------- ### QuarterlyReviewPrompt: Compose a Complete Prompt with Multiple Sections (Python) Source: https://context7.com/burhan-q/proompt/llms.txt Illustrates how to create a complete prompt by composing multiple PromptSection instances using the BasePrompt class. This example defines custom sections for metrics and recommendations, and a main prompt class for quarterly reviews. ```python from proompt.base.prompt import BasePrompt, PromptSection from proompt.base.context import Context, ToolContext from proompt.data import CsvDataProvider, SqliteProvider from datetime import datetime from textwrap import dedent class MetricsSection(PromptSection): """Section for metrics analysis.""" def formatter(self) -> str: data = "\n\n".join(p.run() for p in self.providers) return f"## METRICS\n\n{data}" def render(self) -> str: return self.formatter() class RecommendationsSection(PromptSection): """Section for recommendations.""" def formatter(self) -> str: tools = ", ".join(t.tool_name for t in self.tools) return f"## RECOMMENDATIONS\n\nUsing tools: {tools}\n\nProvide actionable recommendations." def render(self) -> str: return self.formatter() class QuarterlyReviewPrompt(BasePrompt): """Complete quarterly review prompt.""" def __init__(self, company: str, quarter: str, *sections: PromptSection): super().__init__(*sections) self.company = company self.quarter = quarter self.generated_at = datetime.now().strftime("%Y-%m-%d %H:%M") def render(self) -> str: # Header header = dedent(f""" # QUARTERLY REVIEW: {self.company} ## {self.quarter} Analysis **Generated:** {self.generated_at} Analyze the following data and provide insights. """).strip() # Combine sections sections_content = "\n\n---\n\n".join( section.render() for section in self.sections ) # Footer footer = dedent(f""" --- ## SUMMARY Data Providers: {sum(len(s.providers) for s in self.sections)} Analysis Tools: {sum(len(s.tools) for s in self.sections)} """).strip() return f"{header}\n\n{sections_content}\n\n{footer}" # Build the complete prompt def analyze_data(values: list) -> dict: """Analyze a list of values.""" return {"mean": sum(values)/len(values), "count": len(values)} metrics_section = MetricsSection( context=None, tools=[], CsvDataProvider("revenue.csv") ) recommendations_section = RecommendationsSection( context=None, tools=[ToolContext(analyze_data)] ) prompt = QuarterlyReviewPrompt( "TechCorp", "Q3 2024", metrics_section, recommendations_section ) print(prompt.render()) ``` -------------------------------- ### Python: Documenting Functions with ToolContext Source: https://github.com/burhan-q/proompt/blob/main/README.md Demonstrates how to use `ToolContext` to automatically generate documentation for Python functions, making them understandable to LLMs. It includes function signature, description, arguments, and return types. ```python from proompt.base.context import ToolContext def calculate_tax(income: float, rate: float = 0.25) -> float: """Calculate tax owed on income.""" return income * rate tool_ctx = ToolContext(calculate_tax) print(tool_ctx.render()) # Name: calculate_tax # Description: Calculate tax owed on income. # Arguments: income: float, rate: float = 0.25 # Returns: float # Usage: Reference description for usage. ``` -------------------------------- ### Python: Using CsvDataProvider and SqliteProvider Source: https://github.com/burhan-q/proompt/blob/main/README.md Shows how to use `CsvDataProvider` to fetch data from a CSV file and `SqliteProvider` to query a SQLite database, formatting the results as markdown tables for LLM consumption. ```python from proompt.data import CsvDataProvider, SqliteProvider # CSV data as markdown tables csv_provider = CsvDataProvider("sales_data.csv") print(csv_provider.run()) # | Product | Sales | Region | # | ------- | ----- | ------ | # | Widget | 1000 | North | # Database queries as markdown tables db_provider = SqliteProvider( "company.db", 'SELECT * FROM employees WHERE department = "Engineering"' ) print(db_provider.run()) # | name | role | salary | # | ----- | --------- | ------ | # | Alice | Developer | 85000 | ``` -------------------------------- ### Python: Composing Prompts with Proompt Components Source: https://github.com/burhan-q/proompt/blob/main/README.md Demonstrates how to construct prompts using Proompt's object-oriented design, contrasting it with messy string concatenation. It utilizes `CsvDataProvider`, `FileDataProvider`, `SqliteProvider`, and `ToolContext` to build a structured `PromptSection`. ```python from proompt.data import ( CsvDataProvider, FileDataProvider, SqliteProvider, ) from proompt.base.context import ToolContext section = PromptSection( context=ToolContext(my_function), CsvDataProvider("data.csv"), FileDataProvider("file.txt"), SqliteProvider("data.db"), ) ``` -------------------------------- ### Execute SQL Queries with SqliteProvider Source: https://github.com/burhan-q/proompt/blob/main/README.md Connects to an SQLite database, executes a specified SQL query, and returns the results as a markdown table. It supports asynchronous execution with `arun()`. ```python from proompt.data import SqliteProvider # Execute SQL queries, get markdown tables provider = SqliteProvider( database_path="app.db", query="SELECT name, email FROM users WHERE active = 1", table_name="users" # Optional, for better context ) # Async support; NOTE the async only runs sync method .run() result = await provider.arun() ``` -------------------------------- ### Execute SQL Queries and Format as Markdown with SqliteProvider in Python Source: https://context7.com/burhan-q/proompt/llms.txt Uses the SqliteProvider to execute SELECT SQL queries against a SQLite database. The results are returned as formatted markdown tables, suitable for LLM input. Supports both synchronous and asynchronous operations. ```python from proompt.data import SqliteProvider # Initialize with database path, query, and optional table name provider = SqliteProvider( database_path="company.db", query='SELECT name, role, salary FROM employees WHERE department = "Engineering"', table_name="employees" # Optional, for better context ) # Execute query and get markdown table result = provider.run() print(result) # Output: # | name | role | salary | # | --- | --- | --- | # | Alice | Developer | 85000 | # | Bob | Lead Engineer | 95000 | # | Carol | Architect | 110000 | # Check provider metadata print(provider.name) # Output: SqliteProvider for company.db from employees print(provider.provider_ctx) # Output: Executes SQL query against SQLite database company.db in table 'employees'. Query: SELECT name, role, salary FROM employees WHERE department = "Engineering" ``` -------------------------------- ### Testing Individual Prompt Components Source: https://github.com/burhan-q/proompt/blob/main/README.md Shows how to test individual components of the prompt system, such as a `CsvDataProvider` or `ToolContext`. This facilitates easier and more robust testing of prompt logic. ```python # Test individual components def test_csv_provider(): provider = CsvDataProvider("test.csv") result = provider.run() assert "| Name |" in result def test_tool_context(): ctx = ToolContext(my_function) assert "my_function" in ctx.render() ``` -------------------------------- ### Initialize Tools in AnalysisSection (Python) Source: https://context7.com/burhan-q/proompt/llms.txt This snippet demonstrates the initialization of an `AnalysisSection` with different types of tools: a traditional `ToolContext`, an individual `pydantic-ai Tool`, and a `FunctionToolset`. It then prints the total number of tools. ```python section = AnalysisSection( tools=[ proompt_tool, # Traditional ToolContext calc_tool, # Individual pydantic-ai Tool analysis_toolset, # FunctionToolset (extracts all tools) ] ) print(f"Total tools: {len(section.tools)}") # Output: Total tools: 5 (1 proompt + 1 individual + 3 from toolset) ``` -------------------------------- ### Generate Complete Prompt using Proompt Source: https://context7.com/burhan-q/proompt/llms.txt Demonstrates how to render a complete prompt string using the `prompt.render()` method or by converting the prompt object to a string using `str(prompt)`. This is a fundamental step in generating the final output for a prompt. ```python final_prompt = prompt.render() print(final_prompt) # Or use str() final_prompt = str(prompt) ``` -------------------------------- ### Reusing Prompt Components Source: https://github.com/burhan-q/proompt/blob/main/README.md Demonstrates the reusability of prompt components, such as a `DataAnalysisSection`. A single section can be incorporated into multiple different prompts for various use cases. ```python # Define once, use everywhere analysis_section = DataAnalysisSection( providers=[CsvDataProvider("metrics.csv")] ) # Reuse in different prompts customer_prompt = CustomerPrompt(analysis_section, ...) admin_prompt = AdminPrompt(analysis_section, ...) ``` -------------------------------- ### Integrate Proompt with Pydantic-AI Tools and Functions Source: https://context7.com/burhan-q/proompt/llms.txt Demonstrates how to combine Proompt's `ToolContext` with pydantic-ai's `Tool` and `FunctionToolset`. This allows for a flexible way to define and use tools within a prompt, including traditional Python functions and pydantic-ai defined tools. ```python from pydantic_ai import Tool, FunctionToolset, RunContext from proompt.base.context import ToolContext from proompt.base.prompt import BasePrompt, PromptSection from textwrap import dedent # Define functions for tools def search_documents(query: str, max_results: int = 5) -> str: """Search through company documents.""" return f"Found {max_results} documents matching '{query}'" def get_metrics(metric_type: str) -> dict: """Retrieve company metrics by type.""" return {"revenue": 1000000, "users": 50000, "growth": 0.15} def calculate_percentage(numerator: float, denominator: float) -> float: """Calculate percentage from two numbers.""" return (numerator / denominator) * 100 if denominator else 0.0 # Create pydantic-ai Tool objects search_tool = Tool(search_documents, takes_ctx=False) metrics_tool = Tool(get_metrics, takes_ctx=False) calc_tool = Tool(calculate_percentage, takes_ctx=False) # Create a FunctionToolset with multiple tools analysis_toolset = FunctionToolset(tools=[search_tool, metrics_tool]) # Add tools using decorator @analysis_toolset.tool def summarize_data(ctx: RunContext, data: str) -> str: """Summarize the provided data.""" return f"Summary of {len(data)} characters" # Traditional proompt ToolContext def format_report(data: dict) -> str: """Format data into a readable report.""" return "\n".join(f"{k}: {v}" for k, v in data.items()) proompt_tool = ToolContext(format_report) # Create section mixing all tool types class AnalysisSection(PromptSection): def formatter(self) -> str: tools_list = "\n".join( f"- {tool.tool_name}: {tool.tool_description}" for tool in self.tools ) return f"## ANALYSIS TOOLS\n\n{tools_list}" def render(self) -> str: return self.formatter() ``` -------------------------------- ### List Tool Names (Python) Source: https://context7.com/burhan-q/proompt/llms.txt This snippet iterates through the tools within an `AnalysisSection` and prints their names, demonstrating how to access and display the available tools. ```python print("Tool names:", [t.tool_name for t in section.tools]) # Output: ['format_report', 'calculate_percentage', 'search_documents', 'get_metrics', 'summarize_data'] ``` -------------------------------- ### DataAnalysisSection: Create and Render a Data Analysis Prompt Section (Python) Source: https://context7.com/burhan-q/proompt/llms.txt Demonstrates how to create a custom PromptSection subclass for data analysis. It includes implementing formatter and render methods, integrating data providers and tools, and rendering the final prompt section. ```python from proompt.base.prompt import PromptSection from proompt.base.context import Context, ToolContext from proompt.base.provider import BaseProvider from proompt.data import CsvDataProvider from textwrap import dedent, indent class DataAnalysisSection(PromptSection): """Section for data analysis with providers and tools.""" def formatter(self, instruction: str = "Analyze the data") -> str: # Collect data from all providers data_parts = [] for provider in self.providers: data_parts.append(f"### {provider.name}\n{provider.run()}") data = "\n\n".join(data_parts) # Format tool descriptions tools_desc = "\n".join( f"- {tool.tool_name}: {tool.tool_description}" for tool in self.tools ) return dedent(f""" ## DATA ANALYSIS {instruction} ### Available Data: {indent(data, " ")} ### Analysis Tools: {indent(tools_desc, " ")} Provide insights based on the data. """).strip() def render(self) -> str: return self.formatter() # Define analysis function def calculate_trend(current: float, previous: float) -> dict: """Calculate trend between two values.""" rate = (current - previous) / previous if previous else 0 return {"rate": rate, "direction": "up" if rate > 0 else "down"} # Create section with context, tools, and providers section = DataAnalysisSection( context=None, # Optional Context object tools=[ToolContext(calculate_trend)], CsvDataProvider("metrics.csv"), CsvDataProvider("sales.csv") ) # Render the section print(section.render()) # Or use str() prompt_text = str(section) # Add more providers dynamically section.add_providers(CsvDataProvider("inventory.csv")) # Add more tools dynamically section.add_tools(calculate_trend) # Accepts callable section.add_tools(ToolContext(calculate_trend)) # Or ToolContext ``` -------------------------------- ### Read Text File with FileDataProvider Source: https://github.com/burhan-q/proompt/blob/main/README.md Reads the raw string content from a specified text file. This is a foundational data provider for accessing file-based data. ```python from proompt.data import FileDataProvider provider = FileDataProvider("config.yaml") content = provider.run() # raw string content ``` -------------------------------- ### ToolContext - Document Functions for LLMs Source: https://context7.com/burhan-q/proompt/llms.txt The ToolContext class wraps Python functions and generates documentation that LLMs can understand. It automatically extracts function signatures, docstrings, and type annotations, supporting integration with pydantic-ai Tool and FunctionToolset objects. ```python from proompt.base.context import ToolContext from pydantic_ai import Tool, FunctionToolset # Define a function with type hints and docstring def calculate_tax(income: float, rate: float = 0.25) -> float: """Calculate tax owed on income based on the given rate.""" return income * rate def analyze_growth(current: float, previous: float) -> dict: """Analyze growth rate between two periods.""" if previous == 0: return {"rate": 0, "trend": "new"} rate = (current - previous) / previous return {"rate": rate, "trend": "up" if rate > 0 else "down"} # Create ToolContext from function tax_tool = ToolContext(calculate_tax) print(tax_tool.render()) # Custom usage description growth_tool = ToolContext( analyze_growth, tool_use="Use to compare metrics between quarters" ) # Create from pydantic-ai Tool pydantic_tool = Tool(calculate_tax, takes_ctx=False) tool_ctx = ToolContext.from_pydantic_tool(pydantic_tool) # Normalize any tool type to list of ToolContext # Accepts: ToolContext, Callable, Tool, FunctionToolset tools = ToolContext.normalize(calculate_tax) # Returns [ToolContext] tools = ToolContext.normalize(pydantic_tool) # Returns [ToolContext] # FunctionToolset extracts all contained tools toolset = FunctionToolset(tools=[ Tool(calculate_tax, takes_ctx=False), Tool(analyze_growth, takes_ctx=False) ]) tools = ToolContext.normalize(toolset) # Returns [ToolContext, ToolContext] ``` -------------------------------- ### Read Text File Contents with FileDataProvider in Python Source: https://context7.com/burhan-q/proompt/llms.txt Utilizes the FileDataProvider to read the content of a text file. This is useful for including configuration files or templates directly into prompts. The content is returned as a string. ```python from proompt.data import FileDataProvider from pathlib import Path # Initialize with file path (string or Path) provider = FileDataProvider("config.yaml") # Get file contents content = provider.run() print(content) # Output: Raw file contents as string # Check provider metadata print(provider.name) # Output: FileDataProvider for config.yaml print(provider.provider_ctx) # Output: Used to retrieve data from the file config.yaml. # Use in a prompt prompt = f""" Analyze the following configuration: {provider.run()} Provide recommendations for optimization. """ ``` -------------------------------- ### Add Tools Dynamically (Python) Source: https://context7.com/burhan-q/proompt/llms.txt This snippet shows how to dynamically add new tools to an existing `AnalysisSection` using the `add_tools` method. This allows for flexible configuration and extension of the toolset. ```python section.add_tools(search_tool, metrics_tool) section.add_tools(analysis_toolset) ``` -------------------------------- ### Context - Abstract Base Class for Contexts Source: https://context7.com/burhan-q/proompt/llms.txt The Context abstract base class defines the contract for prompt contexts that provide runtime information. Contexts encapsulate dynamic information that should be available when rendering prompts, such as business details or user preferences. ```python from proompt.base.context import Context from datetime import datetime from textwrap import dedent class BusinessContext(Context): """Context for quarterly business review.""" def __init__(self, company_name: str, quarter: str, year: int): self.company_name = company_name self.quarter = quarter self.year = year self.review_date = datetime.now().strftime("%Y-%m-%d") def render(self) -> str: return dedent(f""" Business Review Context: Company: {self.company_name} Review Period: {self.quarter} {self.year} Analysis Date: {self.review_date} This analysis combines operational metrics and technical performance data to provide comprehensive insights for strategic decision making. """).strip() # Usage context = BusinessContext("TechCorp", "Q3", 2024) print(context.render()) # Or use str() print(str(context)) ``` -------------------------------- ### Run Async Operation Source: https://context7.com/burhan-q/proompt/llms.txt Executes an asynchronous operation using asyncio.run. This is typically used to run the main asynchronous function of a provider. ```python import asyncio result = asyncio.run(provider.arun()) ``` -------------------------------- ### Define Custom API Data Provider in Python Source: https://context7.com/burhan-q/proompt/llms.txt Implements a custom data provider for fetching data from a REST API. It inherits from BaseProvider and defines properties for name and context, along with synchronous and asynchronous run methods to fetch and return JSON data. ```python from abc import ABC, abstractmethod from typing import Generic, TypeVar from proompt.base.provider import BaseProvider DataType = TypeVar("DataType") class ApiProvider(BaseProvider[dict]): """Custom provider that fetches data from a REST API.""" def __init__(self, url: str, api_key: str): self.url = url self.api_key = api_key @property def name(self) -> str: return f"API Provider for {self.url}" @property def provider_ctx(self) -> str: return f"Fetches data from REST API at {self.url}" def run(self, endpoint: str = "data") -> dict: import requests response = requests.get( f"{self.url}/{endpoint}", headers={"Authorization": f"Bearer {self.api_key}"} ) return response.json() async def arun(self, endpoint: str = "data") -> dict: # Optional async implementation return self.run(endpoint) # Usage api = ApiProvider("https://api.example.com", "your-api-key") data = api.run("users") # Returns dict from API # Or use as callable data = api("users") # Same as api.run("users") ``` -------------------------------- ### Convert CSV to Markdown Table with CsvDataProvider Source: https://github.com/burhan-q/proompt/blob/main/README.md Reads data from a CSV file and automatically converts it into a formatted markdown table. This is useful for presenting tabular data in a human-readable format for LLMs. ```python from proompt.data import CsvDataProvider # Automatically converts CSV to markdown tables provider = CsvDataProvider("data.csv") table = provider.run() # Returns formatted markdown table ``` -------------------------------- ### Convert Dictionaries to Markdown Table with TableData Source: https://github.com/burhan-q/proompt/blob/main/README.md Converts a list of dictionaries into a markdown table format using the `TableData` utility. This is ideal for preparing structured data for LLM consumption. ```python from proompt.data import TableData # From dictionaries data = [ {"name": "Alice", "role": "Engineer", "salary": 85000}, {"name": "Bob", "role": "Designer", "salary": 75000} ] table = TableData.from_dicts(data) markdown = table.to_md() print(markdown) # | name | role | salary | # | ----- | -------- | ------ | # | Alice | Engineer | 85000 | # | Bob | Designer | 75000 | ``` -------------------------------- ### TableData - Convert Data to Markdown Tables Source: https://context7.com/burhan-q/proompt/llms.txt The TableData utility class converts various data formats (dictionaries, CSV strings, row data) into markdown table format. It's the underlying mechanism used by data providers and offers multiple ways to initialize table data. ```python from proompt.data import TableData, to_markdown_table # From list of dictionaries data = [ {"name": "Alice", "role": "Engineer", "salary": 85000}, {"name": "Bob", "role": "Designer", "salary": 75000}, {"name": "Carol", "role": "Manager", "salary": 95000} ] table = TableData.from_dicts(data) print(table.to_md()) # From headers and rows directly headers = ["Product", "Q1", "Q2", "Q3"] rows = [ ["Widget", 1000, 1200, 1500], ["Gadget", 800, 950, 1100] ] table = TableData.from_rows(headers, rows) print(table.to_md()) # From CSV string csv_text = """name,age,city John,30,NYC Jane,25,LA""" table = TableData.from_csv_str(csv_text) print(table.to_md()) # Low-level function for direct conversion markdown = to_markdown_table( headers=["A", "B", "C"], rows=[[1, 2, 3], [4, 5, 6]] ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.