### Complete Function Instruction Example (Preferred) Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions An integrated example showing preferred function name, description, parameters, example call, constraints, and response structure for clarity and usability. ```text Function Name: get_weather Description: Retrieves the current temperature and weather conditions for a given ZIP code. Supports Celsius and Fahrenheit. Parameters: • zipCode (string, required): The ZIP code of the location. Only US ZIP codes are supported. • measurement (string, optional, default: "F"): The temperature measurement unit, either “C” or “F”. Example Call: get_weather({"zipCode": "10001", "measurement": "C"}) Constraints: • Only retrieves weather data for ZIP codes within the United States. Response: • temperature (number): The current temperature. • conditions (string): The weather conditions (for example, “Cloudy”, “Sunny”). • measurement (string): The unit of temperature measurement. Example Response: {"temperature": 22.5, "conditions": "Sunny", "measurement": "C"} ``` -------------------------------- ### Install dependencies from requirements.txt Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Install missing dependencies after adding them to the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Python 3.10+ Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Use this command to install a specific Python version if a mismatch is detected. ```bash pyenv install 3.13.0 ``` -------------------------------- ### Full Function Example (Preferred) Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions/index.html.md A comprehensive instruction set for a function, including name, description, detailed parameters, constraints, and a clear response structure with an example. This provides agents with all necessary information for effective use. ```json Function Name: `get_weather` Description: Retrieves the current temperature and weather conditions for a given ZIP code. Supports Celsius and Fahrenheit. Parameters: • `zipCode (string, required)`: The ZIP code of the location. Only US ZIP codes are supported. • `measurement (string, optional, default: "F")`: The temperature measurement unit, either “C” or “F”. Example Call: `get_weather({"zipCode": "10001", "measurement": "C"})` Constraints: • Only retrieves weather data for ZIP codes within the United States. Response: • `temperature (number)`: The current temperature. • `conditions (string)`: The weather conditions (for example, “Cloudy”, “Sunny”). • `measurement (string)`: The unit of temperature measurement. Example Response: `{"temperature": 22.5, "conditions": "Sunny", "measurement": "C"}` ``` -------------------------------- ### Verify ADK installation Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk/index.html.md Check the installed version of the ADK. The output should display the version number. ```bash gradient --version ``` -------------------------------- ### Function Input Example (Preferred) Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions/index.html.md Defines required and optional parameters with clear types, purposes, constraints, and provides an example call. This format helps agents understand how to invoke the function correctly. ```json Parameters: • `zipCode (string, required)`: The ZIP code of the location. Only US ZIP codes are supported. • `measurement (string, optional, default: "F")`: The temperature measurement unit, either “C” or “F”. Example Call: `get_weather({"zipCode": "10001", "measurement": "C"})` Constraints: • Only retrieves weather data for ZIP codes within the United States. ``` -------------------------------- ### Function Output Example (Preferred) Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions/index.html.md Specifies the structure and fields of the function's response, including data types and an example. This helps agents understand what data to expect back from the function. ```json Response: • `temperature (number)`: The current temperature. • `conditions (string)`: The weather conditions (for example, “Cloudy”, “Sunny”). • `measurement (string)`: The unit of temperature measurement. Example Response: `{"temperature": 22.5, "conditions": "Sunny", "measurement": "C"}` ``` -------------------------------- ### Install gradient-adk package Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk/index.html.md Install the `gradient-adk` package using pip. This command also makes the `gradient` CLI available. ```bash pip install gradient-adk ``` -------------------------------- ### Function Input Example (Avoid) Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions/index.html.md A less descriptive example of function parameters and call, lacking detail on types and constraints, making it harder for agents to use accurately. ```json Parameters: • `zipCode`: Location. • `measurement`: Temperature format. Example Call: `get_weather({"zipCode": "90210"})` ``` -------------------------------- ### Preferred Function Instruction Example Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions Provides a clear and concise example of a well-structured function instruction, including a descriptive name and purpose statement. ```text > **Function Name:** `get_weather` > > **Description:** Retrieves the current temperature and weather conditions for a given ZIP code. Supports Celsius and Fahrenheit. ``` -------------------------------- ### Get Gradient Agent Help Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk/index.html.md Display help information and available commands for the Gradient agent CLI. ```bash gradient agent --help ``` -------------------------------- ### Start an Indexing Job via cURL Source: https://docs.digitalocean.com/products/ai-platform/how-to/create-manage-agent-knowledge-bases/index.html.md Use this cURL command to send a POST request to start an indexing job for a specified knowledge base and data source. ```shell curl -X POST \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $DIGITALOCEAN_TOKEN" \ "https://api.digitalocean.com/v2/gen-ai/indexing_jobs" \ -d '{ "knowledge_base_uuid": "9758a232-b351-11ef-bf8f-4e013e2ddde4", "data_source_uuids": [ "9a825ee0-bbb1-11ef-bf8f-4e013e2ddde4" ] }' ``` -------------------------------- ### Add Basic Custom Logging Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk/index.html.md An example demonstrating how to integrate basic custom logging into your agent code using the `logging` module and `gradient_adk`'s `entrypoint`. ```python import logging from gradient_adk import entrypoint ``` -------------------------------- ### Focused Prompt Example Source: https://docs.digitalocean.com/products/ai-platform/concepts/context-management/index.html.md This example shows a focused prompt that isolates a single task (JWT authentication), includes only relevant code snippets, and specifies clear requirements for the AI. ```markdown I need to add JWT-based authentication to my Next.js API. Here's the current user model and database connection pattern: [Relevant code files only] Create login and register endpoints that: 1. Validate input data 2. Hash passwords with bcrypt 3. Return JWT tokens 4. Follow the existing error handling pattern ``` -------------------------------- ### Unfocused Prompt Example Source: https://docs.digitalocean.com/products/ai-platform/concepts/context-management/index.html.md This example demonstrates an unfocused prompt that mixes unrelated file context with multiple goals and questions, leading to less effective AI responses. ```markdown Here's my entire codebase (50 files), I want to add user authentication, also fix the database performance issues, and can you also help me deploy this to production, plus I'm thinking about adding real-time features later, what do you think about WebSockets vs Server-Sent Events? ``` -------------------------------- ### Initialize a New Agent Project Source: https://docs.digitalocean.com/products/ai-platform/getting-started/use-adk/index.html.md Use this command to start a new agent project. You will be prompted to provide workspace and deployment names. This command sets up the necessary directory structure and configuration files. ```bash gradient agent init ``` -------------------------------- ### Example Knowledge Base Response Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk This is an example JSON response from the DigitalOcean API when listing knowledge bases. It includes the ID, name, and creation date for each knowledge base. ```json { "knowledge_bases": [ { "id": "kb-abc123-xxxx-xxxx", "name": "My Knowledge Base", "created_at": "2026-01-20T10:00:00Z" } ] } ``` -------------------------------- ### RAG Agent Example with ADK and Langchain Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Example of a Retrieval-Augmented Generation (RAG) agent using ADK with Langchain. This snippet shows basic imports for LLM and prompt templates. ```python from gradient_adk import entrypoint, trace_llm, trace_retriever from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate ``` -------------------------------- ### Complete Function Instruction Example (Avoided) Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions An example of function instructions that should be avoided due to vague descriptions and lack of specific details for parameters and response. ```text Function Name: get_weather Description: Gets weather data. Parameters: • zipCode: Location. • measurement: Temperature format. Example Call: get_weather({"zipCode": "90210"}) Response: Calls an external API to fetch weather data and returns the results in JSON format. Example Response: {"temperature": 22.5, "conditions": "Sunny"} ``` -------------------------------- ### API Response Examples Source: https://docs.digitalocean.com/products/ai-platform/reference/api/serverless-inference Examples of successful and error responses from the API, including status codes and error messages. ```json { "data": [ { "created": 1686935002, "id": "meta-llama/Meta-Llama-3.1-8B-Instruct", "object": "model", "owned_by": "digitalocean" } ], "object": "list" } ``` ```json { "id": "unauthorized", "message": "Unable to authenticate you." } ``` ```json { "id": "too_many_requests", "message": "API rate limit exceeded." } ``` ```json { "id": "server_error", "message": "Unexpected server-side error" } ``` ```json { "id": "example_error", "message": "some error message" } ``` -------------------------------- ### Build a LangGraph Agent with Tools Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk/index.html.md This example demonstrates how to build a LangGraph agent that can utilize tools for calculations and web searches. It includes defining tools, agent nodes, and graph routing for sequential execution. ```python from langgraph.prebuilt import ToolNode, tools_condition from langchain_core.tools import tool @tool def calculator(expression: str) -> str: """Calculate a math expression.""" return str(eval(expression)) @tool def web_search(query: str) -> str: """Search the web.""" # Your search logic return "Search results..." tools = [calculator, web_search] # Define nodes async def agent_node(state: State): """Decide what to do next.""" response = await llm_with_tools.ainvoke(state["messages"]) return {"messages": state["messages"] + [response]} # Build graph with tools graph = StateGraph(State) graph.add_node("agent", agent_node) graph.add_node("tools", ToolNode(tools)) # Add routing graph.set_entry_point("agent") graph.add_conditional_edges( "agent", tools_condition, {"tools": "tools", END: END} ) graph.add_edge("tools", "agent") workflow = graph.compile() @entrypoint async def main(input: dict, context: dict): result = await workflow.ainvoke({ "messages": [HumanMessage(content=input["prompt"])] }) return {"response": result["messages"][-1].content} ``` -------------------------------- ### Poorly Specific Prompt Example Source: https://docs.digitalocean.com/products/ai-platform/concepts/context-management An example of a prompt that is too broad and likely to result in poor AI-generated output. Avoid such prompts. ```text Build a complete e-commerce platform with user management, product catalog, shopping cart, payment processing, order management, inventory tracking, admin dashboard, analytics, and mobile responsiveness. ``` -------------------------------- ### Retrieve Chunks with OR Filter Source: https://docs.digitalocean.com/products/ai-platform/how-to/create-manage-agent-knowledge-bases This `curl` example demonstrates how to retrieve chunks using an `or_all` filter. It targets chunks where the `item_name` starts with a specific URL or the chunk was ingested on or after a specified date. Ensure the `key` and `value` types are compatible with the metadata fields. ```curl curl --location 'https://kbaas.do-ai.run/v1//retrieve' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer $DO_API_TOKEN' \ --data '{ "query": "How do I build an agent on DigitalOcean", "num_results": 5, "filters": { "or_all": [ { "starts_with": { "key": "item_name", ``` -------------------------------- ### Multi Field Ground Truth Example Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Example of a multi-field query and its expected response for a ground truth evaluation dataset. ```csv query,expected_response "{ ""prompt"":""What's the weather in nyc?"", ""messages"": ["old message"]}", "The weather in NYC is sunny with a high of 75°F." ``` -------------------------------- ### Hybrid Search Retrieval Example Source: https://docs.digitalocean.com/products/ai-platform/concepts/retrieval This example demonstrates a retrieval request using hybrid search, which combines keyword search with vector search. It also shows how to scope results to a specific documentation path and enable reranking for improved relevance. ```APIDOC ## POST /v1//retrieve ### Description Performs a retrieval operation using hybrid search, with options for filtering and reranking. ### Method POST ### Endpoint `https://kbaas.do-ai.run/v1//retrieve` ### Parameters #### Request Body - **query** (string) - Required - The search query. - **num_results** (integer) - Optional - The number of results to return. - **alpha** (float) - Optional - A float between 0 and 1 to control the balance between keyword and vector search in hybrid search. - **filters** (object) - Optional - Filtering criteria for the search results. - **starts_with** (object) - Optional - Filters results where a specified key's value starts with a given prefix. - **key** (string) - Required - The metadata key to filter on (e.g., "item_name"). - **value** (string) - Required - The prefix value to match. - **reranking** (object) - Optional - Configuration for reranking search results. - **enabled** (boolean) - Required - Whether to enable reranking. ### Request Example ```json { "query": "How do I build an agent on DigitalOcean?", "num_results": 5, "alpha": 0.5, "filters": { "starts_with": { "key": "item_name", "value": "https://docs.digitalocean.com/products/ai-platform/" } }, "reranking": { "enabled": true } } ``` ### Response #### Success Response (200) - **results** (array) - An array of search result objects. - **metadata** (object) - Metadata associated with the result. - **chunk_category** (string) - The category of the chunk. - **ingested_timestamp** (string) - The timestamp when the data was ingested. - **item_name** (string) - The name or identifier of the item. - **text_content** (string) - The text content of the retrieved chunk. - **total_results** (integer) - The total number of results found. ``` -------------------------------- ### Create an Agent using doctl CLI Source: https://docs.digitalocean.com/products/ai-platform/how-to/create-agents/index.html.md Create an agent with a specified name, project ID, model ID, region, and instructions. Ensure you have installed doctl and authenticated it with your personal access token. ```shell doctl gradient agent create --name "My Agent" --project-id "12345678-1234-1234-1234-123456789012" --model-id "12345678-1234-1234-1234-123456789013" --region "tor1" --instruction "You are an agent who thinks deeply about the world" ``` -------------------------------- ### Multi Field JSON Payload Example Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Example of a multi-field JSON payload including a `prompt` and `messages` array for the `query` column. ```json query "{ ""prompt"":""What's the weather in nyc?"", ""messages"": ["old message"]}" ``` -------------------------------- ### List Dedicated Inference Accelerators Response (200 OK) Source: https://docs.digitalocean.com/products/ai-platform/reference/api/dedicated-inference/index.html.md Example of a successful response when listing accelerators for a Dedicated Inference instance. It includes details about the accelerator and pagination links. ```json { "accelerators": [ { "created_at": "2024-01-09T20:44:32Z", "id": "5b5c619c-359c-44ca-87e2-47e98170c02f", "name": "mi300x1-ghfpsf", "role": "prefill_and_decode", "slug": "gpu-mi300x1-192gb", "status": "active" } ], "links": { "pages": { "first": "https://api.digitalocean.com/v2/dedicated-inferences/6b5c619c-359c-44ca-87e2-47e98170c01d/accelerators?page=1\u0026per_page=20", "last": "https://api.digitalocean.com/v2/dedicated-inferences/6b5c619c-359c-44ca-87e2-47e98170c01d/accelerators?page=1\u0026per_page=20" } }, "meta": { "total": 1 } } ``` -------------------------------- ### Full Function Example (Avoid) Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions/index.html.md An incomplete and vague function instruction set that lacks crucial details about parameters, constraints, and response structure, making it difficult for agents to use. ```json Function Name: `get_weather` Description: Gets weather data. Parameters: • `zipCode`: Location. • `measurement`: Temperature format. Example Call: `get_weather({"zipCode": "90210"})` Response: Calls an external API to fetch weather data and returns the results in JSON format. Example Response: `{"temperature": 22.5, "conditions": "Sunny"}` ``` -------------------------------- ### Create an OpenAI API Key using doctl Source: https://docs.digitalocean.com/products/ai-platform/how-to/use-agents/index.html.md Create an OpenAI API key with a specified name. Ensure you have installed doctl and authenticated it with your DigitalOcean account. ```shell doctl gradient openai-key create --name my-key --api-key sk-1234567890abcdef1234567890abcdef ``` -------------------------------- ### Preferred Function Instruction Format Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions/index.html.md Provides an example of a concise and descriptive function name and description for an agent. ```text > **Function Name:** `get_weather`, , **Description:** Retrieves the current temperature and weather conditions for a given ZIP code. Supports Celsius and Fahrenheit. ``` -------------------------------- ### Image Generation with Python SDK Source: https://docs.digitalocean.com/products/ai-platform/reference/api/serverless-inference/index.html.md Python code example using the pydo client to generate an image. Requires the DIGITALOCEAN_TOKEN environment variable for authentication. ```python import os from pydo import Client client = Client(token=os.environ.get("DIGITALOCEAN_TOKEN")) resp = client.images.generate( model="openai-gpt-image-1", prompt="A cute baby sea otter floating on its back in calm blue water", size="auto", quality="auto", n=1, ) print(resp.data[0].b64_json) ``` -------------------------------- ### Image Generation with JavaScript SDK Source: https://docs.digitalocean.com/products/ai-platform/reference/api/serverless-inference/index.html.md JavaScript code example using the @digitalocean/dots client to generate an image. Ensure your DIGITALOCEAN_TOKEN is set in the environment. ```javascript import { InferenceClient } from "@digitalocean/dots"; const client = new InferenceClient({ apiKey: process.env.DIGITALOCEAN_TOKEN, }); const resp = await client.images.generate({ model: "openai-gpt-image-1", prompt: "A cute baby sea otter floating on its back in calm blue water", size: "auto", quality: "auto", n: 1, }); console.log(resp.data[0].b64_json); ``` -------------------------------- ### Product Requirements Document (PRD) Example Source: https://docs.digitalocean.com/products/ai-platform/concepts/context-management/index.html.md Define project objectives, core features, technical requirements, and out-of-scope items for AI agent projects. ```markdown # Task Management App PRD ## Objective Create a simple task management application for small teams. ## Core Features - User authentication (email/password) - Create, edit, delete tasks - Assign tasks to team members - Mark tasks as complete ## Technical Requirements - Next.js frontend - PostgreSQL database - Deploy to DigitalOcean App Platform - Support up to 50 concurrent users ## Out of Scope - Real-time collaboration - File attachments - Advanced reporting - Mobile app ``` -------------------------------- ### Custom Agent with Full Tracing Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Build a custom agent from scratch using ADK's tracing decorators for memory search, tools, LLM calls, and reasoning. This example shows a complete agent processing pipeline. ```python from gradient_adk import entrypoint, trace_llm, trace_tool, trace_retriever class MyCustomAgent: """Your custom agent.""" @trace_retriever("memory_search") async def search_memory(self, query: str): """Search conversation memory.""" # Your memory search logic return ["relevant", "memories"] @trace_tool("calculator") async def calculate(self, expression: str): """Perform calculation.""" try: result = eval(expression) return {"success": True, "result": result} except Exception as e: return {"success": False, "error": str(e)} @trace_llm("reasoning") async def think(self, prompt: str, context: list): """Reasoning step.""" full_prompt = f"Context: {context}\n\nTask: {prompt}" response = await your_llm_api.generate(full_prompt) return response @trace_llm("respond") async def respond(self, reasoning: str): """Generate final response.""" response = await your_llm_api.generate( f"Based on: {reasoning}\n\nGenerate friendly response:" ) return response async def process(self, user_input: str): """Main processing logic.""" # Step 1: Search memory memories = await self.search_memory(user_input) # Step 2: Use tools if needed if "calculate" in user_input.lower(): calc_result = await self.calculate("2 + 2") memories.append(f"Calculation: {calc_result}") # Step 3: Think reasoning = await self.think(user_input, memories) # Step 4: Respond final_response = await self.respond(reasoning) return final_response # Initialize agent agent = MyCustomAgent() @entrypoint async def main(input: dict, context: dict): """Custom agent entrypoint.""" response = await agent.process(input["prompt"]) return {"response": response} ``` -------------------------------- ### Complete Agent with Trace Decorators Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk A comprehensive example of an agent instrumented with trace decorators for document retrieval, tool execution, and LLM calls. This demonstrates how to integrate tracing into a RAG agent. ```python from gradient_adk import entrypoint, trace_retriever, trace_llm, trace_tool @trace_retriever("search_knowledge_base") async def search_kb(query: str): """Search for relevant documents.""" docs = await vector_db.search(query) return docs @trace_tool("calculator") async def calculate(expr: str): """Calculate math expression.""" return eval(expr) @trace_llm("generate_answer") async def generate(prompt: str, context: str): """Generate final answer.""" full_prompt = f"Context: {context}\n\nQuestion: {prompt}" response = await llm.generate(full_prompt) return response @entrypoint async def main(input: dict, context: dict): """ RAG agent with full tracing. You'll see in traces: 1. Document search with query and results 2. Calculator execution (if needed) 3. LLM call with prompt and response """ query = input["prompt"] # Step 1: Search (traced automatically) docs = await search_kb(query) # Step 2: Calculate if needed (traced automatically) if "calculate" in query.lower(): calc_result = await calculate("2+2") docs.append(f"Calculation: {calc_result}") # Step 3: Generate answer (traced automatically) answer = await generate(query, str(docs)) return {"response": answer} ``` -------------------------------- ### Multi Field JSON Payload Example Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk/index.html.md Illustrates a multi-field JSON payload for the `query` column, including a `messages` array. The ground truth example shows the corresponding `expected_response`. ```javascript query "{ ""prompt"":""What's the weather in nyc?"", ""messages"": ["old message"] }" ``` ```javascript query,expected_response "{ ""prompt"":""What's the weather in nyc?"", ""messages"": ["old message"] }", "The weather in NYC is sunny with a high of 75°F." ``` -------------------------------- ### Get Weather JavaScript Function Implementation Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions An example implementation of the get-weather.js function using axios to fetch weather data from an external API. It handles optional measurement units and returns temperature, measurement unit, and conditions. ```javascript import axios from 'axios'; async function main(args) { const zipCode = args.zipCode; const measurement = args.measurement || 'F'; const weatherResponse = await axios.get(`https://your-api.com/weather/${zipCode}`, { params: { measurement } }); const { temperature, conditions } = weatherResponse.data; return { body: { temperature, measurement, conditions } }; } ``` -------------------------------- ### Successful Model List Response Source: https://docs.digitalocean.com/products/ai-platform/reference/api/serverless-inference/index.html.md Example of a successful response when listing available models. ```json { "data": [ { "created": 1686935002, "id": "meta-llama/Meta-Llama-3.1-8B-Instruct", "object": "model", "owned_by": "digitalocean" } ], "object": "list" } ``` -------------------------------- ### List Dedicated Inference Tokens Response (200 OK) Source: https://docs.digitalocean.com/products/ai-platform/reference/api/dedicated-inference/index.html.md Example of a successful response when listing tokens for a Dedicated Inference instance. It includes pagination links and metadata. ```json { "links": { "pages": { "first": "https://api.digitalocean.com/v2/dedicated-inferences/6b5c619c-359c-44ca-87e2-47e98170c01d/tokens?page=1\u0026per_page=20", "last": "https://api.digitalocean.com/v2/dedicated-inferences/6b5c619c-359c-44ca-87e2-47e98170c01d/tokens?page=1\u0026per_page=20" } }, "meta": { "total": 0 }, "tokens": [] } ``` -------------------------------- ### Initialize Doctl CLI Source: https://docs.digitalocean.com/products/ai-platform/how-to/create-agents Initialize the DigitalOcean CLI with your personal access token to grant it access to your account. ```bash doctl auth init ``` -------------------------------- ### Avoided Function Instruction Format Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions/index.html.md Illustrates an example of a vague and unhelpful function description that should be avoided. ```text > **Function Name:** `get_weather`, , **Description:** Gets weather data. ``` -------------------------------- ### Create Knowledge Base via cURL Source: https://docs.digitalocean.com/products/ai-platform/how-to/create-manage-agent-knowledge-bases/index.html.md Use this cURL command to create a new knowledge base via the DigitalOcean API. Ensure you replace placeholder values with your actual token, project ID, and desired configurations. This example demonstrates creating a knowledge base with multiple data sources, including Spaces buckets and a web crawler, each with specific chunking strategies and options. ```shell curl -X POST \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $DIGITALOCEAN_TOKEN" \ "https://api.digitalocean.com/v2/gen-ai/knowledge_bases" \ -d '{ "name": "kb-api-create", "embedding_model_uuid": "05700391-7aa8-11ef-bf8f-4e013e2ddde4", "project_id": "37455431-84bd-4fa2-94cf-e8486f8f8c5e", "tags": [ "tag1" ], "database_id": "abf1055a-745d-4c24-a1db-1959ea819264", "datasources": [ { "spaces_data_source": { "bucket_name": "test-public-gen-ai", "region": "tor1" }, "chunking_algorithm": "CHUNKING_ALGORITHM_HIERARCHICAL", "chunking_options": { "parent_chunk_size": 1000, "child_chunk_size": 350 } }, { "web_crawler_data_source": { "base_url": "https://example.com", "crawling_option": "SCOPED", "embed_media": false, "exclude_tags": ["nav","footer","header","aside","script","style","form","iframe", "noscript"] }, "chunking_algorithm": "CHUNKING_ALGORITHM_SEMANTIC", "chunking_options": { "max_chunk_size": 500, "semantic_threshold": 0.6 } }, { "spaces_data_source": { "bucket_name": "test-public-gen-ai-2", "region": "tor1" }, "chunking_algorithm": "CHUNKING_ALGORITHM_FIXED_LENGTH", "chunking_options": { "max_chunk_size": 400 } }, ], "region": "tor1", "vpc_uuid": "f7176e0b-8c5e-4e32-948e-79327e56225a", "reranking_config": { "enabled": true, "model": "bge-reranker-v2-m3" } }' ``` -------------------------------- ### Function Output Example (Avoid) Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions/index.html.md An unhelpful description of function output that mentions implementation details (API calls) and omits key information like data types and units. ```json Response: Calls an external API to fetch weather data and returns the results in JSON format. Example Response: `{"temperature": 22.5, "conditions": "Sunny"}` ``` -------------------------------- ### Create requirements.txt Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Create a dependency file if one is missing. Ensure 'gradient-adk' is included. ```bash echo "gradient-adk" > requirements.txt ``` -------------------------------- ### Interact with Agent using Python OpenAI Source: https://docs.digitalocean.com/products/ai-platform/getting-started/quickstart/index.html.md This Python script demonstrates how to interact with your agent using the OpenAI library. It requires setting the agent endpoint and access key as environment variables. The example shows how to request the response content and the full retrieval object. ```python # Install OS, JSON, and OpenAI libraries. import os import json from openai import OpenAI # Set your agent endpoint and access key as environment variables in your OS. agent_endpoint = os.getenv("agent_endpoint") + "/api/v1/" agent_access_key = os.getenv("agent_access_key") if __name__ == "__main__": client = OpenAI( base_url = agent_endpoint, api_key = agent_access_key, ) response = client.chat.completions.create( model = "n/a", messages = [{"role": "user", "content": "Can you provide the name of France's capital in JSON format."}], extra_body = {"include_retrieval_info": True} ) # Prints response's content and retrieval object. for choice in response.choices: print(choice.message.content) response_dict = response.to_dict() print("\nFull retrieval object:") print(json.dumps(response_dict["retrieval"], indent=2)) ``` -------------------------------- ### Single Field JSON Payload Example Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Example of a single-field JSON payload for the `query` column in an evaluation dataset. ```json query "{ ""prompt"":""What's the weather in nyc?""}" ``` -------------------------------- ### Define Function Input Parameters Source: https://docs.digitalocean.com/products/ai-platform/concepts/function-instructions Specify required and optional parameters with their data types, purpose, constraints, and an example call. This ensures agents pass correct values. ```text Parameters: • zipCode (string, required): The ZIP code of the location. Only US ZIP codes are supported. • measurement (string, optional, default: "F"): The temperature measurement unit, either “C” or “F”. Example Call: get_weather({"zipCode": "10001", "measurement": "C"}) Constraints: • Only retrieves weather data for ZIP codes within the United States. ``` -------------------------------- ### Python OpenAI Library Example Source: https://docs.digitalocean.com/products/ai-platform/how-to/use-agents Use the OpenAI Python library to send requests to an agent's endpoint. The library handles the endpoint path, and you can configure parameters like `include_retrieval_info` via `extra_body`. ```APIDOC ## Use Agent Endpoint with OpenAI Python Library ### Description This example demonstrates how to use the `openai` Python library to interact with an agent's chat completions endpoint. It shows how to set up the client with the agent's endpoint and API key, and how to include additional information in the request. ### Method Client method: `client.chat.completions.create` ### Parameters #### Client Initialization - **base_url** (string) - Required - The agent's endpoint URL, typically ending with `/api/v1/`. - **api_key** (string) - Required - The agent's access key for authentication. #### `create` Method Parameters - **model** (string) - Required - The model to use (e.g., "n/a" as specified in the example). - **messages** (list of dict) - Required - A list of message objects, each with a `role` and `content`. - **extra_body** (dict) - Optional - A dictionary for additional parameters, such as `{"include_retrieval_info": True}`. ### Request Example ```python import os from openai import OpenAI agent_endpoint = os.getenv("agent_endpoint") + "/api/v1/" agent_access_key = os.getenv("agent_access_key") client = OpenAI( base_url = agent_endpoint, api_key = agent_access_key, ) response = client.chat.completions.create( model = "n/a", messages = [{"role": "user", "content": "Can you provide the name of France's capital in JSON format." }], extra_body = {"include_retrieval_info": True} ) for choice in response.choices: print(choice.message.content) response_dict = response.to_dict() print("\nFull retrieval object:") print(json.dumps(response_dict["retrieval"], indent=2)) ``` ### Response #### Success Response The response object contains `choices`, where each choice has a `message` with `content`. If `include_retrieval_info` was set, the response dictionary will also contain a `retrieval` object. ``` -------------------------------- ### Start an Indexing Job Source: https://docs.digitalocean.com/products/ai-platform/how-to/create-manage-agent-knowledge-bases/index.html.md Initiates an indexing job for a knowledge base. This process ingests data from specified sources to create embeddings for the knowledge base. ```APIDOC ## POST /v2/gen-ai/indexing_jobs ### Description Starts an indexing job to process data sources and update a knowledge base. ### Method POST ### Endpoint https://api.digitalocean.com/v2/gen-ai/indexing_jobs ### Request Body - **knowledge_base_uuid** (string) - Required - The UUID of the knowledge base to index. - **data_source_uuids** (array of strings) - Required - A list of UUIDs for the data sources to index. ### Request Example ```json { "knowledge_base_uuid": "9758a232-b351-11ef-bf8f-4e013e2ddde4", "data_source_uuids": [ "9a825ee0-bbb1-11ef-bf8f-4e013e2ddde4" ] } ``` ### Success Response (200) (Response details not provided in source) ### Related Endpoints - [Get Indexing Job](https://docs.digitalocean.com/reference/api/reference/gradientai-platform/index.html.md#genai_get_indexing_job) - [Get Knowledge Base](https://docs.digitalocean.com/reference/api/reference/gradientai-platform/index.html.md#genai_get_knowledge_base) - [Cancel Indexing Job](https://docs.digitalocean.com/reference/api/reference/gradientai-platform/index.html.md#genai_cancel_indexing_job) ``` -------------------------------- ### Single Field Ground Truth Example Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Example of a single-field query and its expected response for a ground truth evaluation dataset. ```csv query,expected_response "{"prompt":""What's the weather in nyc?""}", "The weather in NYC is sunny with a high of 75°F." ``` -------------------------------- ### CrewAI Multi-Agent System with Traces Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk Build a multi-agent system using CrewAI and ADK's trace decorators for tools. This example demonstrates research and writing agents. ```python from gradient_adk import entrypoint, trace_tool from crewai import Agent, Task, Crew @trace_tool("research_crew") def run_research(topic: str): """Run research crew.""" # Create researcher researcher = Agent( role='Senior Researcher', goal=f'Research {topic} thoroughly', backstory='Expert at finding and analyzing information', verbose=True ) # Create task research_task = Task( description=f'Research everything about {topic}', agent=researcher, expected_output='Comprehensive research report' ) # Run crew crew = Crew( agents=[researcher], tasks=[research_task], verbose=True ) result = crew.kickoff() return result @trace_tool("writing_crew") def run_writer(research: str): """Run writing crew.""" writer = Agent( role='Content Writer', goal='Write engaging articles', backstory='Professional writer', verbose=True ) write_task = Task( description=f'Write article based on: {research}', agent=writer, expected_output='Well-written article' ) crew = Crew(agents=[writer], tasks=[write_task]) return crew.kickoff() @entrypoint async def main(input: dict, context: dict): """Multi-agent crew system.""" topic = input["prompt"] # Research phase research = run_research(topic) # Writing phase article = run_writer(research) return {"response": article} ``` -------------------------------- ### Get GPU Model Configurations Source: https://docs.digitalocean.com/products/ai-platform/reference/api/dedicated-inference/index.html.md This endpoint retrieves a list of available GPU model configurations, including their slugs, names, and whether they require gated access. ```APIDOC ## GET /v2/inference/gpu/models ### Description Retrieves a list of available GPU model configurations. ### Method GET ### Endpoint /v2/inference/gpu/models ### Parameters None ### Request Example None ### Response #### Success Response (200) - **gpu_model_configs** (array of object) - Optional. Contains details about each GPU model configuration. - **gpu_slugs** (array of string) - Optional. Example: `["gpu-mi300x1-192gb"]` - **is_gated_model** (boolean) - Optional. Indicates if the model requires gated access. - **model_name** (string) - Optional. Example: `Mistral-7B-Instruct-v0.3` - **model_slug** (string) - Optional. Example: `mistral/mistral-7b-instruct-v3` Response Headers: - `ratelimit-limit` (integer) - `ratelimit-remaining` (integer) - `ratelimit-reset` (integer) #### Response Example ```json { "gpu_model_configs": [ { "gpu_slugs": ["gpu-mi300x1-192gb"], "is_gated_model": false, "model_name": "Mistral-7B-Instruct-v0.3", "model_slug": "mistral/mistral-7b-instruct-v3" } ] } ``` #### Error Response (401) - **id** (string) - Required. Example: `not_found` - **message** (string) - Required. Example: `The resource you were accessing could not be found.` - **request_id** (string) - Optional. Example: `4d9d8375-3c56-4925-a3e7-eb137fed17e9` #### Error Response (429) - **id** (string) - Required. Example: `not_found` - **message** (string) - Required. Example: `The resource you were accessing could not be found.` - **request_id** (string) - Optional. Example: `4d9d8375-3c56-4925-a3e7-eb137fed17e9` #### Error Response (500) - **id** (string) - Required. Example: `not_found` - **message** (string) - Required. Example: `The resource you were accessing could not be found.` - **request_id** (string) - Optional. Example: `4d9d8375-3c56-4925-a3e7-eb137fed17e9` ``` -------------------------------- ### Get Available Regions and Sizes Source: https://docs.digitalocean.com/products/ai-platform/reference/api/dedicated-inference Retrieves a list of regions where Dedicated Inference is available, along with the available GPU sizes and their pricing per hour. ```APIDOC ## GET /v2/inference/dedicated/regions ### Description Retrieves a list of regions where Dedicated Inference is available, along with the available GPU sizes and their pricing per hour. ### Method GET ### Endpoint /v2/inference/dedicated/regions ### Responses #### Success Response (200) Enabled regions and sizes with pricing. - **enabled_regions** (array of string) - Optional - Regions where Dedicated Inference is available. - **sizes** (array of object) - Optional - Details about available GPU sizes. - **currency** (string) - Optional - The currency for the price. - **gpu_slug** (string) - Optional - The identifier for the GPU. - **price_per_hour** (string) - Optional - The price per hour for the GPU. - **region** (string) - Optional - The region where this size is available. #### Response Example (200) ```json { "enabled_regions": [ "nyc2", "atl1" ], "sizes": [ { "currency": "USD", "gpu_slug": "gpu-mi300x1-192gb", "price_per_hour": "2", "region": "nyc2" } ] } ``` #### Error Response (401) Authentication failed due to invalid credentials. - **id** (string) - Required - A short identifier corresponding to the HTTP status code. - **message** (string) - Required - A message providing additional information about the error. - **request_id** (string) - Optional - A request ID for reporting issues. #### Error Response (429) The API rate limit has been exceeded. - **id** (string) - Required - A short identifier corresponding to the HTTP status code. - **message** (string) - Required - A message providing additional information about the error. - **request_id** (string) - Optional - A request ID for reporting issues. #### Error Response (500) There was a server error. - **id** (string) - Required - A short identifier corresponding to the HTTP status code. - **message** (string) - Required - A message providing additional information about the error. - **request_id** (string) - Optional - A request ID for reporting issues. ``` -------------------------------- ### Build a Custom Agent Framework with ADK Tracing Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk/index.html.md Use this framework to build your own agent from scratch, incorporating tracing for retrievers, tools, and LLM calls. Requires defining custom methods for searching memory, calculating, reasoning, and responding. ```python from gradient_adk import entrypoint, trace_llm, trace_tool, trace_retriever class MyCustomAgent: """Your custom agent.""" @trace_retriever("memory_search") async def search_memory(self, query: str): """Search conversation memory.""" # Your memory search logic return ["relevant", "memories"] @trace_tool("calculator") async def calculate(self, expression: str): """Perform calculation.""" try: result = eval(expression) return {"success": True, "result": result} except Exception as e: return {"success": False, "error": str(e)} @trace_llm("reasoning") async def think(self, prompt: str, context: list): """Reasoning step.""" full_prompt = f"Context: {context}\n\nTask: {prompt}" response = await your_llm_api.generate(full_prompt) return response @trace_llm("respond") async def respond(self, reasoning: str): """Generate final response.""" response = await your_llm_api.generate( f"Based on: {reasoning}\n\nGenerate friendly response:" ) return response async def process(self, user_input: str): """Main processing logic.""" # Step 1: Search memory memories = await self.search_memory(user_input) # Step 2: Use tools if needed if "calculate" in user_input.lower(): calc_result = await self.calculate("2 + 2") memories.append(f"Calculation: {calc_result}") # Step 3: Think reasoning = await self.think(user_input, memories) # Step 4: Respond final_response = await self.respond(reasoning) return final_response # Initialize agent agent = MyCustomAgent() @entrypoint async def main(input: dict, context: dict): """Custom agent entrypoint.""" response = await agent.process(input["prompt"]) return {"response": response} ``` -------------------------------- ### Main Entrypoint for RAG Agent Source: https://docs.digitalocean.com/products/ai-platform/how-to/build-agents-using-adk/index.html.md The main asynchronous function that takes user input and invokes the compiled workflow to get a response from the RAG agent. ```python @entrypoint async def main(input: dict, context: dict): """ RAG agent with LangGraph and Knowledge Base tool. The agent will automatically use the Knowledge Base when needed. """ result = await workflow.ainvoke({ "messages": [HumanMessage(content=input["prompt"])] }) return {"response": result["messages"][-1].content} ``` -------------------------------- ### Send a Message using Python SDK Source: https://docs.digitalocean.com/products/ai-platform/reference/api/serverless-inference Example of sending a message to the Serverless Inference API using the Python SDK. Requires the pydo library and the DIGITALOCEAN_TOKEN environment variable. ```python import os from pydo import Client client = Client(token=os.environ.get("DIGITALOCEAN_TOKEN")) resp = client.messages.create( model="claude-opus-4-6", max_tokens=1024, messages=[ {"role": "user", "content": "What is the capital of Portugal?"}, ], ) print(resp.content[0].text) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.