pixie-examples 0.1.1.dev3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
examples/sql_utils.py ADDED
@@ -0,0 +1,241 @@
1
+ """
2
+ Lightweight SQL Database Utilities
3
+
4
+ Drop-in replacements for langchain_community.utilities.SQLDatabase and
5
+ langchain_community.agent_toolkits.SQLDatabaseToolkit without the heavy dependencies.
6
+
7
+ Built on top of SQLAlchemy for database interaction.
8
+ """
9
+
10
+ from typing import Any, Optional
11
+ from sqlalchemy import create_engine, inspect, text, MetaData
12
+ from sqlalchemy.engine import Engine
13
+
14
+
15
+ class SQLDatabase:
16
+ """Lightweight SQLAlchemy database wrapper."""
17
+
18
+ def __init__(
19
+ self,
20
+ engine: Engine,
21
+ schema: Optional[str] = None,
22
+ include_tables: Optional[list[str]] = None,
23
+ ignore_tables: Optional[list[str]] = None,
24
+ sample_rows_in_table_info: int = 3,
25
+ ):
26
+ """Initialize SQLDatabase wrapper.
27
+
28
+ Args:
29
+ engine: SQLAlchemy engine
30
+ schema: Optional schema name
31
+ include_tables: Optional list of tables to include
32
+ ignore_tables: Optional list of tables to ignore
33
+ sample_rows_in_table_info: Number of sample rows to include in table info
34
+ """
35
+ self._engine = engine
36
+ self._schema = schema
37
+ self._include_tables = include_tables
38
+ self._ignore_tables = ignore_tables or []
39
+ self._sample_rows_in_table_info = sample_rows_in_table_info
40
+ self._metadata = MetaData()
41
+
42
+ @classmethod
43
+ def from_uri(
44
+ cls,
45
+ database_uri: str,
46
+ engine_args: Optional[dict] = None,
47
+ **kwargs: Any,
48
+ ) -> "SQLDatabase":
49
+ """Create SQLDatabase from a database URI.
50
+
51
+ Args:
52
+ database_uri: Database connection URI (e.g., 'sqlite:///path/to/db.db')
53
+ engine_args: Optional arguments to pass to create_engine
54
+ **kwargs: Additional arguments for SQLDatabase initialization
55
+
56
+ Returns:
57
+ SQLDatabase instance
58
+ """
59
+ engine_args = engine_args or {}
60
+ engine = create_engine(database_uri, **engine_args)
61
+ return cls(engine, **kwargs)
62
+
63
+ @property
64
+ def dialect(self) -> str:
65
+ """Get database dialect name."""
66
+ return self._engine.dialect.name
67
+
68
+ def get_usable_table_names(self) -> list[str]:
69
+ """Get list of usable table names.
70
+
71
+ Returns:
72
+ List of table names
73
+ """
74
+ inspector = inspect(self._engine)
75
+ all_tables = inspector.get_table_names(schema=self._schema)
76
+
77
+ # Filter tables
78
+ if self._include_tables:
79
+ tables = [t for t in all_tables if t in self._include_tables]
80
+ else:
81
+ tables = [t for t in all_tables if t not in self._ignore_tables]
82
+
83
+ return tables
84
+
85
+ def get_table_info(self, table_names: Optional[list[str]] = None) -> str:
86
+ """Get information about specified tables including schema and sample rows.
87
+
88
+ Args:
89
+ table_names: Optional list of table names. If None, uses all usable tables.
90
+
91
+ Returns:
92
+ Formatted string with table information
93
+ """
94
+ if table_names is None:
95
+ table_names = self.get_usable_table_names()
96
+
97
+ inspector = inspect(self._engine)
98
+ table_info = []
99
+
100
+ for table_name in table_names:
101
+ # Get columns
102
+ columns = inspector.get_columns(table_name, schema=self._schema)
103
+
104
+ # Build CREATE TABLE statement
105
+ create_table = f"CREATE TABLE {table_name} (\n"
106
+ column_defs = []
107
+ for col in columns:
108
+ col_type = str(col["type"])
109
+ nullable = "" if col.get("nullable", True) else " NOT NULL"
110
+ column_defs.append(f" {col['name']} {col_type}{nullable}")
111
+ create_table += ",\n".join(column_defs)
112
+ create_table += "\n)"
113
+
114
+ table_info.append(create_table)
115
+
116
+ # Get sample rows
117
+ if self._sample_rows_in_table_info > 0:
118
+ try:
119
+ query = text(
120
+ f"SELECT * FROM {table_name} LIMIT {self._sample_rows_in_table_info}"
121
+ )
122
+ with self._engine.connect() as conn:
123
+ result = conn.execute(query)
124
+ rows = result.fetchall()
125
+ if rows:
126
+ table_info.append(
127
+ f"\n{self._sample_rows_in_table_info} rows from {table_name} table:"
128
+ )
129
+ for row in rows:
130
+ table_info.append(str(row))
131
+ except Exception as e:
132
+ table_info.append(f"\nError fetching sample rows: {e}")
133
+
134
+ table_info.append("") # Empty line between tables
135
+
136
+ return "\n".join(table_info)
137
+
138
+ def run(self, command: str, fetch: str = "all") -> str:
139
+ """Execute a SQL command and return results.
140
+
141
+ Args:
142
+ command: SQL command to execute
143
+ fetch: How to fetch results ('all', 'one', or 'cursor')
144
+
145
+ Returns:
146
+ Query results as a string
147
+ """
148
+ with self._engine.connect() as conn:
149
+ result = conn.execute(text(command))
150
+
151
+ if fetch == "all":
152
+ rows = result.fetchall()
153
+ return str(rows)
154
+ elif fetch == "one":
155
+ row = result.fetchone()
156
+ return str(row)
157
+ else:
158
+ return str(list(result))
159
+
160
+
161
+ class SQLDatabaseToolkit:
162
+ """Toolkit for creating LangChain tools to interact with SQL databases."""
163
+
164
+ def __init__(self, db: SQLDatabase, llm: Any):
165
+ """Initialize SQL Database Toolkit.
166
+
167
+ Args:
168
+ db: SQLDatabase instance
169
+ llm: Language model (not used in tool execution, but kept for compatibility)
170
+ """
171
+ self._db = db
172
+ self._llm = llm
173
+
174
+ def get_tools(self) -> list:
175
+ """Get list of tools for SQL database interaction.
176
+
177
+ Returns:
178
+ List of LangChain Tool objects
179
+ """
180
+ from langchain_core.tools import StructuredTool
181
+
182
+ tools = [
183
+ StructuredTool.from_function(
184
+ name="sql_db_list_tables",
185
+ description="List all available tables in the database. "
186
+ "Use this to see what tables you can query. "
187
+ "Input should be an empty string.",
188
+ func=self._list_tables,
189
+ ),
190
+ StructuredTool.from_function(
191
+ name="sql_db_schema",
192
+ description="Get the schema and sample rows for specified tables. "
193
+ "Input should be a comma-separated list of table names. "
194
+ "Example input: 'table1, table2, table3'",
195
+ func=self._get_schema,
196
+ ),
197
+ StructuredTool.from_function(
198
+ name="sql_db_query",
199
+ description="Execute a SQL query against the database. "
200
+ "Input should be a valid SQL query. "
201
+ "Returns the query results. "
202
+ "If the query is not correct, an error message will be returned. "
203
+ "If an error is returned, rewrite the query and try again.",
204
+ func=self._query,
205
+ ),
206
+ ]
207
+
208
+ return tools
209
+
210
+ def _list_tables(self, _: str = "") -> str:
211
+ """List all tables in the database."""
212
+ tables = self._db.get_usable_table_names()
213
+ return ", ".join(tables)
214
+
215
+ def _get_schema(self, table_names: str) -> str:
216
+ """Get schema for specified tables.
217
+
218
+ Args:
219
+ table_names: Comma-separated list of table names
220
+
221
+ Returns:
222
+ Formatted schema information
223
+ """
224
+ # Parse table names
225
+ tables = [t.strip() for t in table_names.split(",")]
226
+ return self._db.get_table_info(tables)
227
+
228
+ def _query(self, query: str) -> str:
229
+ """Execute SQL query.
230
+
231
+ Args:
232
+ query: SQL query to execute
233
+
234
+ Returns:
235
+ Query results or error message
236
+ """
237
+ try:
238
+ result = self._db.run(query)
239
+ return result
240
+ except Exception as e:
241
+ return f"Error executing query: {str(e)}"
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: pixie-examples
3
+ Version: 0.1.1.dev3
4
+ Summary: examples for using Pixie
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Author: Yiou Li
8
+ Author-email: yol@gopixie.ai
9
+ Requires-Python: >=3.11,<3.14
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Dist: beautifulsoup4 (>=4.14.3,<5.0.0)
16
+ Requires-Dist: langchain (>=1.2.3,<2.0.0)
17
+ Requires-Dist: langchain-openai (>=1.1.7,<2.0.0)
18
+ Requires-Dist: langchain-text-splitters (>=1.1.0,<2.0.0)
19
+ Requires-Dist: langgraph (>=1.0.5,<2.0.0)
20
+ Requires-Dist: lxml (>=6.0.2,<7.0.0)
21
+ Requires-Dist: numpy (>=2.4.1,<3.0.0)
22
+ Requires-Dist: openai-agents (>=0.6.5,<0.7.0)
23
+ Requires-Dist: openinference-instrumentation-crewai (>=0.1.17,<0.2.0)
24
+ Requires-Dist: openinference-instrumentation-dspy (>=0.1.33,<0.2.0)
25
+ Requires-Dist: openinference-instrumentation-google-adk (>=0.1.8,<0.2.0)
26
+ Requires-Dist: openinference-instrumentation-openai-agents (>=1.4.0,<2.0.0)
27
+ Requires-Dist: pixie-sdk (>=0.1.1.dev8,<0.2.0)
28
+ Requires-Dist: pydantic (>=2.7.4,<3.0.0)
29
+ Requires-Dist: pydantic-ai-slim (>=1.39.0,<2.0.0)
30
+ Requires-Dist: pymarkdownlnt (>=0.9.34,<0.10.0)
31
+ Requires-Dist: requests (>=2.32.5,<3.0.0)
32
+ Requires-Dist: sqlalchemy (>=2.0.45,<3.0.0)
33
+ Description-Content-Type: text/markdown
34
+
35
+ # Pixie Examples
36
+
37
+ [![MIT License](https://img.shields.io/badge/License-MIT-red.svg?style=flat-square)](https://opensource.org/licenses/MIT)
38
+ [![Python Version](https://img.shields.io/badge/python-3.11%2B-blue?style=flat-square)](https://www.python.org/downloads/)
39
+ [![Discord](https://img.shields.io/discord/1459772566528069715?style=flat-square&logo=Discord&logoColor=white&label=Discord&color=%23434EE4)](https://discord.gg/YMNYu6Z3)
40
+
41
+ This repository contains a collection of example applications integrated with [**Pixie SDK**](https://github.com/yiouli/pixie-sdk-py) for interactive debugging.
42
+
43
+ ## Get Started
44
+
45
+ > You can play with the demo site [here](https://gopixie.ai/?url=https://demo.yiouli.us/graphql) withou any setup.
46
+
47
+ ### 1. Setup
48
+
49
+ Clone this repository:
50
+
51
+ Install `pixie-examples` python package:
52
+
53
+ ```bash
54
+ pip install pixie-examples
55
+ ```
56
+
57
+ Create a `.env` file with your API keys:
58
+
59
+ ```ini
60
+ # .env
61
+ OPENAI_API_KEY=...
62
+ # Add other API keys as needed for specific examples
63
+ ```
64
+
65
+ Start the Pixie server:
66
+
67
+ ```bash
68
+ pixie
69
+ ```
70
+
71
+ ### 2. Debug with Web UI
72
+
73
+ Visit [gopixie.ai](https://gopixie.ai) to interact with and debug your applications through the web interface.
74
+
75
+ ## Important Links
76
+
77
+ - [**Pixie SDK**](https://github.com/yiouli/pixie-sdk-py)
78
+ - [**Documentation**](https://yiouli.github.io/pixie-sdk-py/)
79
+ - [**Discord**](https://discord.gg/YMNYu6Z3)
80
+
81
+ ## Examples Catelog
82
+
83
+ ### Quickstart
84
+
85
+ - **Basic Example**: Simple hello world application to get started with Pixie SDK
86
+
87
+ ### Pydantic AI Examples
88
+
89
+ - **Bank Support**: Multi-turn chatbot for banking customer support
90
+ - **Flight Booking**: Multi-agent system for flight booking
91
+ - **Question Graph**: Graph-based question answering system
92
+ - **SQL Generation**: Multi-step workflow for generating SQL queries
93
+ - **Structured Output**: Examples of structured data handling
94
+
95
+ ### OpenAI Agents SDK Examples
96
+
97
+ - **Customer Service**: Multi-agent customer service system
98
+ - **Financial Research Agent**: Multi-step financial research workflow
99
+ - **LLM-as-a-Judge**: Evaluation and judging patterns
100
+ - **Routing**: Agent routing and handoffs
101
+
102
+ ### LangChain Examples
103
+
104
+ - **Basic Agent**: Simple LangChain agent integration
105
+ - **Customer Support**: Customer support chatbot
106
+ - **Personal Assistant**: Multi-agent personal assistant
107
+ - **SQL Agent**: SQL query generation with LangChain
108
+
109
+ ### LangGraph Examples
110
+
111
+ - **RAG System**: Retrieval-augmented generation with LangGraph
112
+ - **SQL Agent**: SQL agent built with LangGraph state machines
113
+
@@ -0,0 +1,33 @@
1
+ examples/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ examples/langchain/README.md,sha256=xU8v1xtLYS9TtgLpJAdeu2zrRYK5w19hH_yvg_OsWxY,1179
3
+ examples/langchain/__init__.py,sha256=mwSd_kA79bSHBMmBJL4NawrAow38QcOly4DUtieID3Q,35
4
+ examples/langchain/basic_agent.py,sha256=TjsrMMoHJMQcV1WXvxVwWS0iiPhHglg_w510fgHdRwA,2771
5
+ examples/langchain/customer_support.py,sha256=6r1lfUXVf1uiyle2FmnD3-FLh_KOwX4Xa1q3CJ3VXCA,7845
6
+ examples/langchain/personal_assistant.py,sha256=5jIMzHFeGbo1H1RAagtd2b7gPfF_2dbq0oS9tt7m2Wk,5635
7
+ examples/langchain/sql_agent.py,sha256=M5s9cQ0G3AbSm89s73WQ0Qy6CgC2TZyiAYlv2US6slY,5692
8
+ examples/langgraph/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ examples/langgraph/langgraph_rag.py,sha256=H17pONi4MV_LX-4BxahrkGKDZwaWvL-1DhcTXf6DaDI,8296
10
+ examples/langgraph/langgraph_sql_agent.py,sha256=XfsM_dZlqFzs5Qs4_Urc46srlxFrn1l9TtwsAKMt6Zc,8086
11
+ examples/openai_agents_sdk/README.md,sha256=Q0iszfCK1lRzHoWCI9L5-f7LGLU-3OWSWXUsiBFBp4o,7088
12
+ examples/openai_agents_sdk/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ examples/openai_agents_sdk/customer_service.py,sha256=B4TOnUN7PbevQuLCpGKjct4nfqJmk13KiXN9COVf4wM,8420
14
+ examples/openai_agents_sdk/financial_research_agent.py,sha256=crx5TTmCBpxqPJTOkb2ONtr0H4C154U1C3rdjGULLNQ,10585
15
+ examples/openai_agents_sdk/llm_as_a_judge.py,sha256=vXO4ds79VIqNaITByGpBCeiOYR6jVowO8cHAKxMolWo,3440
16
+ examples/openai_agents_sdk/routing.py,sha256=0SRLmT1Pywjbk4YgqT23n9AHSokbZHcIzdYe1V5IleQ,5268
17
+ examples/pydantic_ai/.env.example,sha256=f-rbvXri1Rfy7Ya1tI4a4cPVWM1YvYHfR8CQEnnYdcg,944
18
+ examples/pydantic_ai/README.md,sha256=Tz80pjaACzAP9WxYVwiWY7Gq03eJwLGsHMGtPj3OOWQ,6677
19
+ examples/pydantic_ai/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ examples/pydantic_ai/bank_support.py,sha256=z46pPLkpswljmRuI1rge5Y5NEpgMQY-yNcJU9HeZgiA,4199
21
+ examples/pydantic_ai/flight_booking.py,sha256=cqZtuxME-Us0l9NFkd6Uz_gajeWtOTDkferEBBkNgMU,8133
22
+ examples/pydantic_ai/question_graph.py,sha256=5BiiXDwnyUERmSK1LnXlpQNkItXDJEtXRQ2S0B3rmd0,4793
23
+ examples/pydantic_ai/sql_gen.py,sha256=UK7Sm9Kpfex_OBwrQl9qH1VZUDjmXvzxqNn_EDPMIgA,4957
24
+ examples/pydantic_ai/structured_output.py,sha256=505L_P_d3lU2GxB8yij7M3A-iMXMCxxrzl_B7Jq3ttE,1386
25
+ examples/quickstart/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
+ examples/quickstart/chatbot.py,sha256=UuN34P1QdgsF_InK2rNTuZ-yzIeJ9WWOskOjPHAWCr0,644
27
+ examples/quickstart/sleepy_poet.py,sha256=XaP8FWW7rVsV16e3sTrY-9amkLUhL93AK9s5_lYIHSE,2914
28
+ examples/quickstart/weather_agent.py,sha256=bRk7kcbPfJ18ywlqVqiwLbi9_z_LtESzaZr2bdLhN1M,3238
29
+ examples/sql_utils.py,sha256=gIR_ViLzoIKTgY7RZnwCBftTscpFLSjRXewNx7TthoI,8125
30
+ pixie_examples-0.1.1.dev3.dist-info/METADATA,sha256=gMYjUNMxLQLGSagE2VEEUPEJjruW3Y63Pwwcpb3kGc0,3884
31
+ pixie_examples-0.1.1.dev3.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
32
+ pixie_examples-0.1.1.dev3.dist-info/licenses/LICENSE,sha256=Qb3t92_AewWub67xNn9upFjh7PrOFF_45wqvHGklA1M,1074
33
+ pixie_examples-0.1.1.dev3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.2.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Finto Technologies
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.