### Example Pricing Configuration (JSON) Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint Shows how to configure custom pricing per 1 million tokens for prompt and completion units. This is applicable for self-hosted or fine-tuned models. ```json "prompt_unit_price": 0.0042 // $0.0042 per 1M tokens ``` ```json "completion_unit_price": 0.0042 // $0.0042 per 1M tokens ``` -------------------------------- ### Run Multi-Provider Tracing Example (Bash) Source: https://docs.keywordsai.co/tracing-sdk-js/examples This command executes the TypeScript example for multi-provider tracing using tsx. Ensure you have Node.js and npm installed, and the necessary environment variables (KEYWORDSAI_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY) are set. ```bash npx tsx multi_provider.ts ``` -------------------------------- ### Complete Example: Async Instructor with KeywordsAI Tracing Source: https://docs.keywordsai.co/integration/development-frameworks/tracing/instructor A comprehensive example demonstrating the integration of async Instructor with KeywordsAI tracing. It includes initialization, client setup, model definition, and a runnable workflow, highlighting the ease of adding tracing. ```python """ Simple Async Instructor + KeywordsAI Tracing Example This example shows how easy it is to add KeywordsAI tracing to your async Instructor workflows. Just 3 lines of setup, then your structured outputs are automatically traced! """ import asyncio import os from pydantic import BaseModel, Field import instructor from openai import AsyncOpenAI from keywordsai_tracing import KeywordsAITelemetry, Instruments from keywordsai_tracing.decorators import task from dotenv import load_dotenv load_dotenv() # 1️⃣ Initialize KeywordsAI tracing (one line!) k_tl = KeywordsAITelemetry( app_name="async-instructor-demo", instruments={Instruments.OPENAI} ) # 2️⃣ Set up your async Instructor client (your existing code) async_client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY")) instructor_client = instructor.from_openai(async_client) # 3️⃣ Define your Pydantic models (your existing code) class User(BaseModel): name: str = Field(description="Full name") age: int = Field(description="Age in years") email: str = Field(description="Email address") role: str = Field(description="Job title") ``` -------------------------------- ### Install Keywords AI Python SDK Source: https://docs.keywordsai.co/python-sdk/quickstart Install the Keywords AI Python SDK using pip. This is the first step to integrate Keywords AI functionalities into your Python projects. ```bash pip install keywordsai ``` -------------------------------- ### Example Timestamp Configuration (JSON) Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint Demonstrates how to set the ISO 8601 timestamp for when a request completed. This is useful for logging and tracking request times. ```json "timestamp": "2025-01-01T10:30:00Z" ``` -------------------------------- ### Example Customer Parameters JSON Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint Provides an example of extended customer information using the `customer_params` field. This allows for a more comprehensive set of customer details, including identifier, name, and email, for advanced analytics. ```json { "customer_params": { "customer_identifier": "customer_123", "name": "John Doe", "email": "john.doe@example.com" } } ``` -------------------------------- ### Start Development Server with pnpm or yarn Source: https://docs.keywordsai.co/integration/development-frameworks/tracing/vercel-tracing These commands initiate your local development server using either pnpm or yarn as your package manager. Ensure your project dependencies are correctly installed before running these commands. ```bash pnpm dev ``` ```bash yarn dev ``` -------------------------------- ### Model Comparison Experiment Setup (Python) Source: https://docs.keywordsai.co/python-sdk/experiments/create This example shows how to create an experiment specifically for comparing the performance of different language models. It defines variants for each model (e.g., GPT-4, Claude) and specifies the metrics to be tracked, such as response quality and cost. ```python # Create experiment to compare different models experiment = client.experiments.create( name="Model Performance Comparison", description="Comparing GPT-4 vs Claude for customer support", variants=[ { "name": "gpt4", "model": "gpt-4", "prompt_id": "prompt_123", "description": "GPT-4 with standard prompt" }, { "name": "claude", "model": "claude-3", "prompt_id": "prompt_123", "description": "Claude-3 with same prompt" } ], metrics=[ "response_quality", "response_time", "cost_per_request", "user_satisfaction" ] ) print(f"Model comparison experiment: {experiment['id']}") ``` -------------------------------- ### Example Usage Metrics JSON Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint Demonstrates the structure of usage metrics for an LLM request, including prompt tokens, completion tokens, and total tokens. This helps in monitoring and analyzing token consumption. ```json { "usage": { "prompt_tokens": 150, "completion_tokens": 85, "total_tokens": 235, "prompt_tokens_details": { "cached_tokens": 10 } } } ``` -------------------------------- ### Azure OpenAI Integration via Keywords AI (Setup & Python) Source: https://docs.keywordsai.co/integration/development-frameworks/llm_framework/openai/openai-sdk Provides instructions and a Python code example for configuring and using Azure OpenAI models through the Keywords AI platform. This involves adding Azure credentials in the Keywords AI provider settings and then using the Keywords AI endpoint with Azure models. The setup requires configuring credentials and deployment settings on the Keywords AI platform. ```plain 1. Go to [Keywords AI Providers](https://platform.keywordsai.co/platform/api/providers) 2. Add your Azure OpenAI credentials 3. Configure your Azure deployment settings 4. Use Azure models through the same Keywords AI endpoint ``` ```python from openai import AsyncOpenAI # Use the same Keywords AI endpoint azure_client = AsyncOpenAI( api_key="YOUR_KEYWORDS_AI_API_KEY", base_url="https://api.keywordsai.co/api/" ) # Call Azure models directly response = await azure_client.chat.completions.create( model="gpt-4o", # Azure-hosted model messages=[{"role": "user", "content": "Hello from Azure!"}], ) ``` -------------------------------- ### Start Development Server Source: https://docs.keywordsai.co/integration/tracing/vercel-tracing These commands show how to start a local development server using different package managers (pnpm, yarn, npm, bun). This is a prerequisite for verifying traces in Keywords AI. ```bash pnpm dev ``` ```bash yarn dev ``` ```bash npm run dev ``` ```bash bun dev ``` -------------------------------- ### Run Advanced Tracing Example (Bash) Source: https://docs.keywordsai.co/tracing-sdk-js/examples Command to execute the advanced tracing TypeScript example using Node.js and tsx. This command assumes you have Node.js and tsx installed globally or in your project. ```bash npx tsx advanced_tracing.ts ``` -------------------------------- ### Install Dependencies with pnpm Source: https://docs.keywordsai.co/integration/development-frameworks/tracing/mastra Installs project dependencies using the pnpm package manager. This is a prerequisite for running the Mastra Weather Agent example. ```bash pnpm install ``` -------------------------------- ### Hello World Example with Keywords AI Tracing Source: https://docs.keywordsai.co/integration/development-frameworks/openai-agent A basic 'Hello World' example demonstrating the OpenAI Agents SDK with Keywords AI tracing. It sets up an agent that responds in haikus and traces the interaction. ```python from dotenv import load_dotenv load_dotenv(override=True) import pytest # ==========copy paste below========== import asyncio import os from agents import Agent, Runner from agents.tracing import set_trace_processors, trace from keywordsai_exporter_openai_agents import KeywordsAITraceProcessor set_trace_processors( [ KeywordsAITraceProcessor( api_key=os.getenv("KEYWORDSAI_API_KEY"), endpoint=os.getenv("KEYWORDSAI_OAIA_TRACING_ENDPOINT"), ), ] ) @pytest.mark.asyncio async def test_main(): agent = Agent( name="Assistant", instructions="You only respond in haikus.", ) with trace("Hello world test"): result = await Runner.run(agent, "Tell me about recursion in programming.") print(result.final_output) # Function calls itself, # Looping in smaller pieces, # Endless by design. if __name__ == "__main__": asyncio.run(test_main()) ``` -------------------------------- ### Get Experiment Logs Summary (Python & cURL) Source: https://docs.keywordsai.co/api-endpoints/develop/experiments-v2/logs-summary Demonstrates how to fetch experiment logs summary using both Python with the requests library and cURL. Includes examples for both GET requests and POST requests with filtering. ```python import requests experiment_id = "experiment_id_123" url = f"https://api.keywordsai.co/api/v2/experiments/{experiment_id}/logs/summary/" headers = { "Authorization": "Bearer YOUR_API_KEY" } # GET request response = requests.get(url, headers=headers) print(response.json()) # POST request with filtering data = { "filters": [ { "field": "status", "operator": "=", "value": "completed" } ] } response = requests.post(url, headers=headers, json=data) print(response.json()) ``` ```bash # GET request curl -X GET "https://api.keywordsai.co/api/v2/experiments/{experiment_id}/logs/summary/" \ -H "Authorization: Bearer YOUR_API_KEY" # POST request with filtering curl -X POST "https://api.keywordsai.co/api/v2/experiments/{experiment_id}/logs/summary/" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "filters": [ { "field": "status", "operator": "=", "value": "completed" } ] }' ``` -------------------------------- ### Create Next.js App with KeywordsAI Example (npm, yarn, pnpm) Source: https://docs.keywordsai.co/integration/development-frameworks/tracing/vercel-tracing Bootsrap a new Next.js application pre-configured with KeywordsAI example projects using npm, yarn, or pnpm. This command clones the specified GitHub repository and sets up the project structure. ```bash npx create-next-app --example https://github.com/Keywords-AI/keywordsai-example-projects/tree/main/vercel_ai_next_openai my-keywordsai-app ``` ```bash yarn create next-app --example https://github.com/Keywords-AI/keywordsai-example-projects/tree/main/vercel_ai_next_openai my-keywordsai-app ``` ```bash pnpm create next-app --example https://github.com/Keywords-AI/keywordsai-example-projects/tree/main/vercel_ai_next_openai my-keywordsai-app ``` -------------------------------- ### Create Prompt API Client using Convenience Function Source: https://docs.keywordsai.co/python-sdk/prompts/create Shows how to use the `create_prompt_client` convenience function to instantiate the `PromptAPI` client. This simplifies the client creation process, especially when providing the API key. ```python from keywordsai import create_prompt_client client = create_prompt_client(api_key="your-api-key") response = client.create() ``` -------------------------------- ### Log Workflow Input Example Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint This JSON snippet shows an example of the 'input' field for logging a workflow or task execution. It can accommodate any JSON-serializable structure, such as a query with context. ```json "input": "{\"query\":\"Help with order #12345\",\"context\":{\"user_id\":\"123\"}}" ``` -------------------------------- ### Log Chat Completion Output Example Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint This JSON snippet provides an example of the 'output' field for a chat completion. It represents the assistant's response, including its role and content. ```json "output": "{\"role\":\"assistant\",\"content\":\"Hello! How can I help you?\"}" ``` -------------------------------- ### Configure Generation Parameters with Python Source: https://docs.keywordsai.co/integration/development-frameworks/llm_framework/google_genai This example shows how to configure model behavior using `GenerateContentConfig`, setting parameters like temperature, top_k, top_p, and max_output_tokens for more controlled responses. ```python from google.GenAI import types config = types.GenerateContentConfig( temperature=0.9, top_k=1, top_p=1, max_output_tokens=2048, ) response = client.models.generate_content( model="gemini-2.5-flash", contents="What is the capital of France?", config=config, ) ``` -------------------------------- ### Demonstrate Logger Inheritance and Levels (Python) Source: https://docs.keywordsai.co/tracing-sdk/examples This Python example illustrates logger inheritance and level settings within the KeywordsAI logging framework. It shows how to get parent and child loggers and set their levels, affecting log message propagation. ```python import logging from keywordsai_tracing.constants import LOGGER_NAME parent_logger = logging.getLogger(LOGGER_NAME) child1_logger = logging.getLogger(f"{LOGGER_NAME}.core.exporter") child2_logger = logging.getLogger(f"{LOGGER_NAME}.core.client") parent_logger.setLevel(logging.DEBUG) ``` -------------------------------- ### List Customers with Query Parameters Source: https://docs.keywordsai.co/api-endpoints/observe/users/user-creation-endpoint This example demonstrates how to list customers using query parameters for pagination, sorting, and environment filtering. It shows how to construct the URL with the desired parameters. ```URL https://api.keywordsai.co/api/users/list/?page=1&page_size=50&sort_by=-first_seen&environment=prod ``` -------------------------------- ### Example URL-based Filtering for Logs Summary Source: https://docs.keywordsai.co/api-endpoints/observe/logs/logs-summary-endpoint These bash examples illustrate how to use URL parameters for quick filtering of logs summaries. You can filter by customer identifier or custom metadata fields like user tier and department. ```bash # Filter summary by customer GET /api/request-logs/summary/?customer_identifier=user_123 # Filter by custom metadata GET /api/request-logs/summary/?user_tier=premium&department=sales ``` -------------------------------- ### Run Basic Usage TypeScript Example Source: https://docs.keywordsai.co/tracing-sdk-js/examples Executes the basic usage TypeScript example using tsx. This command will run the `basic_usage.ts` file, demonstrating the KeywordsAI Tracing SDK's core functionalities. ```bash npx tsx basic_usage.ts ``` -------------------------------- ### Get OpenTelemetry Tracer for Manual Span Creation (Python) Source: https://docs.keywordsai.co/tracing-sdk/client/get-tracer Access the OpenTelemetry tracer to manually create spans when decorators are insufficient. This involves getting the client and then the tracer from it. The tracer can then be used to start and manage spans, setting attributes as needed. ```python from keywordsai_tracing import get_client client = get_client() tracer = client.get_tracer() with tracer.start_as_current_span("custom_operation") as span: span.set_attribute("custom.key", "value") pass ``` -------------------------------- ### Basic Synchronous Prompt Creation with Environment Variables Source: https://docs.keywordsai.co/python-sdk/prompts/create A basic example of creating a prompt synchronously using the `PromptAPI`. It loads the API key from environment variables using `dotenv` and includes error handling for the creation process. ```python import os from dotenv import load_dotenv from keywordsai.prompts.api import PromptAPI load_dotenv() def create_prompt_sync(): """Basic synchronous prompt creation""" api_key = os.getenv("KEYWORDS_AI_API_KEY") prompt_api_client = PromptAPI(api_key=api_key) try: response = prompt_api_client.create() print(f"✓ Prompt created with ID: {response.id}") print(f" Name: {response.name}") print(f" Created at: {response.created_at}") return response except Exception as e: print(f"✗ Error: {e}") return None # Usage create_prompt_sync() ``` -------------------------------- ### Full example: OpenAI integration with Keywords AI header (TypeScript) Source: https://docs.keywordsai.co/integration/development-frameworks/llm_framework/vercel This comprehensive example shows a complete integration of Keywords AI parameters with the Vercel AI SDK for an OpenAI client. It includes setting up the client, defining messages, and streaming the response, demonstrating the full workflow. ```typescript import { streamText, streamObject } from "ai"; import { createOpenAI } from "@ai-sdk/openai"; const keywordsAIHeaderContent = { "customer_identifier": "test_customer_identifier_from_header" } const encoded = Buffer.from(JSON.stringify(keywordsAIHeaderContent)).toString('base64'); const client = createOpenAI({ baseURL: process.env.KEYWORDSAI_ENDPOINT_LOCAL, apiKey: process.env.KEYWORDSAI_API_KEY_TEST, compatibility: "strict", headers: { "X-Data-Keywordsai-Params": encoded } }); const requestParamsDefault: Parameters[0] = { model: client.chat("gpt-4o"), messages: [ { role: "user", content: "Hello! How are you doing today?", }, ], temperature: 0.5, }; try { console.log("Calling OpenAI with Keywords proxy..."); const { textStream: proxyTextStream } = await streamText( requestParamsDefault ); for await (const textPart of proxyTextStream) { console.log("Keywords Proxy Response:", textPart); } } catch (error) { console.error("Error:", error); } ``` -------------------------------- ### Log Embedding Output Example Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint This JSON snippet illustrates the 'output' field for an embedding request, which is typically an array of numerical vector embeddings. ```json "output": "[0.123, -0.456, 0.789, ...]" ``` -------------------------------- ### Filter by Customer Identifier (Bash) Source: https://docs.keywordsai.co/api-endpoints/observe/logs/logs-list-endpoint This example demonstrates how to filter request logs by a specific customer identifier using a GET request. It's a basic filtering operation on a known log field. ```bash GET /api/request-logs/list/?customer_identifier=user_123 ``` -------------------------------- ### Example Log Structure (JSON) Source: https://docs.keywordsai.co/get-started/observability_data_model Demonstrates the structure of a typical log entry, including universal fields, legacy fields for backward compatibility, and various metrics like tokens, cost, and latency. The input and output fields show the data format for LLM interactions. ```json { "id": "log_123", "log_type": "chat", "model": "gpt-4", // Universal fields (always present) "input": "[\"{\"role\": \"user\", \"content\": \"What is the capital of France?\"}]", "output": "{\"role\": \"assistant\", \"content\": \"The capital of France is Paris.\"}", // Extracted legacy fields (for backward compatibility) "prompt_messages": [ {"role": "user", "content": "What is the capital of France?"} ], "completion_message": { "role": "assistant", "content": "The capital of France is Paris." }, // Metrics "prompt_tokens": 8, "completion_tokens": 7, "total_tokens": 15, "cost": 0.0003, "latency": 1.2, "timestamp": "2024-01-15T10:30:00Z", "status": "success" } ``` -------------------------------- ### Example Customer Identifier JSON Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint Shows a simple JSON structure for identifying a customer making a request. This is useful for visualizing user activities and performing user-specific analysis. ```json "customer_identifier": "user_123" ``` -------------------------------- ### Make a Basic Content Generation Request in Python Source: https://docs.keywordsai.co/integration/development-frameworks/llm_framework/google_genai This example demonstrates how to make a simple content generation request to a specified Gemini model using the initialized client. It prints the text response. ```python response = client.models.generate_content( model="gemini-2.5-flash", contents="Hello, world!", ) print(response.text) ``` -------------------------------- ### Log Request Body Model Example Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint This JSON snippet shows how to specify the 'model' field in a log request, which is optional but recommended for identifying the LLM used for inference. ```json "model": "gpt-4o-mini" ``` -------------------------------- ### Run OpenAI Integration TypeScript Example Source: https://docs.keywordsai.co/tracing-sdk-js/examples Executes the OpenAI integration TypeScript example using tsx. This command runs the `openai_integration.ts` file, demonstrating how the KeywordsAI Tracing SDK traces calls to the OpenAI API. ```bash npx tsx openai_integration.ts ``` -------------------------------- ### Example API Controls Configuration (JSON) Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint Illustrates how to control the behavior of the Keywords AI logging API, specifically the 'block' parameter which determines if the server waits for log completion. ```json { "keywordsai_api_controls": { "block": true } } ``` -------------------------------- ### Set Up Async Instructor Client Source: https://docs.keywordsai.co/integration/development-frameworks/tracing/instructor Configures an asynchronous client for Instructor, integrating with OpenAI's API. This client is used for making LLM calls with structured output models. ```python import instructor from openai import AsyncOpenAI # Set up your async Instructor client async_client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY")) instructor_client = instructor.from_openai(async_client) ``` -------------------------------- ### Log Embedding Input Example Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint This JSON snippet illustrates the 'input' field format for logging an embedding request. It typically contains a text string or an array of strings to be embedded. ```json "input": "Keywords AI is an LLM observability platform" ``` -------------------------------- ### Export Experiment Logs via GET Request (Python) Source: https://docs.keywordsai.co/api-endpoints/develop/experiments-v2/logs-export This Python snippet demonstrates how to initiate an experiment log export using a GET request. It includes setting up the request URL, headers for authentication, and query parameters for filtering by time range and triggering the export. The response indicates the export process has started. ```python import requests experiment_id = "experiment_id_123" url = f"https://api.keywordsai.co/api/v2/experiments/{experiment_id}/logs/" headers = { "Authorization": "Bearer YOUR_API_KEY" } # GET request with export parameter params = { "export": "1", "start_time": "2025-01-01T00:00:00Z", "end_time": "2025-01-31T23:59:59Z" } response = requests.get(url, headers=headers, params=params) print(response.json()) ``` -------------------------------- ### Advanced Configuration for Gemini Models in Python Source: https://docs.keywordsai.co/integration/development-frameworks/llm_framework/google_genai This comprehensive example demonstrates advanced configuration options for the Gemini API, including system instructions, sampling parameters, output controls, tools for grounding, and safety settings. ```python from google import GenAI from google.GenAI import types import os client = GenAI.Client( api_key=os.environ.get("KEYWORDSAI_API_KEY"), http_options={ "base_url": "https://api.keywordsai.co/api/google/gemini", } ) # Example: Configure tools for grounding grounding_tool = types.Tool( google_search=types.GoogleSearch() ) # Example: Comprehensive GenerateContentConfig showcasing various parameters config = types.GenerateContentConfig( # System instruction to guide the model's behavior system_instruction="You are a helpful assistant that provides accurate, concise information about sports events.", # Sampling parameters temperature=0.7, # Controls randomness (0.0-1.0). Lower = more focused, Higher = more creative top_p=0.95, # Nucleus sampling. Tokens with cumulative probability up to this value are considered top_k=40, # Top-k sampling. Considers this many top tokens at each step # Output controls max_output_tokens=1024, # Maximum number of tokens in the response stop_sequences=["\n\n\n"], # Sequences that will stop generation # Tools and function calling tools=[grounding_tool], # Enable Google Search grounding # Thinking configuration (for models that support it) thinking_config=types.ThinkingConfig(thinking_budget=0), # Disables thinking mode # Response format options # response_mime_type="application/json", # Uncomment for JSON output # response_schema=types.Schema( # Uncomment to enforce structured output # type=types.Type.OBJECT, # properties={ # "winner": types.Schema(type=types.Type.STRING), # "year": types.Schema(type=types.Type.INTEGER) # } # ), # Safety settings safety_settings=[ types.SafetySetting( category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH, threshold=types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE ), types.SafetySetting( category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, threshold=types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE ) ] ) # Example usage with advanced config (omitted for brevity, but would follow the pattern of previous examples) # response = client.models.generate_content( # model="gemini-2.5-flash", # contents="Provide a brief summary of the latest F1 race.", # config=config # ) ``` -------------------------------- ### Example API Request URL with Query Parameters Source: https://docs.keywordsai.co/api-endpoints/observe/logs/logs-list-endpoint This example demonstrates how to construct a URL for the KeywordsAI API request logs endpoint, including common query parameters for pagination, sorting, and filtering. ```URL https://api.keywordsai.co/api/request-logs/list/?page=1&sort_by=-id&is_test=false&all_envs=false&fetch_filters=false&page_size=1 ``` -------------------------------- ### Log Chat Completion Input Example Source: https://docs.keywordsai.co/api-endpoints/observe/logs/request-logging-endpoint This JSON snippet demonstrates the structure for the 'input' field when logging a chat completion request. It shows a messages array with system and user roles. ```json "input": "[{\"role\":\"system\",\"content\":\"You are helpful.\"},{\"role\":\"user\",\"content\":\"Hello\"}]" ``` -------------------------------- ### Query Parameter Examples Source: https://docs.keywordsai.co/api-endpoints/reference/api_endpoints_sop Examples demonstrating the usage of query parameters for API requests. These examples show the expected format for string and integer parameters, including default values and specific formatting for ordering. ```json { "param_a": "2025-01-01T00:00:00Z" } ``` ```json { "param_b": 5 } ``` ```json { "param_c": 500 } ``` ```json { "param_d": "-option_2" } ``` -------------------------------- ### List Credit Transactions - cURL Source: https://docs.keywordsai.co/api-endpoints/manage/credit-transactions/list A command-line interface example for fetching credit transactions from the KeywordsAI API. It uses the GET method and requires an API key in the Authorization header. ```Bash curl -X GET "https://api.keywordsai.co/api/credit-transactions/list/" \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Asynchronous Prompt Creation with Environment Variables Source: https://docs.keywordsai.co/python-sdk/prompts/create An asynchronous example of creating a prompt using `acreate()`. It retrieves the API key from environment variables and demonstrates how to handle asynchronous operations and potential errors during prompt creation. ```python import asyncio import os from dotenv import load_dotenv from keywordsai.prompts.api import PromptAPI load_dotenv() async def create_prompt_async(): """Asynchronous prompt creation""" api_key = os.getenv("KEYWORDS_AI_API_KEY") prompt_api_client = PromptAPI(api_key=api_key) try: response = await prompt_api_client.acreate() print(f"✓ Async prompt created with ID: {response.id}") print(f" Name: {response.name}") print(f" Created at: {response.created_at}") return response except Exception as e: print(f"✗ Async error: {e}") return None # Usage asyncio.run(create_prompt_async()) ``` -------------------------------- ### Create Record Request Examples (Python, TypeScript, cURL) Source: https://docs.keywordsai.co/api-endpoints/reference/api_endpoints_sop Demonstrates how to create a record using the API with different programming languages and tools. Includes setting up the request URL, headers, and payload. Note that stringified JSON fields like 'field_1' and 'field_2' require careful escaping in cURL. ```python import requests url = "https://api.example.com/api/records/create/" headers = { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" } payload = { "field_3": "type_a", "field_4": "sample-value", "field_1": '[{"key":"value","data":"sample"}]', "field_2": '{"key":"value","data":"response"}', "field_5": { "sub_field_a": 10, "sub_field_b": 8, "sub_field_c": 18 }, "field_10": "entity_123", "field_7": 1.2, "field_9": { "prop_1": "value_a" } } response = requests.post(url, headers=headers, json=payload) print(response.json()) ``` ```typescript const url = 'https://api.example.com/api/records/create/'; const headers = { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }; const payload = { field_3: 'type_a', field_4: 'sample-value', field_1: '[{"key":"value","data":"sample"}]', field_2: '{"key":"value","data":"response"}', field_5: { sub_field_a: 10, sub_field_b: 8, sub_field_c: 18 }, field_10: 'entity_123', field_7: 1.2, field_9: { prop_1: 'value_a' } }; const response = await fetch(url, { method: 'POST', headers: headers, body: JSON.stringify(payload) }); const data = await response.json(); console.log(data); ``` ```bash curl -X POST "https://api.example.com/api/records/create/" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "field_3": "type_a", "field_4": "sample-value", "field_1": "[\"{\\\"key\\\":\\\"value\\\",\\\"data\\\":\\\"sample\\\"}\"]", "field_2": "{\"key\":\"value\",\"data\":\"response\"}", "field_5": { "sub_field_a": 10, "sub_field_b": 8, "sub_field_c": 18 }, "field_10": "entity_123", "field_7": 1.2 }' ``` -------------------------------- ### Basic List Conditions Request (Python & cURL) Source: https://docs.keywordsai.co/api-endpoints/automation/conditions/list Demonstrates how to fetch a list of automation conditions using a basic GET request. Includes examples for both Python with the 'requests' library and cURL. ```python import requests url = "https://api.keywordsai.co/automation/conditions/" headers = { "Authorization": "Bearer YOUR_API_KEY" } response = requests.get(url, headers=headers) print(response.json()) ``` ```bash curl -X GET "https://api.keywordsai.co/automation/conditions/" \ -H "Authorization: Bearer YOUR_API_KEY" ```