Python Client SDK Generated by Speakeasy.
Project description
textql
Developer-friendly & type-safe Python SDK specifically catered to leverage textql API.
[!IMPORTANT] This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Summary
TextQL API: TextQL public API. Generated from protobuf service definitions; internal endpoints are excluded via google.api.visibility / file_visibility.
Table of Contents
SDK Installation
[!TIP] To finish publishing your SDK to PyPI you must run your first generation action.
[!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
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 git+<UNSET>.git
PIP
PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install git+<UNSET>.git
Poetry
Poetry 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 git+<UNSET>.git
Shell and script usage with uv
You can use this SDK in a Python shell with uv and the uvx command that comes with it like so:
uvx --from textql-sdk python
It'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.
IDE Support
PyCharm
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.
SDK Example Usage
Example
# 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())
Authentication
Per-Client Security Schemes
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 Resources and Operations
Available methods
Agents
- create - CreateAgent
- delete - DeleteAgent
- duplicate - DuplicateAgent
- get_agent - GetAgent
- get_run - GetAgentRun
- list_runs - ListAgentRuns
- list - ListAgents
- reset_agent_avatar - ResetAgentAvatar
- trigger_agent - TriggerAgent
- update - UpdateAgent
- upload_agent_avatar - UploadAgentAvatar
Apps
- heartbeat - Viewer heartbeat: keeps a warm compute worker alive while the app is open so its billed lifetime tracks the view session (mirrors a dashboard's viewer TTL). No-op when the app has no warm worker; never spawns one.
- create_app - CreateApp
- delete_app - DeleteApp
- duplicate - Duplicates an app the caller can view into a new draft app they own, named "Copy of ". Copies code/files/data sources/compute functions/ schedule; never carries over the source's published state or data snapshot.
- get - GetApp
- get_app_version - GetAppVersion
- get_app_view_stats - View analytics: reads the engagement views recorded on app page load.
- get_members_with_apps - GetMembersWithApps
- invoke_compute_function - Executes a declared compute function on a pooled sandbox worker; gated, org-scoped, rate-limited.
- list_versions - Version history: a snapshot is recorded on each publish; authors can list and restore.
- list - ListApps
- move_app_to_folder - Moves an app into a library folder (or to root when folder_id is empty).
- refresh - Re-fetches data sources, rebuilds the document with a fresh snapshot, re-uploads.
- restore_app_version - RestoreAppVersion
- set_favorite - 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.
- update - UpdateApp
AuditLogs
- 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
Chats
- approve_context_prompt_change - ApproveContextPromptChange
- approve_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.
- attach_agent - External API users
- attach_app - AttachApp
- attach_dashboard - AttachDashboard
- attach_dataset - AttachDataset
- bookmark - BookmarkChat
- cancel_stream - CancelStream
- check_permissions - CheckChatPermissions
- check_health - CheckHealth
- check_streamlit_health - CheckStreamlitHealth
- create_chat - CreateChat
- delete - DeleteChat
- dismiss_questions - DismissQuestions
- 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 - GetCompletionParameters
- get_completion_parameters_batch - GetCompletionParametersBatch
- get_llm_usage - GetLlmUsage
- get_members_with_chats - List distinct chat creators the user can access
- get_playbook_chats - GetPlaybookChats
- poll_events - PollChatEvents
- query_one_shot - QueryOneShot
- rate_cell - RateChatCell appends a row to cell_rating for every click; thumbs-down also upserts a user_thumbs_down thread_warning.
- reject_context_prompt_change - RejectContextPromptChange
- reject_ontology_change - RejectOntologyChange
- run - RunChat
- send - SendMessage
- submit_context_prompt_change - SubmitContextPromptChange
- submit_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).
- unbookmark - UnbookmarkChat
- update - UpdateChat
Connectors
- 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
Dashboards
- 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
Datasets
- 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
Libraries
- add_submodule - AddLibrarySubmodule
- approve_patch - ApprovePatch
- configure_library_remote - ConfigureLibraryRemote
- create_approval_rule - CreateApprovalRule
- create_context_patch_auto_approve_rule - CreateContextPatchAutoApproveRule
- create_library_directory - CreateLibraryDirectory
- create_file_upload_url - CreateLibraryFileUploadUrl
- delete_approval_rule - DeleteApprovalRule
- delete_context_patch_auto_approve_rule - DeleteContextPatchAutoApproveRule
- delete_library_directory - DeleteLibraryDirectory
- delete_library_file - DeleteLibraryFile
- delete_owners - DeleteLibraryOwners
- deny_patch - DenyPatch
- exchange_github_code - ExchangeLibraryGithubCode
- finalize_file_upload - FinalizeLibraryFileUpload
- get_codeowner_coverage - GetCodeownerCoverage
- get_config_export_capabilities - GetConfigExportCapabilities
- get_effective_owners - GetEffectiveLibraryOwners
- get_file_usage - GetFileUsage
- get_file_usage_timeline - GetFileUsageTimeline
- get_ana_config - GetLibraryAnaConfig
- get_file - GetLibraryFile
- get_library_github_o_auth_url - GetLibraryGithubOAuthURL
- get_history_file_diff - GetLibraryHistoryFileDiff
- get_migration_status - GetLibraryMigrationStatus
- get_library_owners - GetLibraryOwners
- get_remote - GetLibraryRemote
- get_size_timeline - GetLibrarySizeTimeline
- get_library_sync_conflicts - GetLibrarySyncConflicts
- get_ontology_usage_summary - GetOntologyUsageSummary
- get_patch - GetPatch
- get_patch_by_number - GetPatchByNumber
- get_patch_capabilities - GetPatchCapabilities
- 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_library_entries - ListLibraryEntries
- list_library_history - ListLibraryHistory
- list_imports - ListLibraryImports
- list_library_submodules - ListLibrarySubmodules
- list_library_sync_runs - ListLibrarySyncRuns
- list_patch_reviewers - ListPatchReviewers
- list_patches - ListPatches
- list_skills - Lists the skills under the library's flat skills/ root that the caller can read (OWNERS-filtered). Returns display metadata only — never instruction bodies — feeding the chat composer's
/autocomplete. - migrate_legacy_context - MigrateLegacyContextToLibrary
- migrate_ontology - MigrateOntologyToLibrary
- plan_merge - PlanLibraryMerge
- preview_library_pull_from_remote - PreviewLibraryPullFromRemote
- pull_from_remote - PullLibraryFromRemote
- push_library_to_remote - PushLibraryToRemote
- recover - RecoverLibrary
- remove_remote - RemoveLibraryRemote
- remove_library_submodule - RemoveLibrarySubmodule
- rename_file - RenameLibraryFile
- request_patch_review - RequestPatchReview
- resolve_sync_conflict - ResolveLibrarySyncConflict
- restore_patch - RestorePatch
- revert_patch - RevertPatch
- save_all_objects_as_config - SaveAllObjectsAsConfig
- save_as_config - SaveObjectAsConfig
- trigger_config_drift_reconcile - TriggerConfigDriftReconcile forces an immediate config-sync catch-up for the caller's org: if the Library 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.
- update_approval_rule - UpdateApprovalRule
- update_context_patch_auto_approve_rule - UpdateContextPatchAutoApproveRule
- update_library_sync_config - UpdateLibrarySyncConfig
- upsert_ana_config - UpsertLibraryAnaConfig
- upsert_library_file - UpsertLibraryFile
- upsert_owners - UpsertLibraryOwners
- 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.
LibraryService
- library_service_list_golden_files - ListGoldenFiles
- library_service_set_library_file_golden - SetLibraryFileGolden
Mcp
- 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
MetricsExports
- configure - ConfigureMetricsExport
- delete_config - DeleteMetricsExportConfig
- get_metrics_export_config - GetMetricsExportConfig
- test_connection - TestMetricsExportConnection
- trigger_push - TriggerMetricsPush
Observability
- activate_custom_topic - ActivateCustomTopic
- backfill_custom_topic - BackfillCustomTopic
- backfill_thread_warnings - BackfillThreadWarnings
- create_custom_topic - CreateCustomTopic
- 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_observability_stats - GetObservabilityStats
- get_thread_warnings - GetThreadWarnings
- list_custom_topics - ListCustomTopics
- refine_draft - Custom topics
- set_topic_tag_feedback - SetTopicTagFeedback
- update_custom_topic - UpdateCustomTopic
Playbooks
- 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
Powerbi
- 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
Rbac
- add_group_member - AddGroupMember
- approve_access_request - ApproveAccessRequest
- assign_permission_to_role - AssignPermissionToRole
- assign_role_to_member - Member role assignment
- convert_role_to_group - ConvertRoleToGroup
- create_api_key - API Key management
- create_group - CreateGroup
- create_role - Role management
- create_service_account - Service account management
- delete_group - DeleteGroup
- delete_role - DeleteRole
- delete_service_account - DeleteServiceAccount
- generate_share_link - GenerateShareLink
- get_current_member_roles_and_permissions - Get current member roles and permissions
- get_embed_user_api_key - GetEmbedUserApiKey
- get_group - GetGroup
- get_member_groups - GetMemberGroups
- 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_group_connectors - ListGroupConnectors
- list_groups - ListGroups
- list_permissions - Permission management
- list_roles - ListRoles
- list_scim_group_mappings - ListScimGroupMappings
- list_service_accounts - ListServiceAccounts
- migrate_all_scim_group_mappings - MigrateAllScimGroupMappings
- migrate_scim_group_mapping_to_group - MigrateScimGroupMappingToGroup
- reject_access_request - RejectAccessRequest
- remove_group_member - RemoveGroupMember
- remove_permission_from_role - RemovePermissionFromRole
- remove_role_from_member - RemoveRoleFromMember
- request_access - Access request management
- revert_scim_group_mapping_to_role - RevertScimGroupMappingToRole
- revoke_api_key - RevokeApiKey
- revoke_object_access - RevokeObjectAccess
- rotate_api_key - RotateApiKey
- share_object - Object sharing and access control
- share_with_group - ShareObjectWithGroup
- share_object_with_role - ShareObjectWithRole
- update_group - UpdateGroup
- update_object_access - UpdateObjectAccess
- update_object_visibility - UpdateObjectVisibility
- update_role - UpdateRole
Sandbox
- execute_query - ExecuteQuery
SandboxAdmin
- 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
Scim
- 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
Secrets
- create_api_revision - CreateApiRevision
- delete_api_access_key - DeleteApiAccessKey
- delete_api_revision - DeleteApiRevision
- delete_secret - DeleteSecret
- get_api_access_key - GetApiAccessKey
- get_members_with_secrets - GetMembersWithSecrets
- list_api_access_keys - ListApiAccessKeys
- list_api_providers - ListApiProviders
- list_secrets - ListSecrets
- migrate_secret_to_api_connector - MigrateSecretToApiConnector
- put_secret - PutSecret
- test_api_access_key - TestApiAccessKey
- update - UpdateSecret
- upsert_api_access_key - UpsertApiAccessKey
Slack
- 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
Tableau
- 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
Teams
- 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
Retries
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)
Error Handling
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 |
Example
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)
Error Classes
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.
Server Selection
Override Server URL Per-Client
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",
api_key=os.getenv("TEXTQL_API_KEY", ""),
) as textql:
res = textql.agents.create()
# Handle response
print(res)
Custom HTTP Client
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()))
Resource Management
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...
Debugging
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.
Development
Maturity
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.
Contributions
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.
SDK Created by Speakeasy
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file textql_sdk-1.0.0.tar.gz.
File metadata
- Download URL: textql_sdk-1.0.0.tar.gz
- Upload date:
- Size: 642.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d9521c61e254f561ec5fa995f7b8a697a4fb4a6f22a1a90e608e2b309e079fb4
|
|
| MD5 |
c064b2962d010045cc0f815b4d3614e5
|
|
| BLAKE2b-256 |
8bb692a5b90c72ec97b59355db1593354e566390c70ed71b0ffbc989996e73f7
|
File details
Details for the file textql_sdk-1.0.0-py3-none-any.whl.
File metadata
- Download URL: textql_sdk-1.0.0-py3-none-any.whl
- Upload date:
- Size: 2.0 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c1a1987ad604b32da2c9c9a71b4ccfbd49c9a32bbc3efc243b7c42175eb3f247
|
|
| MD5 |
49a513e2aaa8a578401d95134869f267
|
|
| BLAKE2b-256 |
55efaf0ec6072ee50018fc489711e4ec5e4b0c06e9e03ff02209a93d4a45cc7d
|