### Quick Start Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md A brief example demonstrating how to initialize the Api client and perform a basic graph RAG query. ```APIDOC ## Quick Start All classes and types are imported from the `trustgraph.api` package: ```python from trustgraph.api import Api, Triple, ConfigKey # Create API client api = Api(url="http://localhost:8088/") # Get a flow instance flow = api.flow().id("default") # Execute a graph RAG query response = flow.graph_rag( query="What are the main topics?", user="trustgraph", collection="default" ) ``` ``` -------------------------------- ### Start a flow instance request Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Example payload for starting a new flow instance using a specific blueprint and parameters. ```json { * "operation": "start-flow", * "flow-id": "my-flow", * "blueprint-name": "document-rag", * "description": "My document processing flow", * "parameters": { * "model": "gpt-4", * "temperature": "0.7" } } ``` -------------------------------- ### Install and Run Redoc CLI Source: https://github.com/trustgraph-ai/trustgraph/blob/master/specs/api/README.md Install the redoc-cli globally to bundle the OpenAPI specification into a static HTML file for viewing. ```bash npm install -g redoc-cli redoc-cli bundle specs/api/openapi.yaml -o api-docs.html open api-docs.html ``` -------------------------------- ### Install and Run Swagger UI Watcher Source: https://github.com/trustgraph-ai/trustgraph/blob/master/specs/api/README.md Install the swagger-ui-watcher globally and use it to view the OpenAPI specification in your browser. ```bash npm install -g swagger-ui-watcher swagger-ui-watcher specs/api/openapi.yaml ``` -------------------------------- ### Install TrustGraph Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Install the library using pip. ```bash pip install trustgraph ``` -------------------------------- ### Get Specific Flow Configuration Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Example request to the configuration service to retrieve a specific flow definition by its key. ```json { "operation": "get", "keys": [ { "type": "flow", "key": "default" } ] } ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html This example shows a complete configuration response, including default flow settings, system prompt, and token costs. ```json {"version":42,"config":{"flow":{"default":{"blueprint-name":"document-rag+graph-rag","description":"Default flow","interfaces":{"agent":{"request":"non-persistent://tg/request/agent:default","response":"non-persistent://tg/response/agent:default"}}}},"prompt":{"system":"You are a helpful AI assistant"},"token-cost":{"gpt-4":{"prompt":0.03,"completion":0.06}}}} ``` -------------------------------- ### Complete Configuration Response Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Example of a successful response when requesting complete configuration. It includes versioning and nested configuration details. ```json { "version": 42, "config": { "flow": { "default": { "blueprint-name": "document-rag+graph-rag", "description": "Default flow", "interfaces": { "agent": { "request": "non-persistent://tg/request/agent:default", "response": "non-persistent://tg/response/agent:default" } } } }, "prompt": { "system": "You are a helpful AI assistant" }, "token-cost": { "gpt-4": { "prompt": 0.03, "completion": 0.06 } } } } ``` -------------------------------- ### Installation Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Instructions on how to install the TrustGraph Python package using pip. ```APIDOC ## Installation ```bash pip install trustgraph ``` ``` -------------------------------- ### Get Flow Definition Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Example of a retrieved flow definition, showing its blueprint and description. ```json {"values":[{"type":"flow","key":"default","value":{"blueprint-name":"document-rag+graph-rag","description":"Default flow"}}]} ``` -------------------------------- ### Prompt Template Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html An example of a prompt template with placeholders for variables like 'max_length' and 'document'. This template is stored in the config service. ```text Summarize the following document in {max_length} words: {document} ``` -------------------------------- ### XPath Record Path Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/prompt.txt Illustrates various XPath expressions for selecting records in XML data. Examples include simple, nested, absolute, and namespace-aware paths, demonstrating flexibility in targeting specific data elements. ```xml //record //customer //data/records/record //customers/customer /ROOT/data/record //ns:record //soap:Body/data/record ``` -------------------------------- ### Start Flow Instance Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Use `start` to create and initiate a new flow instance from a defined class. Specify the class name, a unique ID, a description, and optional parameters. ```python async_flow = await api.async_flow() # Start a flow from a class await async_flow.start( class_name="default", id="my-flow", description="Custom flow instance", parameters={"model": "claude-3-opus"} ) ``` -------------------------------- ### Create or Update Flow Configuration Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Example request to the configuration service to create or update a flow definition. ```json { "operation": "put", "type": "flow", "key": "my-flow", "value": { "name": "My Custom Flow", "description": "A flow for custom tasks." } } ``` -------------------------------- ### Start Flow Instance with Defaults Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Start a flow instance using default parameters defined in the blueprint. Only requires the flow ID and blueprint name. ```json {"operation":"start-flow","flow-id":"my-flow","blueprint-name":"document-rag"} ``` -------------------------------- ### Streaming Response Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Example of a streaming response configuration. ```json {"id":"generate-report","variables":{"data":{"revenue":1000000,"growth":15},"format":"executive summary"},"streaming":true} ``` -------------------------------- ### Pulsar Start-Flow Request Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/flow-configurable-parameters.md Example JSON payload for the Pulsar start-flow operation, demonstrating the inclusion of an optional 'parameters' field for custom flow configurations. ```json { "flow_class": "document-analysis", "flow_id": "customer-A-flow", "parameters": { "model": "claude-3", "size": "12b", "temp": 0.5, "chunk": 1024 } } ``` -------------------------------- ### Install and Run OpenAPI Spec Validator Source: https://github.com/trustgraph-ai/trustgraph/blob/master/specs/api/README.md Install the openapi-spec-validator using pip and use it to validate the OpenAPI specification file. ```bash pip install openapi-spec-validator openapi-spec-validator specs/api/openapi.yaml ``` -------------------------------- ### NLP Query Request Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of NLP Query requests demonstrating different question types and their corresponding parameters. ```json { "question": "Who does Alice know?", "max-results": 50 } ``` ```json { "question": "What companies employ people that Alice knows?", "max-results": 100 } ``` ```json { "question": "Which engineers does Bob collaborate with?" } ``` -------------------------------- ### Structured Query Request Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of Structured Query requests for simple and complex questions, including user and collection parameters. ```json { "question": "Who does Alice know?", "user": "alice", "collection": "research" } ``` ```json { "question": "What companies employ people that Alice knows?", "user": "alice", "collection": "research" } ``` -------------------------------- ### Python SDK - Usage Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/embeddings-batch-processing.md Provides practical examples of how to use the Python SDK's `embeddings` method for both single text and batch processing. ```APIDOC ## Python SDK - Usage Examples ### Description These examples demonstrate how to utilize the `embeddings` method provided by the TrustGraph AI Python SDK for generating embeddings. It covers scenarios for embedding a single text and processing multiple texts in a batch. ### Method `embeddings` ### Endpoint Not Applicable (SDK Usage) ### Parameters - **texts** (list[str]) - Required - A list of texts to embed. ### Usage Examples ```python # Assuming 'flow' is an initialized SDK client instance # Single text embedding vectors = flow.embeddings(["hello world"]) print(f"Dimensions: {len(vectors[0][0])}") # Batch embedding for multiple texts texts = ["text one", "text two", "text three"] all_vectors = flow.embeddings(texts) # Process results from batch embedding for text, vecs in zip(texts, all_vectors): print(f"{text}: {len(vecs[0])} dimensions") ``` ``` -------------------------------- ### Text Completion Request Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of JSON payloads for basic completion, code generation with streaming, and structured JSON output requests. ```json { "system": "You are a helpful assistant that provides concise answers.", "prompt": "Explain the concept of recursion in programming." } ``` ```json { "system": "You are an expert Python developer. Provide clean, well-documented code.", "prompt": "Write a function to calculate the Fibonacci sequence using memoization.", "streaming": true } ``` ```json { "system": "You are a JSON API. Respond only with valid JSON, no other text.", "prompt": "Extract key information from this text and return as JSON with fields:\ntitle, author, year, summary.\n\nText: \"The Theory of Everything by Stephen Hawking (2006) explores...\"\n" } ``` -------------------------------- ### Install API Documentation CLI Tools Source: https://github.com/trustgraph-ai/trustgraph/blob/master/specs/README.md Installs the necessary Redocly and AsyncAPI command-line tools globally using npm to enable documentation generation and validation. ```bash npm install -g @redocly/cli @asyncapi/cli ``` -------------------------------- ### GraphRAG Session Trace Output Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/explainability-cli.md Example output format for the tg-show-explain-trace command, detailing the question, exploration, focus (selected edges with reasoning and source), and synthesized answer. ```text === GraphRAG Session: urn:trustgraph:question:abc123 === Question: What was the War on Terror? Time: 2024-01-15 10:30:00 --- Exploration --- Retrieved 50 edges from knowledge graph --- Focus (Edge Selection) --- Selected 12 edges: 1. (War on Terror, definition, "A military campaign...") Reasoning: Directly defines the subject of the query Source: chunk → page 2 → "Beyond the Vigilant State" 2. (Guantanamo Bay, part_of, War on Terror) Reasoning: Shows key component of the campaign --- Synthesis --- Answer: The War on Terror was a military campaign initiated... [truncated at 500 chars] ``` -------------------------------- ### ExplainabilityClient Initialization Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Initializes the client for fetching explainability entities. It handles eventual consistency using quiescence detection. ```python from trustgraph.api import ExplainabilityClient ``` -------------------------------- ### Initialize TrustGraph Configuration Source: https://github.com/trustgraph-ai/trustgraph/blob/master/README.md Run this command to generate deployment files including docker-compose.yaml or resources.yaml and installation instructions. ```bash npx @trustgraph/config ``` -------------------------------- ### Test Structure Example (Python) Source: https://github.com/trustgraph-ai/trustgraph/blob/master/TESTS.md Provides a template for structuring asynchronous tests using `unittest.IsolatedAsyncioTestCase`. It includes setup, mocking external dependencies using `@patch`, and standard Arrange-Act-Assert pattern. ```python class TestServiceName(IsolatedAsyncioTestCase): """Test service functionality""" def setUp(self): """Set up test fixtures""" self.config = {...} @patch('external.dependency') async def test_success_case(self, mock_dependency): """Test successful operation""" # Arrange mock_dependency.return_value = expected_result # Act result = await service.method() # Assert assert result == expected_result mock_dependency.assert_called_once() ``` -------------------------------- ### Paginated GraphQL Product Query Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/graphql-query.md Example of a GraphQL query to retrieve a paginated list of products, specifying the number of results (limit) and the starting offset. This query fetches product ID, name, price, and category. ```graphql { products(limit: 20, offset: 40) { product_id name price category } } ``` -------------------------------- ### Run Simple VertexAI Tests (Bash) Source: https://github.com/trustgraph-ai/trustgraph/blob/master/TESTS.md Executes a set of simple VertexAI tests that do not require the full TrustGraph infrastructure. This is recommended for quick checks and getting started. It can be run via a script or directly with pytest. ```bash # Run simple tests that don't require full TrustGraph infrastructure ./run_simple_tests.sh # Or run manually: pytest tests/unit/test_text_completion/test_vertexai_simple.py -v pytest tests/unit/test_text_completion/test_vertexai_core.py -v ``` -------------------------------- ### Initialize Api Client Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Configure the client for local or production environments. ```python # Local development api = Api() # Production with authentication api = Api( url="https://trustgraph.example.com/", timeout=120, token="your-api-token" ) ``` -------------------------------- ### Configure XML Data Mapping Source: https://github.com/trustgraph-ai/trustgraph/blob/master/prompt.txt Example configuration for parsing XML data using XPath and mapping extracted fields to target schema fields with type transformations. ```json { "format": { "type": "xml", "encoding": "utf-8", "options": { "record_path": "/ROOT/data/record", "field_attribute": "name" } }, "mappings": [ { "source_field": "Country", "target_field": "country_name" }, { "source_field": "Year", "target_field": "year", "transforms": [{"type": "to_int"}] }, { "source_field": "Amount", "target_field": "amount", "transforms": [{"type": "to_float"}] } ] } ``` -------------------------------- ### Quick Start with TrustGraph API Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Initialize the API client and execute a graph RAG query. ```python from trustgraph.api import Api, Triple, ConfigKey # Create API client api = Api(url="http://localhost:8088/") # Get a flow instance flow = api.flow().id("default") # Execute a graph RAG query response = flow.graph_rag( query="What are the main topics?", user="trustgraph", collection="default" ) ``` -------------------------------- ### Manage Flows in TrustGraph AI Source: https://context7.com/trustgraph-ai/trustgraph/llms.txt Manage flow blueprints and instances. This includes listing blueprints, active flows, getting flow definitions, starting new flows, stopping flows, and creating/updating blueprints. ```python from trustgraph.api import Api api = Api(url="http://localhost:8088/") flow_client = api.flow() # List available blueprints blueprints = flow_client.list_blueprints() print(f"Available blueprints: {blueprints}") # List active flow instances flows = flow_client.list() print(f"Active flows: {flows}") # Get flow definition flow_def = flow_client.get("default") print(flow_def) # Start a new flow from blueprint flow_client.start( blueprint_name="document-rag", id="my-flow", description="Custom RAG flow for research", parameters={"model": "gpt-4"} ) # Stop a flow flow_client.stop("my-flow") # Create/update a blueprint definition = { "services": ["text-completion", "graph-rag"], "parameters": {"model": "gpt-4"} } flow_client.put_blueprint("my-blueprint", definition) ``` -------------------------------- ### Asynchronous REST Flow API Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/python-api-refactor.md Provides an interface for managing and interacting with asynchronous flows. Supports listing, getting, starting, and stopping flows, as well as instance-level operations like agent execution, text completion, and graph RAG. ```APIDOC ## AsyncFlow API ### Description Manages asynchronous REST-based flows. ### Methods - `list()`: Lists all available flows. - `get(id: str)`: Retrieves a specific flow definition by its ID. - `start(class_name: str, id: str, description: str, parameters: Dict)`: Starts a new flow execution. - `stop(id: str)`: Stops an ongoing flow execution. - `id(flow_id: str)`: Returns an `AsyncFlowInstance` for a given flow ID. - `aclose()`: Closes the connection. ## AsyncFlowInstance API ### Description Represents an instance of an asynchronous flow, allowing interaction with specific flow executions. ### Methods - `agent(question: str, user: str, state: Optional[Dict[str, Any]] = None, group: Optional[str] = None, history: Optional[List[Dict[str, Any]]] = None, **kwargs)`: Executes an agent query asynchronously. - `text_completion(system: str, prompt: str, **kwargs)`: Performs asynchronous text completion. - `graph_rag(question: str, user: str, collection: str, **kwargs)`: Executes asynchronous graph RAG. ``` -------------------------------- ### POST /start Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Starts a new flow instance from a defined class. ```APIDOC ## POST /start ### Description Start a new flow instance. Creates and starts a flow from a flow class definition with the specified parameters. ### Method POST ### Endpoint /start ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **class_name** (str) - Required - Flow class name to instantiate - **id** (str) - Required - Identifier for the new flow instance - **description** (str) - Required - Human-readable description of the flow - **parameters** (Dict | None) - Optional - Configuration parameters for the flow ### Request Example ```python async_flow = await api.async_flow() # Start a flow from a class await async_flow.start( class_name="default", id="my-flow", description="Custom flow instance", parameters={"model": "claude-3-opus"} ) ``` ### Response #### Success Response (200) None explicitly defined, typically indicates success if no exception is raised. #### Response Example None ``` -------------------------------- ### Embeddings Request Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of text inputs for embedding generation. ```json {"text":"Machine learning"} ``` ```json {"text":"Quantum computing uses quantum mechanics principles for computation."} ``` ```json {"text":"Neural networks are computing systems inspired by biological neural networks.\nThey consist of interconnected nodes (neurons) organized in layers.\nThrough training, they learn to recognize patterns and make predictions.\n"} ``` -------------------------------- ### Start a flow instance Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Instantiate a new flow from a blueprint with specific parameters. ```python api.flow().start( blueprint_name="default", id="my-flow", description="My custom flow", parameters={"model": "gpt-4"} ) ``` -------------------------------- ### Streaming Thought Chunk Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Example of a streaming thought chunk response from the API. ```json { * "chunk-type": "thought", * "content": "I need to search for information about quantum computing", * "end-of-message": false, * "end-of-dialog": false } ``` -------------------------------- ### Explainability Client Initialization Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Initializes the explainability client with specified retry parameters. ```APIDOC ## `__init__(self, flow_instance, retry_delay: float = 0.2, max_retries: int = 10)` ### Description Initialize explainability client. ### Arguments - `flow_instance`: A SocketFlowInstance for querying triples - `retry_delay`: Delay between retries in seconds (default: 0.2) - `max_retries`: Maximum retry attempts (default: 10) ``` -------------------------------- ### Setup Config Client for Collection Management (Python) Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/multi-tenant-support.md Initializes producers and consumers for interacting with the Config Service. It sets up request/response queues and tracks pending requests using asyncio.Event. This is essential for asynchronous communication with the config service. ```python # In __init__, add config request/response producers/consumers from trustgraph.schema.services.config import ConfigRequest, ConfigResponse # Producer for config requests self.config_request_producer = Producer( client=pulsar_client, topic=config_request_queue, schema=ConfigRequest, ) # Consumer for config responses (with correlation ID) self.config_response_consumer = Consumer( taskgroup=taskgroup, client=pulsar_client, flow=None, topic=config_response_queue, subscriber=f"{id}-config", schema=ConfigResponse, handler=self.on_config_response, ) # Tracking for pending config requests self.pending_config_requests = {} # request_id -> asyncio.Event ``` -------------------------------- ### Prometheus Metrics Example Response Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Example output from the /api/metrics endpoint showing request totals and latency histograms. ```text # HELP http_requests_total Total HTTP requests # TYPE http_requests_total counter http_requests_total{method="POST",endpoint="/api/v1/flow/my-flow/service/agent"} 1234 # HELP http_request_duration_seconds HTTP request latency # TYPE http_request_duration_seconds histogram http_request_duration_seconds_bucket{le="0.1"} 500 http_request_duration_seconds_bucket{le="0.5"} 950 http_request_duration_seconds_bucket{le="1.0"} 990 http_request_duration_seconds_sum 450.5 http_request_duration_seconds_count 1000 ``` -------------------------------- ### Structured Query Response Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of successful, partial, and failed query responses for structured data queries. ```json {"data":{"person":{"name":"Alice","knows":[{"name":"Bob","email":"bob@example.com"},{"name":"Carol","email":"carol@example.com"}]}},"errors":[]} ``` ```json {"data":{"person":{"name":"Alice","knows":null}},"errors":["Cannot query field 'nonexistent' on type 'Person'"]} ``` ```json {"data":null,"errors":[],"error":{"type":"QUERY_GENERATION_ERROR","message":"Could not understand question structure"}} ``` -------------------------------- ### Start Flow Instance Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Initiate a new flow instance from a specified blueprint. Provide a unique flow ID, blueprint name, and optional parameters for customization. ```json {"operation":"start-flow","flow-id":"my-flow","blueprint-name":"document-rag","description":"My document processing flow","parameters":{"model":"gpt-4","temperature":"0.7"}} ``` -------------------------------- ### Prompt Template Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html A sample prompt template demonstrating the use of curly brace placeholders for variable substitution. ```text Summarize the following document in {max_length} words: {document} ``` -------------------------------- ### Configure Flow Blueprints with Parameter References Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/flow-configurable-parameters.md Demonstrates how to structure a flow blueprint that maps specific flow parameters to centralized definitions. It includes metadata for UI ordering, advanced flag toggles, and parameter inheritance via 'controlled-by'. ```json { "flow_class": "document-analysis", "parameters": { "llm-model": { "type": "llm-model", "description": "Primary LLM model for text completion", "order": 1 }, "llm-rag-model": { "type": "llm-model", "description": "LLM model for RAG operations", "order": 2, "advanced": true, "controlled-by": "llm-model" } }, "flow": { "chunker:{id}": { "input": "persistent://tg/flow/chunk:{id}", "parameters": { "chunk_size": "{chunk-size}" } } } } ``` -------------------------------- ### Triples Query Pattern Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of RDF triple pattern matching using subject, predicate, and object filters. ```json {"s": {"v": "https://example.com/person/alice", "e": true}} ``` ```json { "p": {"v": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", "e": true}, "o": {"v": "https://example.com/type/Person", "e": true} } ``` ```json { "s": {"v": "https://example.com/person/alice", "e": true}, "p": {"v": "https://example.com/knows", "e": true} } ``` -------------------------------- ### Initialize a WebSocket client Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Obtain a synchronous wrapper for streaming operations like agent responses and RAG queries. ```python socket = api.socket() flow = socket.flow("default") # Stream agent responses for chunk in flow.agent( question="Explain quantum computing", user="trustgraph", streaming=True ): if hasattr(chunk, 'content'): print(chunk.content, end='', flush=True) ``` -------------------------------- ### Document RAG Response Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of JSON response payloads for the Document RAG service, showing complete non-streaming responses. ```json {"response":"The research papers present three key findings:\n1. Quantum entanglement exhibits non-local correlations\n2. Bell's inequality is violated in experimental tests\n3. Applications in quantum cryptography are promising\n","end-of-stream":false} ``` -------------------------------- ### CLI Tool - Add Document (Basic) Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/large-document-loading.md Command-line interface for adding documents. Handles any file size transparently using the SDK's internal chunking mechanism. ```bash # Works transparently for any size - SDK handles chunking internally tg-add-library-document --file large-report.pdf --title "Large Report" ``` -------------------------------- ### List Flow Definitions Example Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Response indicating a list of available flow definition keys. ```json {"directory":["default","production","my-flow"]} ``` -------------------------------- ### Configure and Verify MCP Tools via CLI Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/mcp-tool-bearer-token.md Demonstrates how to register an MCP tool with a bearer token using the tg-set-mcp-tool command and how to verify the configuration status using tg-show-mcp-tools. ```bash tg-set-mcp-tool \ --id secure-tool \ --tool-url https://secure-server.example.com/mcp \ --auth-token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` ```bash tg-show-mcp-tools ``` -------------------------------- ### Bulk Client Initialization and Management Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Initialize and manage connections for the synchronous bulk client. ```APIDOC ## `__init__(self, url: str, timeout: int, token: str | None) -> None` Initialize synchronous bulk client. ### Arguments - **url** (str) - Base URL for TrustGraph API (HTTP/HTTPS will be converted to WS/WSS) - **timeout** (int) - WebSocket timeout in seconds - **token** (str | None) - Optional bearer token for authentication ## `close(self) -> None` Close connections ``` -------------------------------- ### Agent Service Response Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of JSON response payloads for the Agent service, covering streaming chunks and legacy non-streaming formats. ```json {"chunk-type":"thought","content":"I need to search for information about quantum computing","end-of-message":false,"end-of-dialog":false} ``` ```json {"chunk-type":"answer","content":"Quantum computing uses quantum mechanics principles...","end-of-message":false,"end-of-dialog":false} ``` ```json {"chunk-type":"answer","content":"","end-of-message":true,"end-of-dialog":true} ``` ```json {"answer":"Paris is the capital of France.","thought":"User is asking about the capital of France","observation":"","end-of-message":false,"end-of-dialog":false} ``` -------------------------------- ### Agent Service Request Examples Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html Examples of JSON request payloads for the Agent service, including simple, streaming, and multi-turn conversation formats. ```json {"question":"What is the capital of France?","user":"alice"} ``` ```json {"question":"Explain quantum computing","user":"alice","streaming":true} ``` ```json {"question":"And what about its population?","user":"alice","history":[{"thought":"User is asking about the capital of France","action":"search","arguments":{"query":"capital of France"},"observation":"Paris is the capital of France","user":"alice"}]} ``` -------------------------------- ### Explainable CLI Output Format Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/query-time-explainability.md Example of the structured output generated by the CLI when explainability is enabled. ```text [session] urn:trustgraph:session:abc123 [retrieval] urn:trustgraph:prov:retrieval:abc123 [selection] urn:trustgraph:prov:selection:abc123 Selected 12 edge(s) Edge: (Guantanamo, definition, A detention facility...) Reason: Directly connects Guantanamo to the War on Terror Source: Chunk 1 → Page 2 → Beyond the Vigilant State [answer] urn:trustgraph:prov:answer:abc123 Based on the provided knowledge statements... ``` -------------------------------- ### POST /start-flow Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/tech-specs/flow-configurable-parameters.md Initiates a new flow execution with optional user-defined parameters. ```APIDOC ## POST /start-flow ### Description Starts a new flow execution. The system resolves provided parameters against flow blueprint defaults before execution. ### Method POST ### Endpoint /start-flow ### Request Body - **flow_class** (string) - Required - The class identifier for the flow. - **flow_id** (string) - Required - Unique identifier for the flow instance. - **parameters** (object) - Optional - Map of key-value pairs for flow configuration. ### Request Example { "flow_class": "document-analysis", "flow_id": "customer-A-flow", "parameters": { "model": "claude-3", "size": "12b", "temp": 0.5, "chunk": 1024 } } ``` -------------------------------- ### NLP Query Example Request Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/api.html This example shows a request to the NLP query service, which converts a natural language question into a structured GraphQL query. ```json { "query": "Who does Alice know?", "user": "alice", "collection": "research" } ``` -------------------------------- ### Initialize AsyncFlow client Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Import the AsyncFlow client for asynchronous flow management. ```python from trustgraph.api import AsyncFlow ``` -------------------------------- ### Import Api Class Source: https://github.com/trustgraph-ai/trustgraph/blob/master/docs/python-api.md Import the main client class. ```python from trustgraph.api import Api ```