POST
/
v2
/
logs
/
span
const API_KEY = "my_workspace_api_key";
const PROMPT_ID = "my_prompt_id";
const PROJECT_ID = "my_project_id";
const TRACE_ID = "my_trace_id";
const BASE_URL = "https://api.adaline.ai/v2/logs";

async function createLogSpan(span) {
  const response = await fetch(`${BASE_URL}/span`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      projectId: PROJECT_ID,
      span,
    }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`API Error: ${error.error}`);
  }

  return response.json();
}

async function main() {
  try {
    const spanResult = await createLogSpan({
      promptId: PROMPT_ID,
      traceId: TRACE_ID,
      startedAt: Date.now(),
      endedAt: Date.now() + 30000,
      name: "llm_call",
      status: "success",
      content: {
        "type": "Model",
        "provider": "openai",
        "model": "gpt-4o-mini",
        "variables": {
          "user_input": {
            "modality": "text",
            "value": "librarian"
          }
        },
        "cost": 0.002,
        "input": "{\n    \"model\":\"gpt-4o-mini\",\n    \"max_tokens\": 50,\n    \"messages\": [{\n      \"role\": \"system\",\n      \"content\": [\n        {\n            \"type\": \"text\",\n            \"text\": \"You are a helpful librarian. You answer in 1-2 lines.\"\n        }\n      ]\n    },\n    {\n      \"role\": \"user\",\n      \"content\": [\n        {\n          \"type\": \"text\",\n          \"text\": \"What is Adaline?\"\n        }\n      ]\n    }\n  ]\n}",
        "output": "{\n    \"id\": \"chatcmpl-BjKjQqVBN0WdTbkFHZ2C6tLXerKvl\",\n    \"object\": \"chat.completion\",\n    \"created\": 1750144152,\n    \"model\": \"gpt-4o-mini-2024-07-18\",\n    \"choices\": [\n        {\n            \"index\": 0,\n            \"message\": {\n                \"role\": \"assistant\",\n                \"content\": \"Adaline, or Adaptive Linear Neuron, is a type of artificial neural network that uses a linear activation function and employs the least mean squares (LMS) algorithm for training, aiming to minimize the difference between predicted and actual outputs.\",\n                \"refusal\": null,\n                \"annotations\": []\n            },\n            \"logprobs\": null,\n            \"finish_reason\": \"stop\"\n        }\n    ],\n    \"usage\": {\n        \"prompt_tokens\": 31,\n        \"completion_tokens\": 47,\n        \"total_tokens\": 78,\n        \"prompt_tokens_details\": {\n            \"cached_tokens\": 0,\n            \"audio_tokens\": 0\n        },\n        \"completion_tokens_details\": {\n            \"reasoning_tokens\": 0,\n            \"audio_tokens\": 0,\n            \"accepted_prediction_tokens\": 0,\n            \"rejected_prediction_tokens\": 0\n        }\n    },\n    \"service_tier\": \"default\",\n    \"system_fingerprint\": \"fp_34a54ae93c\"\n}"
      },
      referenceId: "span_004",
      sessionId: "session_123",
      attributes: {
        "app_name": "my_app",
        "user_id": "user_123"
      },
      tags: ["dev-env"]
    });

    console.log("spanResult:", spanResult);
  } catch (error) {
    console.error("Error creating span:", error);
  }
}

main();
{
  "spanId":"5066102c-f90a-4a36-9cf0-4ea7759107b8"
}

Request

Authorization
string
required

Bearer Token Authentication

All API requests must include a valid workspace API key in the Authorization header using the Bearer token format.

Authorization: Bearer YOUR_WORKSPACE_API_KEY

You can create your workspace API key in Adaline by visiting Settings > API Keys.

Body

projectId
string
required

The unique identifier of the project.

span
object
required

The span object containing span details.

span.startedAt
number
required

Unix timestamp when the span started.

span.endedAt
number
required

Unix timestamp when the span ended.

span.name
string
required

Name/identifier for the span.

span.status
string
required

Status of the span (one of: “success”, “failure”, “unknown”).

span.content
string
required

The content must be a valid JSON string with a type field that determines the structure. Supported types include:

Model Type

For AI model interactions (LLM calls, completions, etc.):

{
  "type": "Model",
  "provider": "openai",
  "model": "gpt-4o-mini",
  "variables": {
    "user_input": {
      "modality": "text",
      "value": "librarian"
    }
  },
  "cost": 0.002,
  "input": "{\"messages\": [{\"role\": \"user\", \"content\": [{\"modality\": \"text\", \"value\": \"You are a helpful {{user_input}}. You answer in 1-2 lines.\"}]}]}",
  "output": "{\"messages\": [{\"role\": \"assistant\", \"content\": [{\"modality\": \"text\", \"value\": \"Hello! How can I help you today?\"}]}]}",
}

Required Fields:

  • type: String identifying the span type
  • provider: String identifying the provider of the model
  • model: String identifying the model
  • input: JSON string containing input data, either exactly the payload sent to the LLM provider (using REST API) or using Adaline types.
  • output: JSON string containing output data, either exactly the response received from the LLM provider (using REST API) or using Adaline types.

If using Adaline types:

If using Adaline types:

  • output.messages: refer to MessageType.
  • output.tokenUsage.promptTokens: Number of tokens used for the prompt.
  • output.tokenUsage.completionTokens: Number of tokens used for the completion.
  • output.tokenUsage.totalTokens: Total number of tokens used.

If using LLM provider REST API payload, refer this example using OpenAI chat completion API payload:

{
  "type": "Model",
  "provider": "openai",
  "model": "gpt-4o-mini",
  "variables": {
    "user_input": {
      "modality": "text",
      "value": "librarian"
    }
  },
  "cost": 0.002,
  "input": "{\n    \"model\":\"gpt-4o-mini\",\n    \"max_tokens\": 50,\n    \"messages\": [{\n      \"role\": \"system\",\n      \"content\": [\n        {\n            \"type\": \"text\",\n            \"text\": \"You are a helpful librarian. You answer in 1-2 lines.\"\n        }\n      ]\n    },\n    {\n      \"role\": \"user\",\n      \"content\": [\n        {\n          \"type\": \"text\",\n          \"text\": \"What is Adaline?\"\n        }\n      ]\n    }\n  ]\n}",
  "output": "{\n    \"id\": \"chatcmpl-BjKjQqVBN0WdTbkFHZ2C6tLXerKvl\",\n    \"object\": \"chat.completion\",\n    \"created\": 1750144152,\n    \"model\": \"gpt-4o-mini-2024-07-18\",\n    \"choices\": [\n        {\n            \"index\": 0,\n            \"message\": {\n                \"role\": \"assistant\",\n                \"content\": \"Adaline, or Adaptive Linear Neuron, is a type of artificial neural network that uses a linear activation function and employs the least mean squares (LMS) algorithm for training, aiming to minimize the difference between predicted and actual outputs.\",\n                \"refusal\": null,\n                \"annotations\": []\n            },\n            \"logprobs\": null,\n            \"finish_reason\": \"stop\"\n        }\n    ],\n    \"usage\": {\n        \"prompt_tokens\": 31,\n        \"completion_tokens\": 47,\n        \"total_tokens\": 78,\n        \"prompt_tokens_details\": {\n            \"cached_tokens\": 0,\n            \"audio_tokens\": 0\n        },\n        \"completion_tokens_details\": {\n            \"reasoning_tokens\": 0,\n            \"audio_tokens\": 0,\n            \"accepted_prediction_tokens\": 0,\n            \"rejected_prediction_tokens\": 0\n        }\n    },\n    \"service_tier\": \"default\",\n    \"system_fingerprint\": \"fp_34a54ae93c\"\n}"
}

Optional Fields:

  • cost: Number representing the cost of the span (in USD)
  • variables: JSON object containing variable values. key is the variable name and value is the variable value of type ContentType.

Function Type

For function calls and executions:

{
  "type": "Function",
  "input": "{\"function_name\": \"calculate_sum\", \"args\": [1, 2, 3]}",
  "output": "{\"result\": 6}"
}

Tool Type

For tool usage and API calls:

{
  "type": "Tool",
  "input": "{\"tool\": \"weather_api\", \"location\": \"San Francisco\"}",
  "output": "{\"temperature\": 72, \"condition\": \"sunny\"}"
}

Guardrail Type

For safety and validation checks:

{
  "type": "Guardrail",
  "input": "{\"content\": \"User message to validate\", \"rules\": [\"no_pii\", \"content_safety\"]}",
  "output": "{\"passed\": true, \"violations\": []}"
}

Retrieval Type

For document retrieval and search operations:

{
  "type": "Retrieval",
  "input": "{\"query\": \"machine learning best practices\", \"top_k\": 5}",
  "output": "{\"documents\": [{\"id\": \"doc1\", \"score\": 0.95, \"content\": \"...\"}]}"
}

Embeddings Type

For text embedding operations:

{
  "type": "Embeddings",
  "input": "{\"text\": \"Convert this text to embeddings\", \"model\": \"text-embedding-ada-002\"}",
  "output": "{\"embeddings\": [0.1, 0.2, 0.3, ...], \"dimensions\": 1536}"
}

Other Type

For custom span types not covered by the predefined categories:

{
  "type": "Other",
  "input": "{\"custom_field\": \"value\"}",
  "output": "{\"result\": \"success\"}"
}

Required Fields (for all span types other than ‘Model’):

  • type: String identifying the span type
  • input: JSON string containing input data
  • output: JSON string containing output data

Notes:

  • Maximum content size is 1MB
span.traceId
string

The ID of an existing trace (required if traceReferenceId not provided).

span.traceReferenceId
string

The reference ID of an existing trace (required if traceId not provided). This is usually the traceId used within your application / system.

span.promptId
string

The unique identifier of the prompt used. If not provided, you will not be able to view the span in prompt’s monitor section.

span.deploymentId
string

The deployment ID used for this span.

span.runEvaluation
boolean

Whether to run evaluation on this span.

span.parentReferenceId
string

Reference ID of the parent span. This is usually this span’s parent’s spanId used within your application / system.

span.referenceId
string

External reference ID for the span. This is usually the spanId used within your application / system.

span.sessionId
string

Session ID associated with the span. This is usually the sessionId / threadId / chatId used within your application / system.

span.attributes
object

Additional attributes for the span. Key-value pairs of attributes. Keys must be strings, values must be strings, numbers, or booleans.

span.tags
array

Array of tags for categorization. Each tag must be a string.

Response

spanId
array

Array of unique identifiers for the created span.

const API_KEY = "my_workspace_api_key";
const PROMPT_ID = "my_prompt_id";
const PROJECT_ID = "my_project_id";
const TRACE_ID = "my_trace_id";
const BASE_URL = "https://api.adaline.ai/v2/logs";

async function createLogSpan(span) {
  const response = await fetch(`${BASE_URL}/span`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      projectId: PROJECT_ID,
      span,
    }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`API Error: ${error.error}`);
  }

  return response.json();
}

async function main() {
  try {
    const spanResult = await createLogSpan({
      promptId: PROMPT_ID,
      traceId: TRACE_ID,
      startedAt: Date.now(),
      endedAt: Date.now() + 30000,
      name: "llm_call",
      status: "success",
      content: {
        "type": "Model",
        "provider": "openai",
        "model": "gpt-4o-mini",
        "variables": {
          "user_input": {
            "modality": "text",
            "value": "librarian"
          }
        },
        "cost": 0.002,
        "input": "{\n    \"model\":\"gpt-4o-mini\",\n    \"max_tokens\": 50,\n    \"messages\": [{\n      \"role\": \"system\",\n      \"content\": [\n        {\n            \"type\": \"text\",\n            \"text\": \"You are a helpful librarian. You answer in 1-2 lines.\"\n        }\n      ]\n    },\n    {\n      \"role\": \"user\",\n      \"content\": [\n        {\n          \"type\": \"text\",\n          \"text\": \"What is Adaline?\"\n        }\n      ]\n    }\n  ]\n}",
        "output": "{\n    \"id\": \"chatcmpl-BjKjQqVBN0WdTbkFHZ2C6tLXerKvl\",\n    \"object\": \"chat.completion\",\n    \"created\": 1750144152,\n    \"model\": \"gpt-4o-mini-2024-07-18\",\n    \"choices\": [\n        {\n            \"index\": 0,\n            \"message\": {\n                \"role\": \"assistant\",\n                \"content\": \"Adaline, or Adaptive Linear Neuron, is a type of artificial neural network that uses a linear activation function and employs the least mean squares (LMS) algorithm for training, aiming to minimize the difference between predicted and actual outputs.\",\n                \"refusal\": null,\n                \"annotations\": []\n            },\n            \"logprobs\": null,\n            \"finish_reason\": \"stop\"\n        }\n    ],\n    \"usage\": {\n        \"prompt_tokens\": 31,\n        \"completion_tokens\": 47,\n        \"total_tokens\": 78,\n        \"prompt_tokens_details\": {\n            \"cached_tokens\": 0,\n            \"audio_tokens\": 0\n        },\n        \"completion_tokens_details\": {\n            \"reasoning_tokens\": 0,\n            \"audio_tokens\": 0,\n            \"accepted_prediction_tokens\": 0,\n            \"rejected_prediction_tokens\": 0\n        }\n    },\n    \"service_tier\": \"default\",\n    \"system_fingerprint\": \"fp_34a54ae93c\"\n}"
      },
      referenceId: "span_004",
      sessionId: "session_123",
      attributes: {
        "app_name": "my_app",
        "user_id": "user_123"
      },
      tags: ["dev-env"]
    });

    console.log("spanResult:", spanResult);
  } catch (error) {
    console.error("Error creating span:", error);
  }
}

main();
{
  "spanId":"5066102c-f90a-4a36-9cf0-4ea7759107b8"
}

Span Creation Validation Rules

  1. Trace Association: Either traceId or traceReferenceId must be provided
  2. Time Validation: startedAt must be before endedAt
  3. Content Size: Content must not exceed 1MB when serialized to JSON

Best Practices

  1. Structured Logging: Use consistent naming conventions for traces and spans to enable better analysis.

  2. Reference IDs: Use meaningful reference IDs that can be tracked across your application for better debugging.

  3. Content Size Management: Monitor your content size to stay within the 1MB limit per span.

  4. Batch Operations: When possible, use the trace endpoint to create multiple spans in a single request.

  5. Time Accuracy: Ensure timestamps are accurate and represent the actual start/end times of operations.

  6. Meaningful Attributes: Use attributes and tags to add context that will be useful for analysis and debugging.

  7. Session Tracking: Use session IDs consistently to track user sessions across multiple traces.