Skip to main content

Railtown AI Python SDK

The Railtown AI Python SDK provides error tracking for applications and agent observability.

Logging

  1. Sign up for Railtown AI - Conductr
  2. Create a project, navigate to the Project Configuration page, and copy your API key
  3. In your app:
    1. Install the Railtown AI SDK: pip install railtownai
    2. Initialize Railtown AI with your API key: railtownai.init('YOUR_RAILTOWN_API_KEY')
    3. Use Python's native logging - all logs will automatically be sent to Railtown AI

Log delivery runs on a background thread. Calling logger.info() enqueues the record and returns immediately; the SDK does not perform network I/O on the thread that emitted the log.

Logging Basic Usage

import logging
import railtownai

# Initialize Railtown AI
railtownai.init('YOUR_RAILTOWN_API_KEY')

# Use Python's native logging - all logs are sent to Railtown AI
logging.info("User logged in", extra={"user_id": 123, "action": "login"})
logging.warning("High memory usage detected", extra={"memory_usage": "85%"})
logging.error("Database connection failed", extra={"db_host": "localhost"})

# Log exceptions with full stack traces
try:
    result = 1 / 0
except Exception:
    logging.exception("Division by zero error")

Logging with Breadcrumbs

Railtown AI supports breadcrumbs - contextual information that gets attached to log events. This is useful for tracking user actions or system state leading up to an error.

import logging
import railtownai

railtownai.init('YOUR_RAILTOWN_API_KEY')

# Add breadcrumbs throughout your application
railtownai.add_breadcrumb("User clicked login button", category="ui")
railtownai.add_breadcrumb("Validating user credentials", category="auth")
railtownai.add_breadcrumb("Database query executed", category="database",
                         data={"query": "SELECT * FROM users", "duration_ms": 45})

# When an error occurs, all breadcrumbs are automatically attached
try:
    # Some operation that might fail
    result = risky_operation()
except Exception:
    logging.exception("Operation failed")  # This will include all the breadcrumbs above

Agent Observability

Track and monitor your AI agent executions with structured data upload. This feature allows you to store detailed information about agent runs, including nodes, steps, and execution flow.

  1. Sign up for Conductr AI for FREE
  2. Initialize Conductr AI with your API key in your Project Configuration (Logs)
  3. Structure your agent data in the session format
  4. Upload using upload_agent_run()
import json
import logging

import railtownai
import railtracks as rt
from fastapi import FastAPI, Query

logger = logging.getLogger(__name__)

# Initialize SDK
railtownai.init("YOUR_API_KEY")

app = FastAPI()

# Replace with your actual agent
# from your_agents_module import WeatherAgent


@app.get("/weather")
async def get_weather(
    city: str = Query(..., description="City name like Vancouver"),
    units: str = Query("metric", description="metric or imperial"),
):
    try:
        # Build the message history for the weather request
        message_history = rt.llm.MessageHistory([
            rt.llm.UserMessage(f"Weather request\nCity: {city}\nUnits: {units}")
        ])

        # Call the agent
        with rt.Session(name="agent-session") as session:
            result = await rt.call(WeatherAgent, message_history)

            # Upload agent run data to RailTown AI
            agent_run_data = session.payload()
            success = railtownai.upload_agent_run(agent_run_data)

            if success:
                logger.info("Agent run data uploaded successfully")
            else:
                logger.error("Failed to upload agent run data")

        logger.info("Weather processing completed successfully")

        return {
            "success": True,
            "city": city,
            "units": units,
            "analysis": str(result),
        }

    except Exception as e:
        logger.error(f"Error processing weather request: {e}")
        return {"error": str(e)}

If you are using the Railtown AI Python Logger, RailTracks Frameworkr automatically propagates any errors at run-time and attaches the node_id, run_id, and session_id via the python logging package, so that Conductr Agent Observability platform can show you exactly which nodes failed or retried.

Agent Evaluations

Send agent evaluation results to Railengine (Conductr Agent Evaluations) for tracking and analysis.

  1. Get your EVALUATIONS_API_TOKEN from the Conductr Agent Evaluations page
  2. Add to .env: EVALUATIONS_API_TOKEN=<base64-encoded-json-from-conductr>
  3. Call upload_agent_evaluation() with your evaluation payload
import railtownai

# Set EVALUATIONS_API_TOKEN in .env (from Conductr Agent Evaluations onboarding)
success = railtownai.upload_agent_evaluation(result_from_evaluation_run)

upload_agent_evaluation() is safe to call inside a running asyncio event loop — for example from a FastAPI async def handler, or as the payload_callback passed to a railtracks evaluate() call that runs inside one. When a loop is already running it transparently offloads the upload to a worker thread. If you are already in async code and prefer to await directly, use the async-native variant:

success = await railtownai.upload_agent_evaluation_async(result_from_evaluation_run)

End-to-end: evaluate runs pulled from Conductr

Fetch the runs you have stored in Conductr with get_agent_runs() (see Fetching Agent Runs from Conductr) and pass the payloads straight into the railtracks evaluations API:

import railtownai
from railtracks import evaluations as evals

payloads = railtownai.get_agent_runs(agent_run_ids)
data = evals.extract_agent_data_points(payloads)   # railtracks >= the version with list[dict] support
results = evals.evaluate(data=data, evaluators=[...])
railtownai.upload_agent_evaluation(results)

Fetching Agent Runs from Conductr

Pull agent runs from the Conductr platform by id — for example when the platform triggers an evaluation against your deployed agent and hands it a list of agentRunIds.

  1. Generate a project PAT in the platform UI (project → Secret Tokens)
  2. Add to .env (or the environment):
    • CONDUCTR_PROJECT_PAT=<your-project-pat>
    • CONDUCTR_PROJECT_ID=<your-project-id>
    • RAILTOWN_API_URL=<platform-base-url> (optional; defaults to https://cndr.railtown.ai)
  3. Call get_agent_runs()

railtownai.init() is not required when both project environment variables are set. The platform host defaults to https://cndr.railtown.ai; set RAILTOWN_API_URL to target a different environment, or call init() to have the host derived from your API key. CONDUCTR_PROJECT_ID overrides the project id from an init() key.

import railtownai

# Fetch one or more runs — pass a list of size 1 for a single run.
# Fail-fast by default; skip_errors=True logs a warning per failed run
# and returns the successful payloads instead.
payloads = railtownai.get_agent_runs([id1, id2], skip_errors=False)

Fetch failures raise railtownai.AgentRunFetchError (with .agent_run_id and .status_code); a missing PAT or project id raises railtownai.AgentRunsNotInitializedError.

Contributing

See the contributing guide for more information (including pip install -e ".[test,dev]" for tests and Ruff in a local clone).

License

The MIT License is a permissive license that allows you to:

  • Use the software for any purpose
  • Modify the software
  • Distribute the software
  • Use it commercially
  • Use it privately
  • Sublicense it

The only requirement is that the original copyright notice and license must be included in all copies or substantial portions of the software.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

railtownai-2.1.1.tar.gz (24.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

railtownai-2.1.1-py3-none-any.whl (25.7 kB view details)

Uploaded Python 3

File details

Details for the file railtownai-2.1.1.tar.gz.

File metadata

  • Download URL: railtownai-2.1.1.tar.gz
  • Upload date:
  • Size: 24.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.34.2

File hashes

Hashes for railtownai-2.1.1.tar.gz
Algorithm Hash digest
SHA256 5008b50f3b85db7bb7eaa1e24d8a7e11c6d64cd67c27a9d0a3bcaca6d1fe113c
MD5 962c38bf9ef8e9cfb08dc49ccd2a32fe
BLAKE2b-256 34cfa9d91a6332c9180942cd6836849de7b8221474d9dee1c5cc30c3423d8d4f

See more details on using hashes here.

File details

Details for the file railtownai-2.1.1-py3-none-any.whl.

File metadata

  • Download URL: railtownai-2.1.1-py3-none-any.whl
  • Upload date:
  • Size: 25.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.34.2

File hashes

Hashes for railtownai-2.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 47860a60a4e9ae7ebf55053224ccfb5a2257aa4d0c9796c59961a170b86ef8b0
MD5 a17bf77b1c2a2766a86cd08957f300f3
BLAKE2b-256 4b3288d309753122baf5f93025caa5b933ae179fe821234976923c94ed5a1e1e

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

2.1.1 This release

2 files

2.1.0

2 files

2.0.17

2 files

2.0.16

2 files

2.0.15

2 files

2.0.14

2 files

2.0.13

2 files

2.0.12

2 files

2.0.11

2 files

2.0.10

2 files

2.0.9

2 files

2.0.8

2 files

2.0.7

2 files

2.0.6

2 files

2.0.5

2 files

2.0.4

2 files

2.0.3

2 files

2.0.2

2 files

2.0.1

2 files

2.0.0

2 files

1.0.3

2 files

1.0.2

2 files

1.0.1

2 files

1.0.0

2 files

0.0.7

2 files

0.0.6

2 files

0.0.5

2 files

0.0.4

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page