A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
audit: fix langchain_data_agent - replace em dashes in README, add missing docstrings
Tiioluwani9ec5d74f06f9
diff --git a/ai_agents/langchain_data_agent/README.md b/ai_agents/langchain_data_agent/README.mdindex 77a1ae6..62b2c2b 100644--- a/ai_agents/langchain_data_agent/README.md+++ b/ai_agents/langchain_data_agent/README.md@@ -25,12 +25,12 @@ This project is useful for data analysts, engineers, and learners who want to ex**Frameworks & Libraries:**-- LangGraph — agent workflow orchestration-- LangChain — SQL toolkit, messages, and LLM integration-- langchain-openai — ChatOpenAI client for the Orq.ai router-- OpenAI SDK — API client (routed through Orq.ai)-- SQLAlchemy — database engine for SQLite-- Pandas — result parsing and chart data prep+- LangGraph: agent workflow orchestration+- LangChain: SQL toolkit, messages, and LLM integration+- langchain-openai: ChatOpenAI client for the Orq.ai router+- OpenAI SDK: API client (routed through Orq.ai)+- SQLAlchemy: database engine for SQLite+- Pandas: result parsing and chart data prep**Additional Tools:**@@ -131,12 +131,12 @@ langchain-data-agent/## How It Works-1. **User input** — You type a question in the Streamlit chat.-2. **List tables** — The agent loads available Chinook tables (Artist, Album, Track, Invoice, etc.).-3. **Get schema** — The LLM calls `sql_db_schema` for tables relevant to your question.-4. **Generate SQL** — The model writes a SQLite `SELECT` query from the schema and question.-5. **Check SQL** — A dedicated step reviews the query for common SQL mistakes.-6. **Execute** — `ReadOnlyQuerySQLDatabaseTool` validates and runs the query; results include column names.-7. **Respond** — The agent returns a natural-language answer; the UI shows the SQL, a data table, and a Plotly chart when appropriate.+1. **User input:** You type a question in the Streamlit chat.+2. **List tables:** The agent loads available Chinook tables (Artist, Album, Track, Invoice, etc.).+3. **Get schema:** The LLM calls `sql_db_schema` for tables relevant to your question.+4. **Generate SQL:** The model writes a SQLite `SELECT` query from the schema and question.+5. **Check SQL:** A dedicated step reviews the query for common SQL mistakes.+6. **Execute:** `ReadOnlyQuerySQLDatabaseTool` validates and runs the query; results include column names.+7. **Respond:** The agent returns a natural-language answer; the UI shows the SQL, a data table, and a Plotly chart when appropriate.The LLM (`kimi-k2.6`) is called through the [Orq.ai](https://orq.ai) router (`https://api.orq.ai/v3/router`). Message history is flattened for compatibility with the model’s tool-calling requirements, while the graph still runs the full LangGraph SQL workflow under the hood.\ No newline at end of filediff --git a/ai_agents/langchain_data_agent/agent.py b/ai_agents/langchain_data_agent/agent.pyindex 3b22f75..607ab12 100644--- a/ai_agents/langchain_data_agent/agent.py+++ b/ai_agents/langchain_data_agent/agent.py@@ -60,6 +60,7 @@ def _llm_context(state: MessagesState) -> list[HumanMessage]:def _validate_read_only(query: str) -> str:+ """Raise ValueError if the query contains any non-SELECT or mutating SQL statement."""cleaned = query.strip().rstrip(";")if FORBIDDEN_SQL.search(cleaned):raise ValueError("Only read-only SELECT queries are allowed.")@@ -77,6 +78,7 @@ class ReadOnlyQuerySQLDatabaseTool(QuerySQLDatabaseTool):def _build_model() -> ChatOpenAI:+ """Build and return the ChatOpenAI client pointed at the Orq.ai router."""api_key = os.getenv("ORQ_API_KEY")if not api_key:raise ValueError("ORQ_API_KEY is not set. Copy .env.example to .env and add your key.")@@ -92,6 +94,7 @@ def _build_model() -> ChatOpenAI:def _build_tools(db: SQLDatabase, model: ChatOpenAI) -> list:+ """Build the LangChain SQL toolkit and replace the default query tool with the read-only version."""toolkit = SQLDatabaseToolkit(db=db, llm=model)tools = toolkit.get_tools()for i, tool in enumerate(tools):@@ -101,6 +104,7 @@ def _build_tools(db: SQLDatabase, model: ChatOpenAI) -> list:def _create_agent():+ """Build and compile the full LangGraph SQL agent workflow against the Chinook database."""if not DB_PATH.exists():raise FileNotFoundError(f"Database not found at {DB_PATH}")@@ -239,6 +243,7 @@ _agent = Nonedef get_agent(*, reload: bool = False):+ """Return the cached agent instance, building it on first call or when reload is True."""global _agentif _agent is None or reload:_agent = _create_agent()@@ -246,6 +251,7 @@ def get_agent(*, reload: bool = False):def _to_langchain_messages(history: list[dict]) -> list[BaseMessage]:+ """Convert a list of role/content dicts from session history into LangChain message objects."""messages: list[BaseMessage] = []for item in history:role = item.get("role", "user")@@ -258,6 +264,7 @@ def _to_langchain_messages(history: list[dict]) -> list[BaseMessage]:def _extract_sql_metadata(messages: list[BaseMessage]) -> tuple[str | None, str | None]:+ """Extract the last SQL query and its raw result string from the agent message history."""last_sql: str | None = Nonelast_results: str | None = Nonefor message in messages:@@ -271,6 +278,7 @@ def _extract_sql_metadata(messages: list[BaseMessage]) -> tuple[str | None, strdef extract_answer(messages: list[BaseMessage]) -> str:+ """Return the last plain-text AI response from the message list, skipping tool calls and table listings."""for message in reversed(messages):if isinstance(message, AIMessage) and message.content and not message.tool_calls:text = message.contentdiff --git a/ai_agents/langchain_data_agent/app.py b/ai_agents/langchain_data_agent/app.pyindex 4c76796..7e4cc1b 100644--- a/ai_agents/langchain_data_agent/app.py+++ b/ai_agents/langchain_data_agent/app.py@@ -88,6 +88,7 @@ def _column_names_from_sql(sql: str | None, num_cols: int) -> list[str]:def _parse_results(raw: str | None, sql: str | None = None) -> pd.DataFrame | None:+ """Parse raw SQL query results (JSON list or pipe-delimited string) into a DataFrame."""if not raw or not raw.strip():return None@@ -130,6 +131,7 @@ def _parse_results(raw: str | None, sql: str | None = None) -> pd.DataFrame | Nodef _build_chart(df: pd.DataFrame):+ """Return a Plotly bar or pie chart for the DataFrame, or None if the data is not plottable."""if df.empty or len(df) < 2:return None