posthog-python API reference
138 public APIs from posthog-python (posthog/posthog-python) — 41 classes, 77 functions, 20 methods. Signatures extracted by static analysis of the actual source.
Repository: posthog/posthog-python
| Kind | Count |
|---|---|
| Classes | 41 |
| Functions | 77 |
| Methods | 20 |
API list
func
bin.docs_scripts.generate_json_schemas.analyze_class(cls) -> dictAnalyze a class and return its documentation.
func
bin.docs_scripts.generate_json_schemas.analyze_function(func, name:str) -> dictAnalyze a function and return its documentation.
func
bin.docs_scripts.generate_json_schemas.extract_description_from_docstring(docstring:str) -> strExtract main description from docstring.
func
bin.docs_scripts.generate_json_schemas.extract_details_from_docstring(docstring:str) -> strExtract details section from docstring.
func
bin.docs_scripts.generate_json_schemas.extract_examples_from_docstring(docstring:str) -> listExtract code examples from docstring.
func
bin.docs_scripts.generate_json_schemas.get_type_name(type_annotation) -> strConvert type annotation to string name.
func
bin.docs_scripts.generate_json_schemas.parse_docstring_tags(docstring:str) -> dictParse tags from docstring Category section.
class
posthog.PosthogPublic PostHog SDK client.
func
posthog.ai.anthropic.anthropic_converter.extract_anthropic_stop_reason(response:Any) -> Optional[str]Extract stop reason from Anthropic response.
func
posthog.ai.anthropic.anthropic_converter.extract_anthropic_tools(kwargs:Dict[str, Any]) -> Optional[Any]Extract tool definitions from Anthropic API kwargs.
func
posthog.ai.anthropic.anthropic_converter.extract_anthropic_web_search_count(response:Any) -> intExtract web search count from Anthropic response.
func
posthog.ai.gateway.is_posthog_ai_gateway_url(base_url:Any) -> boolReturn True if base_url points at a known PostHog AI Gateway host.
func
posthog.ai.gateway.warn_if_posthog_ai_gateway(base_url:Any) -> NoneWarn when an AI wrapper is pointed at the PostHog AI Gateway.
class
posthog.ai.gemini.gemini_converter.GeminiPartRepresents a part in a Gemini message.
func
posthog.ai.gemini.gemini_converter.extract_gemini_stop_reason(response:Any) -> Optional[str]Extract stop reason from Gemini response.
func
posthog.ai.gemini.gemini_converter.extract_gemini_stop_reason_from_chunk(chunk:Any) -> Optional[str]Extract stop reason from a Gemini streaming chunk.
func
posthog.ai.gemini.gemini_converter.extract_gemini_tools(kwargs:Dict[str, Any]) -> Optional[Any]Extract tool definitions from Gemini API kwargs.
func
posthog.ai.gemini.gemini_converter.extract_gemini_usage_from_chunk(chunk:Any) -> TokenUsageExtract usage statistics from a Gemini streaming chunk.
func
posthog.ai.gemini.gemini_converter.extract_gemini_web_search_count(response:Any) -> intExtract web search count from Gemini response.
func
posthog.ai.media.ensure_serializable(obj:Any) -> AnyEnsure an object is JSON-serializable, converting to str as fallback.
class
posthog.ai.openai.openai.WrappedChatWrapper for OpenAI chat that tracks usage in PostHog.
func
posthog.ai.openai.openai_converter.extract_openai_content_from_chunk(chunk:Any, provider_type:str='chat') -> Optional[Any]Extract content from an OpenAI streaming chunk.
func
posthog.ai.openai.openai_converter.extract_openai_stop_reason(response:Any) -> Optional[str]Extract stop reason from OpenAI response.
func
posthog.ai.openai.openai_converter.extract_openai_tools(kwargs:Dict[str, Any]) -> Optional[Any]Extract tool definitions from OpenAI API kwargs.
func
posthog.ai.openai.openai_converter.extract_openai_web_search_count(response:Any) -> intExtract web search count from OpenAI response.
func
posthog.ai.openai.openai_converter.format_openai_input(messages:Optional[List[Dict[str, Any]]]=None, input_data:Optional[Any]=None) -> List[FormattedMessage]Format OpenAI input messages.
func
posthog.ai.openai.openai_converter.format_openai_streaming_input(kwargs:Dict[str, Any], api_type:str='chat') -> AnyFormat OpenAI streaming input based on API type.
class
posthog.ai.prompts.CachedPromptCached prompt with metadata.
class
posthog.ai.prompts.PromptResultResult of a prompt fetch with metadata about its source.
class
posthog.ai.prompts.PromptsFetch and compile LLM prompts from PostHog.
method
posthog.ai.prompts.Prompts.clear_cache(name:Optional[str]=None, *version:Optional[int]=None) -> NoneClear cached prompts.
method
posthog.ai.prompts.Prompts.compile(prompt:str, variables:PromptVariables) -> strReplace {{variableName}} placeholders with values.
class
posthog.ai.types.FormattedFunctionCallFormatted function/tool call content item.
class
posthog.ai.types.FormattedImageContentFormatted image content item.
class
posthog.ai.types.FormattedMessageStandardized message format for PostHog tracking.
class
posthog.ai.types.FormattedTextContentFormatted text content item.
class
posthog.ai.types.ProviderResponseStandardized provider response format.
class
posthog.ai.types.TokenUsageToken usage information for AI model responses.
func
posthog.ai.utils.extract_stop_reason(response:Any, provider:str) -> Optional[str]Extract stop reason from response based on provider.
func
posthog.ai.utils.format_response(response, provider:str)Format a regular (non-streaming) response.
func
posthog.ai.utils.get_model_params(kwargs:Dict[str, Any]) -> Dict[str, Any]Extracts model parameters from the kwargs dictionary.
func
posthog.ai.utils.get_usage(response, provider:str) -> TokenUsageExtract usage statistics from response based on provider.
class
posthog.args.OptionalCaptureArgsOptional arguments for the capture method.
class
posthog.args.OptionalSetArgsOptional arguments for the set method.
func
posthog.capture(event:str, **kwargs:Unpack[OptionalCaptureArgs]) -> Optional[str]Capture anything a user does within your system.
func
posthog.capture_exception(exception:Optional[ExceptionArg]=None, **kwargs:Unpack[OptionalCaptureArgs]) -> Optional[str]Capture exceptions that happen in your code.
class
posthog.capture_mode.CaptureModeSelects the capture wire protocol used for event ingestion.
class
posthog.capture_v1.CaptureV1ErrorBatch-level failure of a capture-v1 send.
class
posthog.client.ClientThis is the SDK reference for the PostHog Python SDK.
method
posthog.client.Client.capture(event:str, **kwargs:Unpack[OptionalCaptureArgs]) -> Optional[str]Captures an event manually.
method
posthog.client.Client.capture_exception(exception:Optional[ExceptionArg], **kwargs:Unpack[OptionalCaptureArgs]) -> Optional[str]Capture an exception for error tracking.
method
posthog.client.Client.flush(timeout_seconds:Optional[float]=10) -> NoneForce a flush from the internal queue to the server.
method
posthog.client.Client.get_tags() -> Dict[str, Any]Get all tags from the current context.
method
posthog.client.Client.identify_context(distinct_id:str) -> NoneIdentify the current context with a distinct ID.
method
posthog.client.Client.set(**kwargs:Unpack[OptionalSetArgs]) -> Optional[str]Set properties on a person profile.
method
posthog.client.Client.set_context_device_id(device_id:str) -> NoneSet the device ID for the current context.
method
posthog.client.Client.set_context_session(session_id:str) -> NoneSet the session ID for the current context.
method
posthog.client.Client.shutdown() -> NoneFlush all messages and cleanly shutdown the client.
method
posthog.client.Client.tag(name:str, value:Any) -> NoneAdd a tag to the current context.
class
posthog.consumer.ConsumerConsumes the messages from the client's queue.
method
posthog.consumer.Consumer.next()Return the next batch of items to upload.
method
posthog.consumer.Consumer.run()Runs the consumer.
func
posthog.contexts.get_context_device_id() -> Optional[str]Get the device ID for the current context.
func
posthog.contexts.get_context_distinct_id() -> Optional[str]Get the distinct ID for the current context.
func
posthog.contexts.get_context_session_id() -> Optional[str]Get the session ID for the current context.
func
posthog.contexts.get_tags() -> Dict[str, Any]Get all tags from the current context.
func
posthog.contexts.set_code_variables_mask_url_credentials_context(enabled:bool) -> NoneWhether to scrub credentials embedded in URLs/DSNs (e.g.
func
posthog.contexts.tag(key:str, value:Any) -> NoneAdd a tag to the current context.
class
posthog.exception_utils.AnnotatedValueMeta information for a data field in the event payload.
func
posthog.feature_flag_definitions()Returns loaded feature flags.
class
posthog.feature_flags.ConditionMatchOutcome of evaluating a single condition group.
class
posthog.flag_definition_cache.FlagDefinitionCacheDataData structure for cached flag definitions.
func
posthog.flush(timeout_seconds:Optional[float]=10) -> NoneTell the client to flush all queued events.
func
posthog.get_remote_config_payload(key:str)Get the payload for a remote config feature flag.
func
posthog.get_tags() -> Dict[str, Any]Get all tags from the current context.
func
posthog.identify_context(distinct_id:str)Identify the current context with a distinct ID.
class
posthog.integrations.django.PosthogContextMiddlewareMiddleware to automatically track Django requests.
class
posthog.mcp.McpAnalyticsHandle returned by :func:`instrument`.
method
posthog.mcp.McpAnalytics.capture(event:str, properties:Optional[dict]=None) -> NoneCapture a custom event for this server.
func
posthog.mcp._conversation_id.resolve_conversation_id(enabled:bool, args:Any, tool_name:Optional[str], missing_capability_tool_name:str) -> Tuple[Optional[str], bool]Return ``(conversation_id, minted)``.
func
posthog.mcp._ids.deterministic_prefixed_id(prefix:MCPAnalyticsIDPrefix, value:str) -> strDeterministic id derived from an arbitrary string.
func
posthog.mcp._instrument_lowlevel.instrument_low_level(server:Any, data:MCPAnalyticsData) -> NoneInstrument a raw ``mcp.server.Server``.
func
posthog.mcp._instrumentation.read_tool_category(tool:Any) -> Optional[str]Read a tool's product category from its ``_meta.category``.
class
posthog.mcp._internal.MCPAnalyticsDataAll per-server tracking state.
func
posthog.mcp._sanitization.sanitize_event(event:Dict[str, Any]) -> Dict[str, Any]Sanitize an event's response, parameters, and user_intent.
func
posthog.mcp._sink.process_mcp_event(event:McpEvent, options:McpCaptureOptions) -> Optional[Tuple[Event, List[PostHogCaptureEvent]]]Run an MCP event through the full transform.
func
posthog.mcp.asgi.autowire_stateless_mint(server:Any) -> NoneMake stateless minting zero-config on the ``instrument()`` path.
class
posthog.mcp.constants.PostHogMCPAnalyticsEventPostHog-owned event names.
class
posthog.mcp.constants.PostHogMCPAnalyticsPropertyPostHog property wire-keys emitted on MCP events.
func
posthog.mcp.session.resolve_session_id(data:MCPAnalyticsData, mcp_session_id:Optional[str], *token:Optional[SessionTokenPayload]=None) -> strResolve the session id for a request.
class
posthog.mcp.session_token.SessionTokenPayloadWhat a session token carries.
func
posthog.mcp.session_token.decode_session_id(value:Any) -> Optional[SessionTokenPayload]Decode an ``Mcp-Session-Id`` value into a token payload.
func
posthog.mcp.session_token.read_mcp_session_header(headers:Any) -> Optional[str]Read the ``mcp-session-id`` value off a headers mapping.
class
posthog.mcp.types.MCPAnalyticsOptionsConfiguration for ``instrument()``.
class
posthog.mcp.types.PostHogCaptureEventA fully-built payload ready for ``Client.capture()``.
class
posthog.mcp.types.UserIdentityResolved identity for a session.
class
posthog.request.GetResponseResponse from a GET request with ETag support.
class
posthog.request.HTTPAdapterWithSocketOptionsHTTPAdapter with configurable socket options.
func
posthog.request.determine_server_host(host:Optional[str]) -> strDetermines the server host to use.
func
posthog.request.disable_connection_reuse() -> NoneDisable HTTP connection reuse for SDK requests.
func
posthog.request.enable_keep_alive() -> NoneEnable TCP keepalive for SDK HTTP connections.
func
posthog.request.get(api_key:str, url:str, host:Optional[str]=None, timeout:Optional[int]=None, etag:Optional[str]=None) -> GetResponseMake a GET request with optional ETag support.
func
posthog.request.normalize_host(host:Optional[str]) -> strNormalize a configured host, defaulting blank values to DEFAULT_HOST.
func
posthog.request.post(api_key:str, host:Optional[str]=None, path:Optional[str]=None, gzip:bool=False, timeout:int=15, session:Optional[requests.Session]=None, **kwargs) -> requests.ResponsePost the `kwargs` to the API
func
posthog.request.reset_sessions() -> NoneReset the global sessions.
func
posthog.request.set_socket_options(socket_options:Optional[SocketOptions]) -> NoneConfigure socket options for all SDK HTTP connections.
func
posthog.set(**kwargs:Unpack[OptionalSetArgs]) -> Optional[str]Set properties on a user record.
func
posthog.set_context_session(session_id:str)Set the session ID for the current context.
func
posthog.set_once(**kwargs:Unpack[OptionalSetArgs]) -> Optional[str]Set properties on a user record, only if they do not yet exist.
func
posthog.shutdown() -> NoneFlush all messages and cleanly shutdown the client.
func
posthog.tag(name:str, value:Any)Add a tag to the current context.
class
posthog.types.FeatureFlagDetailed feature flag evaluation returned by the flags API.
class
posthog.types.FeatureFlagErrorError type constants for the $feature_flag_error property.
method
posthog.types.FeatureFlagError.api_error(status:Union[int, str]) -> strGenerate API error string with status code.
class
posthog.types.FlagMetadataFeature flag metadata returned by the feature flag API.
class
posthog.types.FlagReasonReason metadata returned by the feature flag API.
class
posthog.types.FlagsAndPayloadsFeature flag values and payloads keyed by feature flag key.
class
posthog.types.FlagsResponseNormalized response from the PostHog feature flags API.
class
posthog.types.LegacyFlagMetadataLegacy feature flag metadata containing only a payload.
func
posthog.utils.guess_timezone(dt:datetime) -> datetimeAttempts to convert a naive datetime to an aware datetime.
func
posthog.utils.is_naive(dt:datetime) -> boolDetermines if a given datetime.datetime is naive.
func
posthog.utils.total_seconds(delta:timedelta) -> floatReturn the total number of seconds contained in the duration.
class
sdk_compliance_adapter.adapter.RequestInfoInformation about an HTTP request made by the SDK
class
sdk_compliance_adapter.adapter.SDKStateTracks SDK internal state for test assertions
method
sdk_compliance_adapter.adapter.SDKState.get_state() -> Dict[str, Any]Get current state as dict
method
sdk_compliance_adapter.adapter.SDKState.increment_captured()Increment total events captured
method
sdk_compliance_adapter.adapter.SDKState.record_error(error:str)Record an error
method
sdk_compliance_adapter.adapter.SDKState.reset()Reset all state
func
sdk_compliance_adapter.adapter.capture()Capture a single event
func
sdk_compliance_adapter.adapter.create_batch_id(batch:List[Dict]) -> strCreate a unique ID for a batch based on UUIDs
func
sdk_compliance_adapter.adapter.flush()Force flush all pending events
func
sdk_compliance_adapter.adapter.get_feature_flag()Evaluate a feature flag
func
sdk_compliance_adapter.adapter.get_state()Get internal SDK state
func
sdk_compliance_adapter.adapter.health()Health check endpoint
func
sdk_compliance_adapter.adapter.identify()Identify a user
func
sdk_compliance_adapter.adapter.init()Initialize the SDK client
func
sdk_compliance_adapter.adapter.main()Main entry point
func
sdk_compliance_adapter.adapter.reset()Reset SDK state
About this data
These signatures were extracted from the public source of posthog/posthog-python
using Python's ast module. Argument names, default values,
type annotations and return types are taken verbatim from the code.
Implementation bodies are never stored. See
how it works for details.