### Install Axiom Go SDK Source: https://axiom.co/docs/guides/go Install the Axiom Go SDK using the go get command. ```shell go get github.com/axiomhq/axiom-go/axiom ``` -------------------------------- ### Install axiom-hostmetrics with Homebrew Source: https://axiom.co/docs/query-data/metrics Install the axiom-hostmetrics CLI tool using Homebrew for quick setup of OTel metrics streaming to Axiom. ```sh brew install axiomhq/tap/axiom-hostmetrics ``` -------------------------------- ### Install Axiom Loki Proxy using go get Source: https://axiom.co/docs/send-data/loki-multiplexer Install or update the axiom-loki-proxy using the go get command. This method requires Go to be installed on your system. ```bash go get -u github.com/axiomhq/axiom-loki-proxy/cmd/axiom-loki-proxy ``` -------------------------------- ### Run Axiom Loki Proxy Locally Source: https://axiom.co/docs/send-data/loki-multiplexer Execute the axiom-loki-proxy binary after installation. This command starts the proxy service, ready to receive logs. ```bash ./axiom-loki-proxy ``` -------------------------------- ### Source Script and Start Claude Code Source: https://axiom.co/docs/guides/opentelemetry-claude-code This command sources the setup script to export necessary environment variables and then starts the Claude Code application. Ensure the setup script is in your current directory. ```bash source ./setup-otel.sh && claude ``` -------------------------------- ### Install axiom-hostmetrics with Go Source: https://axiom.co/docs/llms-full.txt Install the axiom-hostmetrics CLI using Go if Homebrew is not available. ```sh go install github.com/axiom/axiom-hostmetrics/cmd/axiom-hostmetrics@latest ``` -------------------------------- ### Install Axiom Syslog Proxy using Go command Source: https://axiom.co/docs/send-data/syslog-proxy Install the Axiom Syslog Proxy directly using the 'go install' command. ```shell go install github.com/axiomhq/axiom-syslog-proxy/cmd/axiom-syslog-proxy@latest ``` -------------------------------- ### Install axiom-hostmetrics with Go Source: https://axiom.co/docs/query-data/metrics Install the axiom-hostmetrics CLI tool using Go for streaming OTel metrics to Axiom. ```sh go install github.com/axiomhq/axiom-hostmetrics/cmd/axiom-hostmetrics@latest ``` -------------------------------- ### Install Axiom CLI using Go Source: https://axiom.co/docs/reference/cli Install the Axiom CLI using the Go programming language. Ensure you have Go installed before running this command. ```bash go install github.com/axiomhq/cli/cmd/axiom@latest ``` -------------------------------- ### Install Axiom MCP Server Binary Source: https://axiom.co/docs/console/intelligence/mcp-server Installs the latest Axiom MCP Server binary from GitHub releases using go install. ```bash go install github.com/axiomhq/axiom-mcp@latest ``` -------------------------------- ### Install Axiom Python SDK on Windows Source: https://axiom.co/docs/guides/python Install the axiom-py package using pip on Windows. ```shell py -m pip install axiom-py ``` -------------------------------- ### Start Node.js Application in Production Source: https://axiom.co/docs/guides/opentelemetry-nodejs Start your built Node.js application in production mode. ```bash npm start ``` -------------------------------- ### Install Project Dependencies Source: https://axiom.co/docs/llms-full.txt Run this command in the root of your project to install all necessary packages listed in package.json. ```bash npm install ``` -------------------------------- ### Install Axiom CLI using Homebrew Source: https://axiom.co/docs/reference/cli Install the Axiom CLI using Homebrew. This command installs Axiom command globally. ```bash brew install --cask axiomhq/tap/axiom ``` -------------------------------- ### Install dependencies from requirements.txt Source: https://axiom.co/docs/guides/opentelemetry-python Install all Python dependencies listed in the requirements.txt file using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install @axiomhq/logging Source: https://axiom.co/docs/guides/javascript Install the @axiomhq/logging library using npm. This library provides structured logging capabilities. ```bash npm install @axiomhq/logging ``` -------------------------------- ### Install Axiom Python SDK using pip3 Source: https://axiom.co/docs/guides/python Install the axiom-py package using pip3. ```shell pip3 install axiom-py ``` -------------------------------- ### Install Autoevals Source: https://axiom.co/docs/ai-engineering/evaluate/scorers Install the autoevals library using npm. This is a prerequisite for using the prebuilt scorers. ```bash npm install autoevals ``` -------------------------------- ### Install @axiomhq/js Source: https://axiom.co/docs/guides/javascript Install the @axiomhq/js library using npm. This is the first step to integrate Axiom into your JavaScript application. ```shell npm install @axiomhq/js ``` -------------------------------- ### Get the role of the first message in a GenAI conversation Source: https://axiom.co/docs/apl/scalar-functions/genai-functions/genai-get-role Retrieves the role of the very first message (index 0) in a GenAI conversation. This example counts conversations starting with a 'system' role. ```kusto ['otel-demo-genai'] | extend first_role = genai_get_role(['attributes.gen_ai.input.messages'], 0) | summarize conversations_with_system = countif(first_role == 'system'), total_conversations = count() ``` -------------------------------- ### Main HTTP Server Setup and Signal Handling Source: https://axiom.co/docs/llms-full.txt This Go code sets up a basic HTTP server with OpenTelemetry instrumentation. It includes signal handling for graceful shutdown and demonstrates server configuration like timeouts and context. ```go // main.go package main import ( "context" "fmt" "log" "math/rand" "net" "net/http" "os" "os/signal" time "time" // OpenTelemetry imports for tracing and observability. "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace" ) // main function starts the application and handles run function errors. func main() { if err := run(); err != nil { log.Fatalln(err) } } // run sets up signal handling, tracer initialization, and starts an HTTP server. func run() error { // Creating a context that listens for the interrupt signal from the OS. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() // Initializes tracing and returns a function to shut down OpenTelemetry cleanly. otelShutdown, err := SetupTracer() if err != nil { return err } defer func() { if shutdownErr := otelShutdown(ctx); shutdownErr != nil { log.Printf("failed to shutdown OpenTelemetry: %v", shutdownErr) // Log fatal errors during server shutdown } }() // Configuring the HTTP server settings. srv := &http.Server{ Addr: ":8080", // Server address BaseContext: func(_ net.Listener) context.Context { return ctx }, ReadTimeout: 5 * time.Second, // Server read timeout WriteTimeout: 15 * time.Second, // Server write timeout Handler: newHTTPHandler(), // HTTP handler } // Starting the HTTP server in a new goroutine. go func() { if err := srv.ListenAndServe(); err != http.ErrServerClosed { log.Fatalf("HTTP server ListenAndServe: %v", err) } }() // Wait for interrupt signal to gracefully shut down the server with a timeout context. <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() // Ensures cancel function is called on exit if err := srv.Shutdown(shutdownCtx); err != nil { log.Fatalf("HTTP server Shutdown: %v", err) // Log fatal errors during server shutdown } return nil } // newHTTPHandler configures the HTTP routes and integrates OpenTelemetry. func newHTTPHandler() http.Handler { mux := http.NewServeMux() // HTTP request multiplexer // Wrapping the handler function with OpenTelemetry instrumentation. handleFunc := func(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) { handler := otelhttp.WithRouteTag(pattern, http.HandlerFunc(handlerFunc)) mux.Handle(pattern, handler) // Associate pattern with handler } // Registering route handlers with OpenTelemetry instrumentation handleFunc("/rolldice", rolldice) handleFunc("/roll_with_link", rollWithLink) handler := otelhttp.NewHandler(mux, "/") return handler } // rolldice handles the /rolldice route by generating a random dice roll. func rolldice(w http.ResponseWriter, r *http.Request) { _, span := otel.Tracer("example-tracer").Start(r.Context(), "rolldice") defer span.End() // Generating a random dice roll. randGen := rand.New(rand.NewSource(time.Now().UnixNano())) roll := 1 + randGen.Intn(6) // Writing the dice roll to the response. fmt.Fprintf(w, "Rolled a dice: %d\n", roll) } // rollWithLink handles the /roll_with_link route by creating a new span with a link to the parent span. func rollWithLink(w http.ResponseWriter, r *http.Request) { ctx, span := otel.Tracer("example-tracer").Start(r.Context(), "roll_with_link") defer span.End() /** * Create a new span for rolldice with a link to the parent span. * This link helps correlate events that are related but not directly a parent-child relationship. */ rollDiceCtx, rollDiceSpan := otel.Tracer("example-tracer").Start(ctx, "rolldice", trace.WithLinks(trace.Link{ SpanContext: span.SpanContext(), Attributes: nil, }), ) defer rollDiceSpan.End() // Generating a random dice roll linked to the parent context. randGen := rand.New(rand.NewSource(time.Now().UnixNano())) roll := 1 + randGen.Intn(6) // Writing the linked dice roll to the response. fmt.Fprintf(w, "Dice roll result (with link): %d\n", roll) // Use the rollDiceCtx if needed. _ = rollDiceCtx } ``` -------------------------------- ### Install Axiom CLI from Source Source: https://axiom.co/docs/reference/cli Build and install the Axiom CLI binary from its source code. This requires cloning the repository and using the make command. ```bash git clone https://github.com/axiomhq/cli.git cd cli make install ``` -------------------------------- ### Get Schema Use Case Example Source: https://axiom.co/docs/llms-full.txt Example of querying the schema for 'sample-http-logs' dataset using the getschema operator in APL. ```kusto ['sample-http-logs'] | getschema ``` -------------------------------- ### Basic MPL Query Example Source: https://axiom.co/docs/llms-full.txt This example queries the otel-demo-metrics dataset's go.memory.used metric. It filters results to the 'checkout' deployment and aggregates values over 5-minute time windows into their average. ```kusto `otel-demo-metrics`:`go.memory.used` | where `k8s.deployment.name` == "checkout" | align to 5m using avg ``` -------------------------------- ### Get current time in APL (equivalent to SQL) Source: https://axiom.co/docs/apl/scalar-functions/datetime-functions/now This APL example demonstrates getting the current time, equivalent to SQL's CURRENT_TIMESTAMP. ```kusto ['dataset'] | extend current_time = now() ``` -------------------------------- ### Create Project Directory Source: https://axiom.co/docs/guides/opentelemetry-cloudflare-workers Create a new directory for your project and navigate into it. ```bash mkdir my-axiom-worker && cd my-axiom-worker ``` -------------------------------- ### Get current time in APL (equivalent to Splunk) Source: https://axiom.co/docs/apl/scalar-functions/datetime-functions/now This APL example demonstrates getting the current time, equivalent to the Splunk SPL now() function. ```kusto | extend current_time = now() ``` -------------------------------- ### Top 5 Cities Generating GET HTTP Requests Source: https://axiom.co/docs/apl/aggregation-function/topkif Find the top 5 cities that are generating the most GET HTTP requests. This example uses topkif on the 'geo.city' field, filtered by requests where the method is 'GET'. ```kusto ['sample-http-logs'] | summarize topkif(['geo.city'], 5, method == 'GET') ``` -------------------------------- ### Complete Example: Instrumenting AI SDK with Axiom Source: https://axiom.co/docs/llms-full.txt This example demonstrates how `wrapAISDKModel`, `wrapTool`, and `withSpan` work together. It shows wrapping the AI model client, defining and wrapping tools, and using `withSpan` to tie everything together. ```typescript import { withSpan, wrapAISDKModel, wrapTool } from 'axiom/ai'; import { generateText, tool } from 'ai'; import { createOpenAI } from '@ai-sdk/openai'; import { z } from 'zod'; // 1. Create and wrap the AI model client const openaiProvider = createOpenAI({ apiKey: process.env.OPENAI_API_API_KEY, }); const gpt4o = wrapAISDKModel(openaiProvider('gpt-4o')); // 2. Define and wrap your tool(s) const findDirectionsTool = wrapTool( 'findDirections', // The tool name must be passed to the wrapper tool({ description: 'Find directions to a location', inputSchema: z.object({ from: z.string(), to: z.string() }), execute: async ({ from, to }) => ({ directions: `To get from ${from} to ${to}, use a teleporter.`, }), }) ); // 3. In your application logic, use `withSpan` to add context // and call the AI model with your wrapped tools. export default async function Page() { const userId = 123; const { text } = await withSpan({ capability: 'get_directions', step: 'generate_ai_response' }, async (span) => { // You have access to the OTel span to add custom attributes span.setAttribute('user_id', userId); return generateText({ model: gpt4o, // Use the wrapped model messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'How do I get from Paris to Berlin?' }, ], tools: { findDirections: findDirectionsTool, // Use the wrapped tool }, }); }); return

{text}

; } ``` -------------------------------- ### Splunk SPL now() example Source: https://axiom.co/docs/llms-full.txt This snippet shows how to get the current time in Splunk SPL using the `now()` function. ```sql ... | eval current_time=now() ``` -------------------------------- ### Splunk SPL len Function Example Source: https://axiom.co/docs/apl/scalar-functions/array-functions/len In Splunk SPL, the len function is used within eval or where expressions to get string length or array size. This example shows how to evaluate the length of a 'uri' field. ```sql ... | eval uri_length=len(uri) ``` -------------------------------- ### Get current timestamp in SQL Source: https://axiom.co/docs/apl/scalar-functions/datetime-functions/now This SQL example shows how to retrieve the current date and time using CURRENT_TIMESTAMP. ```sql SELECT CURRENT_TIMESTAMP AS current_time; ``` -------------------------------- ### OpenAPI Specification for Get Annotations Source: https://axiom.co/docs/restapi/endpoints/getAnnotations This OpenAPI 3.0.0 specification defines the GET /annotations endpoint. It details the request parameters, including filtering by datasets, start time, and end time, as well as the structure of the Annotation response object. ```yaml openapi: 3.0.0 info: description: A public and stable API for interacting with axiom services title: Axiom termsOfService: http://axiom.co/terms contact: name: Axiom support team url: https://axiom.co email: hello@axiom.co license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html version: 2.0.0 servers: - url: https://api.axiom.co/v2/ security: - bearerAuth: [] paths: /annotations: get: tags: - annotations description: Get annotations operationId: getAnnotations parameters: - description: 'Optional: Filter for dataset names.' name: datasets in: query style: form explode: false schema: type: array items: type: string - description: >- Optional: Filter for events after this date. Use RFC3339 time format. name: start in: query schema: type: string - description: >- Optional: Filter for events before this date. Use RFC3339 time format. name: end in: query schema: type: string responses: '200': description: Annotation content: application/json: schema: type: array items: $ref: '#/components/schemas/Annotation' security: - Auth: - annotations|read components: schemas: Annotation: type: object required: - id - time - datasets - type properties: datasets: description: >- array of dataset names for which the annotation appears on charts type: array minItems: 1 items: type: string minLength: 1 description: description: Explanation of the event the annotation marks on the charts type: string maxLength: 512 endTime: description: End time of the annotation type: string format: date-time nullable: true id: $ref: '#/components/schemas/AnnotationID' time: description: >- Time the annotation marks on the charts. If you don't include this field, Axiom assigns the time of the API request to the annotation. type: string format: date-time title: description: Summary of the annotation that appears on the charts type: string maxLength: 256 type: description: >- Type of the event marked by the annotation. Use only alphanumeric characters or hyphens. For example, "production-deployment". type: string maxLength: 256 pattern: '^[a-z0-9-]+$' url: description: >- URL relevant for the event marked by the annotation. For example, link to GitHub pull request. type: string maxLength: 512 example: datasets: - my-dataset description: Deploy new feature to the sales form endTime: '2024-02-06T11:39:28.382Z' id: ann_123 time: '2024-02-06T10:39:28.382Z' title: Production deployment type: deploy url: https://example.com AnnotationID: type: string x-go-type: import: package: github.com/axiomhq/axiom/pkg/core/ids type: AnnotationID securitySchemes: bearerAuth: type: http scheme: bearer description: >- Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens). Auth: description: >- Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens). type: oauth2 flows: authorizationCode: authorizationUrl: https://accounts.google.com/o/oauth2/v2/auth tokenUrl: https://www.googleapis.com/oauth2/v4/token scopes: {} ``` -------------------------------- ### Build and Run .NET Application Source: https://axiom.co/docs/guides/send-logs-from-dotnet Build and run your .NET application from the project directory in your terminal. This command compiles the project and starts the application, sending logs to Axiom. ```bash dotnet build dotnet run ``` -------------------------------- ### Get General Axiom CLI Help Source: https://axiom.co/docs/reference/cli Run this command to display general usage tips and information about available commands in the Axiom CLI. ```bash axiom help ``` -------------------------------- ### OpenAPI Specification for Get Monitor History Source: https://axiom.co/docs/restapi/endpoints/getMonitorHistory This OpenAPI 3.0 specification defines the GET /monitors/{id}/history endpoint. It includes parameters for filtering by ID, start time, and end time, and specifies the response structure for alert history. ```yaml openapi: 3.0.0 info: description: A public and stable API for interacting with axiom services title: Axiom termsOfService: http://axiom.co/terms contact: name: Axiom support team url: https://axiom.co email: hello@axiom.co license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html version: 2.0.0 servers: - url: https://api.axiom.co/v2/ security: - bearerAuth: [] paths: /monitors/{id}/history: get: tags: - Monitors description: Get monitor history operationId: getMonitorHistory parameters: - name: id in: path required: true schema: type: string - description: Start time (ISO 8601 format) for filtering alert history. name: startTime in: query required: true schema: type: string format: date-time - description: End time (ISO 8601 format) for filtering alert history. name: endTime in: query required: true schema: type: string format: date-time responses: '200': description: AlertHistory content: application/json: schema: type: array items: $ref: '#/components/schemas/AlertHistory' security: - Auth: - monitors|read components: schemas: AlertHistory: description: > Historical record of an alert's state changes. Tracks when alerts are opened and closed, allowing for incident timeline analysis. type: object required: - name - checkId - timestamp - state properties: checkId: description: Unique identifier of the check that triggered the alert type: string example: chk_abc123 name: description: The name of the alert type: string example: High CPU Usage Alert state: description: Current state of the alert type: string enum: - open - closed example: open timestamp: description: ISO 8601 timestamp when the alert state changed type: string format: date-time example: '2024-03-20T15:30:00Z' securitySchemes: bearerAuth: type: http scheme: bearer description: >- Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens). Auth: description: >- Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens). type: oauth2 flows: authorizationCode: authorizationUrl: https://accounts.google.com/o/oauth2/v2/auth tokenUrl: https://www.googleapis.com/oauth2/v4/token scopes: {} ``` -------------------------------- ### Extract Assistant Response Example Source: https://axiom.co/docs/apl/scalar-functions/genai-functions/genai-extract-assistant-response Demonstrates how to use genai_extract_assistant_response to get AI responses from a GenAI conversation and filter for non-empty results. ```kusto ['otel-demo-genai'] | extend ai_response = genai_extract_assistant_response(['attributes.gen_ai.input.messages']) | where strlen(ai_response) > 0 | project _time, ai_response | limit 3 ``` -------------------------------- ### APL: Top 5 status codes for GET requests (estimated) Source: https://axiom.co/docs/apl/aggregation-function/topkif This APL query achieves a similar result to the Splunk example by summarizing the top 5 status codes for requests where the method is 'GET'. It uses the estimated topkif aggregation for efficiency. ```kusto ['sample-http-logs'] | summarize topkif(status, 5, method == 'GET') ``` -------------------------------- ### Install Axiom Syslog Proxy from GitHub source Source: https://axiom.co/docs/send-data/syslog-proxy Install the Axiom Syslog Proxy by cloning the GitHub repository and building from source. ```shell git clone https://github.com/axiomhq/axiom-syslog-proxy.git cd axiom-syslog-proxy make install ``` -------------------------------- ### MPL Source Syntax Examples Source: https://axiom.co/docs/mpl/introduction Demonstrates specifying the dataset, metric, and optional time ranges or aliases in MPL queries. ```kusto `otel-demo-metrics`:`go.memory.used`[1h..] ``` ```kusto `otel-demo-metrics`:`go.memory.used`[2h..5m] ``` ```kusto `otel-demo-metrics`:`go.memory.used`[2025-03-01T13:00:00Z..+1h] as mem_usage ``` -------------------------------- ### Get Annotations Source: https://axiom.co/docs/restapi/endpoints/getAnnotations Fetches a list of annotations. You can filter the results by specifying dataset names, a start date, or an end date. The dates should be in RFC3339 format. ```APIDOC ## GET /annotations ### Description Get annotations. This endpoint retrieves a list of annotations, which can be filtered by dataset names, and by a time range (start and end dates). ### Method GET ### Endpoint /annotations ### Parameters #### Query Parameters - **datasets** (array[string]) - Optional - Filter for dataset names. - **start** (string) - Optional - Filter for events after this date. Use RFC3339 time format. - **end** (string) - Optional - Filter for events before this date. Use RFC3339 time format. ### Response #### Success Response (200) - **Annotation** (array) - A list of annotation objects. ### Response Example { "example": "[ { \"datasets\": [\"my-dataset\"], \"description\": \"Deploy new feature to the sales form\", \"endTime\": \"2024-02-06T11:39:28.382Z\", \"id\": \"ann_123\", \"time\": \"2024-02-06T10:39:28.382Z\", \"title\": \"Production deployment\", \"type\": \"deploy\", \"url\": \"https://example.com\" } ]" } ``` -------------------------------- ### Create Experiment Configurations for Model Comparison Source: https://axiom.co/docs/ai-engineering/evaluate/flags-experiments Generate separate configuration files for each model to systematically test capabilities across different AI models. This example creates JSON files for 'gpt-4o-mini', 'gpt-4o', and 'gpt-4-turbo'. ```bash # Create experiment configs for each model echo '{"ticketClassification":{"model":"gpt-4o-mini"}}' > exp-mini.json echo '{"ticketClassification":{"model":"gpt-4o"}}' > exp-4o.json echo '{"ticketClassification":{"model":"gpt-4-turbo"}}' > exp-turbo.json # Run all experiments axiom eval --flags-config=exp-mini.json axiom eval --flags-config=exp-4o.json axiom eval --flags-config=exp-turbo.json ``` -------------------------------- ### APL Query Example Source: https://axiom.co/docs/apl/overview This APL query filters HTTP logs for GET requests with a 200 status, then summarizes the count by time bins and country. ```kusto ['sample-http-logs'] | where method == "GET" and status == "200" | summarize count() by bin_auto(_time), ['geo.country'] ``` -------------------------------- ### OpenAPI Specification for Get Datasets Source: https://axiom.co/docs/restapi/endpoints/getDatasets This OpenAPI 3.0 specification defines the GET /datasets endpoint. It outlines the request method, summary, description, operation ID, and possible responses, including success (200) and error (403) cases. The success response includes an example of the dataset list structure. ```yaml openapi: 3.0.0 info: description: A public and stable API for interacting with axiom services title: Axiom termsOfService: http://axiom.co/terms contact: name: Axiom support team url: https://axiom.co email: hello@axiom.co license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html version: 2.0.0 servers: - url: https://api.axiom.co/v2/ security: - bearerAuth: [] paths: /datasets: get: tags: - Datasets summary: Get list of datasets description: Get list of datasets operationId: getDatasets responses: '200': description: Success content: application/json: schema: type: array items: $ref: '#/components/schemas/Dataset' example: - created: '2020-01-01T00:00:00Z' description: This is an example dataset id: example-dataset name: example-dataset updatedAt: '2020-01-01T00:00:00Z' who: John Doe - created: '2020-02-01T00:00:00Z' description: This is an example dataset id: example-dataset-2 name: example-dataset-2 updatedAt: '2020-02-01T00:00:00Z' who: Foo Bar '403': $ref: '#/components/responses/ForbiddenError' security: - Auth: [] components: schemas: Dataset: type: object required: - id - name - description - created - updatedAt - who - kind properties: canWrite: description: Whether this dataset has write access type: boolean created: description: The RFC3339-formatted time when the dataset was created. type: string format: date-time description: description: Dataset description type: string edgeDeployment: description: Edge deployment of the dataset type: string x-omitempty: true id: description: Dataset ID type: string kind: description: The kind of the dataset type: string default: axiom:events:v1 enum: - otel:metrics:v1 - otel:traces:v1 - otel:logs:v1 - axiom:events:v1 example: axiom:events:v1 mapFields: type: array items: type: string name: description: Unique dataset name type: string retentionDays: description: Number of days to retain data in the dataset type: integer x-omitempty: false sharedByOrg: description: ID of the org that shared this resource, if it's shared type: string updatedAt: description: The RFC3339-formatted time when the dataset was last updated. type: string format: date-time useRetentionPeriod: description: Whether to use the retention period type: boolean x-omitempty: false who: description: Name of the dataset creator type: string example: created: '2022-07-20T02:35:14.137Z' description: string id: string kind: axiom:events:v1 name: string updatedAt: '2022-07-20T02:35:14.137Z' who: string responses: ForbiddenError: description: Forbidden content: application/json: schema: type: object properties: code: type: string message: type: string example: code: 403 message: Forbidden securitySchemes: bearerAuth: type: http scheme: bearer description: >- Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens). Auth: description: >- Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens). type: oauth2 flows: authorizationCode: authorizationUrl: https://accounts.google.com/o/oauth2/v2/auth tokenUrl: https://www.googleapis.com/oauth2/v4/token scopes: {} ``` -------------------------------- ### Install Axiom Python SDK Source: https://axiom.co/docs/llms-full.txt Install the axiom-py package using pip. Choose the appropriate command for your operating system or environment. ```shell python3 -m pip install axiom-py ``` ```shell py -m pip install axiom-py ``` ```shell pip3 install axiom-py ``` -------------------------------- ### APL Equivalent for Splunk SPL Source: https://axiom.co/docs/apl/scalar-functions/string-functions/unicode-codepoints-from-string This APL code provides a concise and efficient way to get Unicode code points, serving as an equivalent to the Splunk SPL example. ```kusto print codepoints = unicode_codepoints_from_string('abc') ``` -------------------------------- ### APL array_slice Use Case Example Source: https://axiom.co/docs/apl/scalar-functions/array-functions/array-slice Filters trace data by slicing the `events` array to analyze a specific range of events using negative indices for start and end. ```kusto ['otel-demo-traces'] | where array_length(events) > 4 | extend sliced_events = array_slice(events, -3, -1) ``` -------------------------------- ### Display Axiom CLI Help Source: https://axiom.co/docs/reference/cli Run this command to view a list of all available commands and their descriptions in the Axiom CLI. ```bash ➜ ~ axiom The power of Axiom on the command-line. USAGE axiom [flags] CORE COMMANDS ingest: Ingest structured data query: Query data using APL stream: Livestream data MANAGEMENT COMMANDS auth: Manage authentication state config: Manage configuration dataset: Manage datasets ADDITIONAL COMMANDS completion: Generate shell completion scripts help: Help about any command version: Print version web: Open Axiom in the browser FLAGS -O, --auth-org-id string Organization ID to use -T, --auth-token string Token to use -C, --config string Path to configuration file to use -D, --deployment string Deployment to use -h, --help Show help for command --no-spinner Disable the activity indicator -v, --version Show axiom version EXAMPLES $ axiom auth login $ axiom version $ cat http-logs.json | axiom ingest http-logs AUTHENTICATION See 'axiom help credentials' for help and guidance on authentication. ENVIRONMENT VARIABLES See 'axiom help environment' for the list of supported environment variables. LEARN MORE Use 'axiom --help' for more information about a command. Read the manual at https://axiom.co/reference/cli ``` -------------------------------- ### ANSI SQL day of year extraction Source: https://axiom.co/docs/apl/scalar-functions/datetime-functions/dayofyear In ANSI SQL, the EXTRACT(DOY FROM timestamp) function is commonly used to get the day of the year. This example shows the standard SQL syntax. ```sql SELECT EXTRACT(DOY FROM timestamp_column) AS day_of_year FROM events; ``` -------------------------------- ### Run Query (Legacy) with Descending Order and Limit Source: https://axiom.co/docs/llms-full.txt Example of a curl request to the legacy Run Query endpoint, specifying start and end times, a limit, and ordering by time in descending order. ```bash curl -X 'POST' 'https://api.axiom.co/v1/datasets/DATASET_NAME/query' \ -H 'Authorization: Bearer API_TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "startTime": "2024-11-30T00:00:00.000Z", "endTime": "2024-11-30T23:59:59.999Z", "limit": 100, "order": [{ "field": "_time", "desc": true }] }' ``` -------------------------------- ### Initialize Wrangler Project Source: https://axiom.co/docs/guides/opentelemetry-cloudflare-workers Initialize a new Wrangler project using the command. ```bash wrangler init --type="javascript" ``` -------------------------------- ### Extract First Letter of City Name Source: https://axiom.co/docs/apl/tabular-operators/extend-valid-operator Use `extend-valid` with `extract` to get the first letter of a city name from the `geo.city` field. The extraction is performed only for valid, alphabetically starting city names. ```kusto ['sample-http-logs'] | extend-valid city_first_letter = extract('^([A-Za-z])', 1, ['geo.city']) ``` -------------------------------- ### Complete Example: Model, Tool, and Span Instrumentation Source: https://axiom.co/docs/ai-engineering/observe/axiom-ai-sdk-instrumentation This example demonstrates how `wrapAISDKModel`, `wrapTool`, and `withSpan` work together. It wraps the AI model client, instruments a tool, and uses `withSpan` to tie everything together under a business capability. ```typescript import { withSpan, wrapAISDKModel, wrapTool } from 'axiom/ai'; import { generateText, tool } from 'ai'; import { createOpenAI } from '@ai-sdk/openai'; import { z } from 'zod'; // 1. Create and wrap the AI model client const openaiProvider = createOpenAI({ apiKey: process.env.OPENAI_API_KEY, }); const gpt4o = wrapAISDKModel(openaiProvider('gpt-4o')); // 2. Define and wrap your tool(s) const findDirectionsTool = wrapTool( 'findDirections', // The tool name must be passed to the wrapper tool({ description: 'Find directions to a location', inputSchema: z.object({ from: z.string(), to: z.string() }), execute: async ({ from, to }) => ({ directions: `To get from ${from} to ${to}, use a teleporter.`, }), }) ); // 3. In your application logic, use `withSpan` to add context // and call the AI model with your wrapped tools. export default async function Page() { const userId = 123; const { text } = await withSpan({ capability: 'get_directions', step: 'generate_ai_response' }, async (span) => { // You have access to the OTel span to add custom attributes span.setAttribute('user_id', userId); return generateText({ model: gpt4o, // Use the wrapped model messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'How do I get from Paris to Berlin?' }, ], tools: { findDirections: findDirectionsTool, // Use the wrapped tool }, }); }); return

{text}

; } ``` -------------------------------- ### Install next-axiom Package Source: https://axiom.co/docs/send-data/nextjs Install the next-axiom package using npm. Ensure you have the necessary environment variables configured for your Axiom dataset and token. ```sh npm install --save next-axiom ``` -------------------------------- ### APL not Example: Identify Non-Standard HTTP Methods Source: https://axiom.co/docs/apl/scalar-functions/mathematical-functions/not Use the 'not' function to filter for HTTP requests that do not use standard GET or HEAD methods. This helps identify potentially suspicious activity. ```kusto ['sample-http-logs'] | extend is_safe_method = (method == 'GET' or method == 'HEAD') | where not(is_safe_method) | project _time, id, status, method, uri ``` -------------------------------- ### Complete Support Ticket Classification Evaluation Source: https://axiom.co/docs/ai-engineering/evaluate/write-evaluations A full evaluation setup including capability definition, custom scorers for category and confidence, and test data. This example demonstrates classifying tickets into predefined categories. ```typescript import { Eval } from 'axiom/ai/evals'; import { Scorer } from 'axiom/ai/scorers'; import { generateObject } from 'ai'; import { openai } from '@ai-sdk/openai'; import { wrapAISDKModel } from 'axiom/ai'; import { z } from 'zod'; // The capability function async function classifyTicket({ subject, content }: { subject?: string; content: string }) { const result = await generateObject({ model: wrapAISDKModel(openai('gpt-4o-mini')), messages: [ { role: 'system', content: `You are a customer support engineer. Classify tickets as: spam, question, feature_request, or bug_report.`, }, { role: 'user', content: subject ? `Subject: ${subject}\n\n${content}` : content, }, ], schema: z.object({ category: z.enum(['spam', 'question', 'feature_request', 'bug_report']), confidence: z.number().min(0).max(1), }), }); return result.object; } ``` ```typescript // Custom scorer for category matching const CategoryScorer = Scorer( 'category-match', ({ output, expected }) => { return output.category === expected.category ? true : false; } ); // Custom scorer for high-confidence predictions const ConfidenceScorer = Scorer( 'high-confidence', ({ output }) => { return output.confidence >= 0.8 ? true : false; } ); // Define the evaluation Eval('spam-classification', { data: [ { input: { subject: "Congratulations! You've Won!", content: 'Claim your $500 gift card now!', }, expected: { category: 'spam', }, }, { input: { subject: 'How do I reset my password?', content: 'I forgot my password and need help resetting it.', }, expected: { category: 'question', }, }, { input: { subject: 'Feature request: Dark mode', content: 'Would love to see a dark mode option in the app.', }, expected: { category: 'feature_request', }, }, { input: { subject: 'App crashes on startup', content: 'The app crashes immediately when I try to open it.', }, expected: { category: 'bug_report', }, }, ], task: async ({ input }) => { return await classifyTicket(input); }, scorers: [CategoryScorer, ConfidenceScorer], metadata: { description: 'Classify support tickets into categories', }, }); ``` -------------------------------- ### Build and Run .NET App Source: https://axiom.co/docs/guides/send-logs-from-dotnet Builds and runs the .NET project. Ensure you are in the project directory. ```bash dotnet build dotnet run ``` -------------------------------- ### Initialize a Go Module Source: https://axiom.co/docs/guides/opentelemetry-go Creates a go.mod file to track your project's dependencies. Replace with your project's name or GitHub repository path. ```bash go mod init ``` -------------------------------- ### Filter for Specific Status Codes in APL Source: https://axiom.co/docs/apl/guides/migrating-from-sumologic-to-apl Filters logs where the content type starts with 'text/css' and the status code is exactly '200'. Note: This example appears to have a mismatch between the description and the code's filtering logic. ```kusto ['sample-http-logs'] | where content_type startswith 'text/css' | extend p = ("HTTP/1.1\" * * \") | where status == "200" ```