Developer-friendly & type-safe Python SDK specifically catered to leverage textql API.
TextQL API: TextQL public API. Generated from protobuf service definitions; internal endpoints are excluded via google.api.visibility / file_visibility.
Note
Python version upgrade policy
Once a Python version reaches its official end of life date, a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.
The SDK can be installed with uv, pip, or poetry package managers.
uv is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities.
uv add textql-sdkPIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install textql-sdkPoetry is a modern tool that simplifies dependency management and package publishing by using a single pyproject.toml file to handle project metadata and dependencies.
poetry add textql-sdkYou can use this SDK in a Python shell with uv and the uvx command that comes with it like so:
uvx --from textql-sdk pythonIt's also possible to write a standalone Python script without needing to set up a whole project like so:
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "textql-sdk",
# ]
# ///
from textql_sdk import Textql
sdk = Textql(
# SDK arguments
)
# Rest of script here...Once that is saved to a file, you can run it with uv run script.py where
script.py can be replaced with the actual file name.
Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.
# Synchronous Example
import os
from textql_sdk import Textql
with Textql(
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
res = textql.agents.create()
# Handle response
print(res)The same SDK client can also be used to make asynchronous requests by importing asyncio.
# Asynchronous Example
import asyncio
import os
from textql_sdk import Textql
async def main():
async with Textql(
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
res = await textql.agents.create_async()
# Handle response
print(res)
asyncio.run(main())This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
|---|---|---|---|
api_key |
apiKey | API key | TEXTQL_API_KEY |
To authenticate with the API the api_key parameter must be set when initializing the SDK client instance. For example:
import os
from textql_sdk import Textql
with Textql(
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
res = textql.agents.create()
# Handle response
print(res)Available methods
- create - CreateAgent
- delete - DeleteAgent
- duplicate - DuplicateAgent
- get_agent - GetAgent
- get_db_schema - GetAgentDBSchema
- get_db_table_preview - GetAgentDBTablePreview
- get_run - GetAgentRun
- list_runs - ListAgentRuns
- list - ListAgents
- reset_agent_avatar - ResetAgentAvatar
- trigger_agent - TriggerAgent
- update - UpdateAgent
- upload_agent_avatar - UploadAgentAvatar
- heartbeat - Executes a declared compute function on a pooled sandbox worker; gated, org-scoped, rate-limited.
- create_app - CreateApp
- delete_app - DeleteApp
- duplicate - Duplicates an app the caller can view into a new app they own, named "Copy of ". Copies code/files/data sources/compute functions/ schedule; never carries over the source's data snapshot.
- get - GetApp
- get_db_schema - View analytics: reads the engagement views recorded on app page load.
- get_db_table_preview - Staff-only (superadmin gated in-handler): publishes the embedded component gallery as an app tree and returns its signed viewer URL.
- get_member_state - GetAppMemberState
- get_app_version - Version history: git-backed, one version per save (plus legacy publish-era snapshots); authors can list and restore.
- get_app_view_stats - Per-member notification subscription to an app ("watch this app").
- get_members_with_apps - GetMembersWithApps
- invoke_compute_function - InvokeAppComputeFunction
- list_activity_since - Lists the calling member's favorited library items (apps, dashboards, agents) for the sidebar Pinned section: id, type, name, preview screenshot.
- list_versions - Overwrites the published tree's pinned _runtime/ana-1.js with the platform's current copy so host-driven affordances (comment hit-testing) work on older documents; never touches authored content or data. repinned=false for legacy pre-tree documents.
- list - ListApps
- list_my_member_activity - Favorite/unfavorite a library item (app or dashboard) for the calling member. Per-member, per-org; favorited=false hard-deletes the row. Covers both primitives since the merged library page pins apps and dashboards through one client.
- move_app_to_folder - Moves an app into a library folder (or to root when folder_id is empty).
- presence_heartbeat - Replaces the calling member's entire ordering; capped server-side.
- record_member_activity - Watcher management: app owners/editors and org admins list the app's subscribers and add/remove members (Upsert/Delete with member_id).
- refresh - Re-fetches data sources, rebuilds the document with a fresh snapshot, re-uploads.
- restore_app_version - RestoreAppVersion
- set_member_state - SetAppMemberState
- set_favorite - Keeps the viewed app's compute worker alive; first view spawns and pre-warms it (dashboard viewer-TTL parity).
- update - UpdateApp
- configure_otlp_export - ConfigureOtlpExport
- configure_s3_export - ConfigureS3Export
- delete_otlp_export_config - DeleteOtlpExportConfig
- delete_s3_export_config - DeleteS3ExportConfig
- get_otlp_export_config - GetOtlpExportConfig
- get_s3_export_config - GetS3ExportConfig
- list - ListAuditLogs
- test_otlp_export_connection - TestOtlpExportConnection
- test_s3_export_connection - TestS3ExportConnection
- trigger_otlp_export - TriggerOtlpExport
- trigger_s3_export - TriggerS3Export
- approve_context_prompt_change - ApproveContextPromptChange
- approve_ontology_change - ApproveOntologyChange
- attach_agent - AttachAgentToChat
- attach_app - AttachApp
- attach_dashboard - AttachDashboard
- attach_dataset - RateChatCell appends a row to cell_rating for every click; thumbs-down also upserts a user_thumbs_down thread_warning.
- bookmark - BookmarkChat
- cancel_stream - CancelStream
- check_permissions - CheckChatPermissions
- check_health - CheckHealth
- check_streamlit_health - CheckStreamlitHealth
- create_chat - CreateChat
- delete - DeleteChat
- dismiss_questions - Resolve a halted questions cell. Submit hands the answers to the agent and resumes it; Dismiss hands over only the answered count and does NOT resume (the user's next message becomes the dismissal reason).
- duplicate_chat - DuplicateChat
- get_api_answer - GetAPIChatAnswer
- get_artifact - GetArtifact
- get - GetChat
- get_artifacts_summary - GetChatArtifactsSummary
- get_chat_execution_timing - GetChatExecutionTiming
- get_history - GetChatHistory
- get_all - GetChats
- get_completion_parameters - List distinct chat creators the user can access
- get_completion_parameters_batch - GetCompletionParametersBatch
- get_llm_usage - GetLlmUsage
- get_members_with_chats - GetMembersWithChats
- get_playbook_chats - GetPlaybookChats
- poll_events - PollChatEvents
- query_one_shot - QueryOneShot
- rate_cell - RateChatCell
- reject_context_prompt_change - RejectContextPromptChange
- reject_ontology_change - Resolve a halted ask_approval form cell. Submit runs the form's submission and continues the agent with the outcome; Reject discards it (passive, no run); Dismiss treats it as a change request (no run, next message says what to change). All three set the cell's outcome, like the other approve/deny cells.
- run - RunChat
- send - SendMessage
- submit_context_prompt_change - SubmitContextPromptChange
- submit_questions - SubmitQuestions
- unbookmark - UnbookmarkChat
- update - UpdateChat
- create - CreateConnector
- delete - DeleteConnector
- duplicate_connector - DuplicateConnector
- execute_query - ExecuteQuery
- get - GetConnector
- get_connector_cell_durations - GetConnectorCellDurations
- get_chats - GetConnectorChats
- get_dashboards - GetConnectorDashboards
- get_connector_stats - GetConnectorStats
- get_usage - GetConnectorUsage
- get_connectors - GetConnectors
- get_example_queries - GetExampleQueries
- get_table_preview - GetTablePreview
- list_tables - ListConnectorTables
- list_query_templates - ListQueryTemplates
- test - TestConnector
- update - UpdateConnector
- check_health - CheckDashboardHealth
- create_dashboard - CRUD operations
- create_folder - Folder management
- delete - DeleteDashboard
- delete_folder - DeleteDashboardFolder
- discard_changes - DiscardDashboardChanges
- duplicate - DuplicateDashboard
- get - GetDashboard
- get_version - GetDashboardVersion
- get_dashboard_view_stats - View analytics
- get_members_with_dashboards - Member management
- list_folders - ListDashboardFolders
- list_versions - Version history
- list - ListDashboards
- move_to_folder - MoveDashboardToFolder
- preview_config - Config-managed dashboards: render a
.dashboardstraight from a patch ref before it merges (ADR-0022). Runs as the file's run_as, gated on the previewer being authorized for it; persists nothing. - publish - Publishing workflow
- regenerate_screenshot - Screenshot management
- restore_dashboard_version - RestoreDashboardVersion
- run_scheduled_dashboard - RunScheduledDashboard
- spawn - Dashboard execution
- update_dashboard - UpdateDashboard
- update_dashboard_folder - UpdateDashboardFolder
- update_dashboard_schedule - Scheduling
- create_folder - CreateFolder
- create_power_bi_dataset - CreatePowerBIDataset
- create_tableau_dataset - Create Tableau dataset from views/datasources
- create_upload_presign_url - uploads
- delete - Delete a dataset (soft delete)
- export - export dataset in "raw" format – original if dataset is uploaded, converted format otherwise (defaults to CSV)
- fetch - GetDataset, GetDatasets only return metadata
- get_stats - GetDatasetStats
- get_dataset_values - GetDatasetValues
- get - GetDatasets
- get_by_ids - GetDatasetsByIds
- get_folders - for AR: CreateFolderACL, UpdateFolderACL, DeleteFolderACL
- process_upload_presign_url - ProcessUploadPresignUrl
- update_dataset - Update dataset metadata
- clear_o_auth_token - ClearOAuthToken
- delete - DeleteMCPServer
- get_servers - GetMCPServers
- handle_o_auth_callback - HandleOAuthCallback
- initiate_o_auth_flow - InitiateOAuthFlow
- toggle_server - ToggleMCPServer
- upsert_mcp_servers - UpsertMCPServers
- configure - ConfigureMetricsExport
- delete_config - DeleteMetricsExportConfig
- get_metrics_export_config - GetMetricsExportConfig
- test_connection - TestMetricsExportConnection
- trigger_push - TriggerMetricsPush
- activate_custom_topic - ActivateCustomTopic
- backfill_custom_topic - BackfillCustomTopic
- backfill_thread_warnings - BackfillThreadWarnings
- create_custom_topic - Custom topics
- deactivate_custom_topic - DeactivateCustomTopic
- delete_custom_topic - DeleteCustomTopic
- export_csv - ExportObservabilityCsv
- fix_check_record - FixCheckRecord
- fix_warning - FixWarning
- get_access_method_stats - GetAccessMethodStats
- get_active_people_stats - GetActivePeopleStats
- get_active_people_trend - GetActivePeopleTrend
- get_backfill_preview - GetBackfillPreview
- get_backfill_status - GetBackfillStatus
- get_billing_stats - GetBillingStats
- get_chat_source_stats - GetChatSourceStats
- get_chat_topics - GetChatTopics
- get_check_record_fix - GetCheckRecordFix
- get_custom_topic - GetCustomTopic
- get_custom_topic_people - GetCustomTopicPeople
- get_custom_topic_threads - GetCustomTopicThreads
- get_engagement_spectrum - GetEngagementSpectrum
- get_member_activity - GetMemberActivity
- get_member_signal_trend - GetMemberSignalTrend
- get_observability_stats - GetObservabilityStats
- get_thread_warnings - GetThreadWarnings
- list_custom_topics - ListCustomTopics
- refine_draft - RefineTopicDraft
- set_topic_tag_feedback - SetTopicTagFeedback
- update_custom_topic - UpdateCustomTopic
- add_submodule - AddOntologySubmodule
- approve_patch - ApprovePatch
- configure_remote - ConfigureOntologyRemote
- create_approval_rule - CreateApprovalRule
- create_context_patch_auto_approve_rule - CreateContextPatchAutoApproveRule
- create_directory - CreateOntologyDirectory
- create_file_upload_url - Streams how many folders and files a subtree holds, so the UI can report the size of the whole Ontology rather than only the directories it has lazily listed. Counts rise monotonically across frames; the last frame sets
final. A cache hit emits a singlefinalframe withfrom_cacheset. - delete_approval_rule - DeleteApprovalRule
- delete_context_patch_auto_approve_rule - DeleteContextPatchAutoApproveRule
- delete_directory - DeleteOntologyDirectory
- delete_file - DeleteOntologyFile
- deny_patch - DenyPatch
- exchange_github_code - ExchangeOntologyGithubCode
- finalize_file_upload - FinalizeOntologyFileUpload
- get_codeowner_coverage - GetCodeownerCoverage
- get_config_export_capabilities - GetConfigExportCapabilities
- get_effective_owners - GetEffectiveOntologyOwners
- get_file_usage - GetFileUsage
- get_file_usage_timeline - GetFileUsageTimeline
- get_ana_config - GetOntologyAnaConfig
- get_file - GetOntologyFile
- get_github_o_auth_url - GetOntologyGithubOAuthURL
- get_history_file_diff - GetOntologyHistoryFileDiff
- get_owners - GetOntologyOwners
- get_remote - GetOntologyRemote
- get_size_timeline - GetOntologySizeTimeline
- get_sync_conflicts - GetOntologySyncConflicts
- get_usage_summary - GetOntologyUsageSummary
- get_patch - GetPatch
- get_patch_by_number - GetPatchByNumber
- get_patch_capabilities - PlanConfigMigration reports what the lazy config migration WOULD do to this org's objects, and writes nothing. Admin-only, internal: it exists so a release manager can warn the specific orgs a rollout will affect — notably the objects that will stop running because adoption binds a Runner who can no longer run them.
- get_raw_patch - GetRawPatch
- get_usage_details_for_file - GetUsageDetailsForFile
- list_approval_rules - ListApprovalRules
- list_chats_for_file - ListChatsForFile
- list_context_patch_auto_approve_rules - ListContextPatchAutoApproveRules
- list_golden_files - Deprecated: use SetOntologyOwners with the desired entry set. An empty desired set is not currently supported, so retain this RPC for deletion.
- list_entries - ListOntologyEntries
- list_history - ListOntologyHistory
- list_imports - ListOntologyImports
- list_submodules - ListOntologySubmodules
- list_sync_runs - ListOntologySyncRuns
- list_patch_objects - ListPatchObjects parses the config objects present at a patch's git ref and returns each object's Library path, resolved display name, and granular type (e.g. "playbook", "dashboard/streamlit", "dashboard/dash"). Parse-only: it reuses the snapshot-at-ref + parse steps the preview path performs before spawning — no sandbox spawn, no run_as authorization, no persistence. The frontend uses the dashboard subtype to decide previewability (streamlit/dash).
- list_patch_reviewers - ListPatchReviewers
- list_patches - ListPatches
- list_skills - ListSkills
- plan_merge - PlanOntologyMerge
- preview_pull_from_remote - PreviewOntologyPullFromRemote
- pull_from_remote - PullOntologyFromRemote
- push_to_remote - PushOntologyToRemote
- recover - RecoverOntology
- remove_remote - Lists the skills under the ontology's flat skills/ root that the caller can read (OWNERS-filtered). Returns display metadata only — never instruction bodies — feeding the chat composer's
/autocomplete. Unlisted skills are omitted unless include_unlisted is set. - remove_submodule - RemoveOntologySubmodule
- rename_file - RenameOntologyFile
- request_patch_review - RequestPatchReview
- resolve_sync_conflict - TriggerConfigDriftReconcile forces an immediate config-sync catch-up for the caller's org: if the Ontology repo's live HEAD differs from the last reconciled commit, it enqueues a reconcile (otherwise no-op). The on-demand equivalent of waiting for the periodic drift scan.
- restore_patch - RestorePatch
- revert_patch - RevertPatch
- save_all_objects_as_config - SaveAllObjectsAsConfig
- save_object_as_config - SaveObjectAsConfig
- set_file_golden - Deprecated: use SetOntologyOwners with the complete desired entry set.
- set_owners - SetOntologyOwners
- trigger_config_drift_reconcile - TriggerConfigDriftReconcile
- update_approval_rule - UpdateApprovalRule
- update_context_patch_auto_approve_rule - UpdateContextPatchAutoApproveRule
- update_sync_config - UpdateOntologySyncConfig
- upsert_ana_config - UpsertOntologyAnaConfig
- upsert_file - UpsertOntologyFile
- validate_config - Read-only functional validation of a proposed config: parse + dependency resolution/reachability, no authorization and no persistence. "ok" means functionally valid, not "guaranteed to merge" — the merge gate re-checks authorization at approve time.
- attach_dashboard - AttachDashboard
- attach_dataset - AttachDataset
- cancel_template_execution - Cancel template execution for a specific template header
- create_playbook - CreatePlaybook
- deactivate - DeactivatePlaybook
- delete - DeletePlaybook
- demo_playbook - DemoPlaybook
- deploy - DeployPlaybook
- duplicate - DuplicatePlaybook
- favorite_report - Favorite report management
- get_active_subscribed_count - GetActiveSubscribedPlaybooksCount
- get_chat_reports_summary - Lightweight endpoint for chat report drawer - returns summaries without full blocks
- get_members_with - GetMembersWithPlaybooks
- fetch - GetPlaybook
- get_batch_run - Get a specific batch run
- get_playbook_lineage - GetPlaybookLineage
- get_reports - GetPlaybookReports
- get_playbook_reports_batch - Get reports for multiple template data IDs in a single batch request
- get - GetPlaybooks
- get_playbooks_previews - GetPlaybooksPreviews
- get_report_by_id - Get a single report by ID
- get_reports_with_filters - GetReportsWithFilters
- list_slack_channel_context_playbooks - List all Slack channels context playbook mappings for the organization
- list_all_teams_channel_context_playbooks - ListAllTeamsChannelContextPlaybooks
- list_batch_runs - List batch runs for a playbook
- list_slack_channels_for_context - List Slack channel IDs where the given playbook is set as the context
- list_teams_channels_for_context_playbook - ListTeamsChannelsForContextPlaybook
- mark_report_as_read - Report read tracking
- preview_slack_report - PreviewSlackReport
- remove_dashboard - RemoveDashboard
- remove_dataset - RemoveDataset
- run - RunPlaybook
- set_slack_channel_context_playbook - Set the context playbook for a Slack channel. This associates the given playbook to a Slack channel so that Slack messages in that channel use the playbook's context by default.
- set_teams_channel_context - SetTeamsChannelContextPlaybook
- subscribe - SubscribeToPlaybook
- unset_slack_channel_context_playbook - Unset the context playbook for a Slack channel. This clears any association so that messages in this channel no longer use a specific playbook context.
- unset_teams_channel_context - UnsetTeamsChannelContextPlaybook
- unsubscribe - UnsubscribeFromPlaybook
- update - UpdatePlaybook
- export_report_image - ExportPowerBIReportImage
- generate_embed_token - GeneratePowerBIEmbedToken
- get_dataset_preview - GetPowerBIDatasetPreview
- get_synced_items - GetSyncedPowerBIItems
- list - ListPowerBIDatasets
- list_reports - ListPowerBIReports
- list_workspaces - ListPowerBIWorkspaces
- sync_power_bi_items - SyncPowerBIItems
- test_connection - TestPowerBIConnection
- unsync_items - UnsyncPowerBIItems
- approve_access_request - ApproveAccessRequest
- assign_permission_to_role - AssignPermissionToRole
- assign_role_to_member - AssignRoleToMember
- create_api_key - CreateApiKey
- create_personal_api_key - CreatePersonalApiKey
- create_role - Role management
- create_service_account - CreateServiceAccount
- create_service_account_api_key - CreateServiceAccountApiKey
- delete_role - DeleteRole
- delete_service_account - DeleteServiceAccount
- generate_share_link - GenerateShareLink
- get_current_member_roles_and_permissions - GetCurrentMemberRolesAndPermissions
- get_embed_user_api_key - GetEmbedUserApiKey
- get_member_roles - GetMemberRoles
- get_object_access - GetObjectAccess
- get_role - GetRole
- get_role_permissions - GetRolePermissions
- has_object_access - HasObjectAccess
- list_access_requests - ListAccessRequests
- list_api_keys - ListApiKeys
- list_permissions - Permission management
- list_roles - ListRoles
- list_service_accounts - ListServiceAccounts
- reject_access_request - SCIM group-mapping migration tooling: one-time role<->group conversion, internal only.
- remove_permission_from_role - RemovePermissionFromRole
- remove_role_from_member - Member role assignment
- request_access - RequestAccess
- revoke_api_key - Object sharing and access control
- revoke_object_access - RevokeObjectAccess
- rotate_api_key - RotateApiKey
- set_role_permissions - Bulk add/remove permissions on a role in one call, producing a single audit entry for the whole edit.
- share_object - Describe what a key is allowed to do.
- share_object_with_role - Group management. Internal only.
- update_object_access - UpdateObjectAccess
- update_object_visibility - UpdateObjectVisibility
- update_role - UpdateRole
- who_am_i - Get current member roles and permissions
- create - CreateSandbox
- exec - Exec
- execute_code - ExecuteCode
- get_tool_availability - GetToolAvailability
- load_connector_data - LoadConnectorData
- execute_bash - Runs in the caller's own worker; no connector/source scoping.
- execute_query - ExecuteQuery
- get_sandbox - GetSandbox
- list_sandbox_egress - Outbound HTTP(S) calls a sandbox made (the egress ledger). Durable — reads the recorded table, so it works for stopped sandboxes too.
- list_executions - ListSandboxExecutions
- list_sandbox_files - Live filesystem of a running sandbox. Both are NO-OP (read-only) and only return data while the worker is alive; available=false otherwise.
- list_sandbox_spend - Per-lease compute usage for a sandbox, computed from lease durations × the compute rate. Durable (reads the lease table), so it works for stopped sandboxes. This is usage (ACUs), not the invoiced dollar amount.
- list - ListSandboxes
- read_file - ReadSandboxFile
- restart_sandbox - Restart a stopped/reaped sandbox by re-acquiring a worker for the same sandbox_id, preserving the original owner. Same scoping as StopSandbox (owner, or sandbox:write_private for org-wide).
- stop - StopSandbox
- execute_write - ExecuteWrite
- poll_ask - PollAsk
- put_asset - PutAsset
- send_notify - SendNotify
- start_ask - StartAsk
- state_op - StateOp
- create_o_auth_client - CreateScimOAuthClient
- create_scim_token - CreateScimToken
- list_scim_o_auth_clients - ListScimOAuthClients
- list - ListScimTokens
- revoke_o_auth_client - RevokeScimOAuthClient
- revoke_scim_token - RevokeScimToken
- delete_secret - DeleteSecret
- get_members_with_secrets - GetMembersWithSecrets
- list_secrets - ListSecrets
- put_secret - PutSecret
- update - UpdateSecret
- check_member_status - CheckMemberStatus
- delete_member - DeleteOrganizationMember
- get - GetOrganizationSettings
- invite_member - InviteOrganizationMember
- list_members - ListOrganizationMembers
- update - UpdateOrganizationSettings
- create_uuid - CreateSlackUuid
- delete_installation - DeleteInstallation
- get_current_user - GetCurrentUser
- handle_o_auth_callback - HandleSlackOAuthCallback
- list_channels - ListChannels
- list_installations - ListInstallations
- list_users - ListUsers
- sync_workspace - SyncWorkspace
- generate_embed_token - Generate JWT token for embedding views
- get_collection_thumbnail - Get collection thumbnail (first view image)
- get_connected_app_status - GetConnectedAppStatus
- get_starred_items - GetStarredTableauItems
- list_tableau_datasources - List Tableau datasources
- list_projects - List Tableau projects
- list_views - List Tableau views
- list_workbooks - List Tableau workbooks
- refresh_collection - RefreshTableauCollection
- reset_connected_app - ResetConnectedApp
- star_item - Star/unstar items
- test_tableau_connection - Test a Tableau connection
- unstar_tableau_item - UnstarTableauItem
- create_uuid - CreateTeamsUuid
- delete_installation - DeleteInstallation
- get_current_user - GetCurrentUser
- handle_o_auth_callback - HandleTeamsOAuthCallback
- list - ListChannels
- list_installations - ListInstallations
- list_users - ListUsers
- sync_workspace - SyncWorkspace
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:
import os
from textql_sdk import Textql
from textql_sdk.utils import BackoffStrategy, RetryConfig
with Textql(
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
res = textql.agents.create(,
RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))
# Handle response
print(res)If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:
import os
from textql_sdk import Textql
from textql_sdk.utils import BackoffStrategy, RetryConfig
with Textql(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
res = textql.agents.create()
# Handle response
print(res)TextqlError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
err.message |
str |
Error message |
err.status_code |
int |
HTTP response status code eg 404 |
err.headers |
httpx.Headers |
HTTP response headers |
err.body |
str |
HTTP body. Can be empty string if no body is returned. |
err.raw_response |
httpx.Response |
Raw HTTP response |
import os
from textql_sdk import Textql, errors
with Textql(
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
res = None
try:
res = textql.agents.create()
# Handle response
print(res)
except errors.TextqlError as e:
# The base class for HTTP error responses
print(e.message)
print(e.status_code)
print(e.body)
print(e.headers)
print(e.raw_response)Primary error:
TextqlError: The base class for HTTP error responses.
Less common errors (5)
Network errors:
httpx.RequestError: Base class for request errors.httpx.ConnectError: HTTP client was unable to make a request to a server.httpx.TimeoutException: HTTP request timed out.
Inherit from TextqlError:
ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via thecauseattribute.
The default server can be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:
import os
from textql_sdk import Textql
with Textql(
server_url="https://app.textql.com/rpc/public",
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
res = textql.agents.create()
# Handle response
print(res)The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance.
Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls.
This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.
For example, you could specify a header for every request that this sdk makes as follows:
from textql_sdk import Textql
import httpx
http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = Textql(client=http_client)or you could wrap the client with your own custom logic:
from textql_sdk import Textql
from textql_sdk.httpclient import AsyncHttpClient
import httpx
class CustomClient(AsyncHttpClient):
client: AsyncHttpClient
def __init__(self, client: AsyncHttpClient):
self.client = client
async def send(
self,
request: httpx.Request,
*,
stream: bool = False,
auth: Union[
httpx._types.AuthTypes, httpx._client.UseClientDefault, None
] = httpx.USE_CLIENT_DEFAULT,
follow_redirects: Union[
bool, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
) -> httpx.Response:
request.headers["Client-Level-Header"] = "added by client"
return await self.client.send(
request, stream=stream, auth=auth, follow_redirects=follow_redirects
)
def build_request(
self,
method: str,
url: httpx._types.URLTypes,
*,
content: Optional[httpx._types.RequestContent] = None,
data: Optional[httpx._types.RequestData] = None,
files: Optional[httpx._types.RequestFiles] = None,
json: Optional[Any] = None,
params: Optional[httpx._types.QueryParamTypes] = None,
headers: Optional[httpx._types.HeaderTypes] = None,
cookies: Optional[httpx._types.CookieTypes] = None,
timeout: Union[
httpx._types.TimeoutTypes, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
extensions: Optional[httpx._types.RequestExtensions] = None,
) -> httpx.Request:
return self.client.build_request(
method,
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
s = Textql(async_client=CustomClient(httpx.AsyncClient()))httpx2 is Pydantic's maintained fork of httpx. To run this SDK on httpx2, call alias_httpx() at your program's entry point, before importing the SDK, so every import httpx — including the ones inside the SDK — resolves to httpx2:
import httpx2
httpx2.alias_httpx()
from textql_sdk import Textql
s = Textql()An SDK can also be generated against httpx2 directly, so it depends on the fork instead of httpx, by setting python.httpClientLibrary: httpx2 in gen.yaml.
The Textql class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.
import os
from textql_sdk import Textql
def main():
with Textql(
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
# Rest of application here...
# Or when using async:
async def amain():
async with Textql(
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
# Rest of application here...You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass your own logger class directly into your SDK.
from textql_sdk import Textql
import logging
logging.basicConfig(level=logging.DEBUG)
s = Textql(debug_logger=logging.getLogger("textql_sdk"))You can also enable a default debug logger by setting an environment variable TEXTQL_DEBUG to true.
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.