### Complete Non-Streaming Example Setup in Python Source: https://dev.writer.com/home/tool-calling Initializes the Writer client, defines a tool function, sets up initial messages, and makes the first request with tools. ```python import json from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() def calculate_mean(numbers: list) -> float: return sum(numbers) / len(numbers) tools = [ { "type": "function", "function": { "name": "calculate_mean", "description": "Calculate the mean (average) of a list of numbers.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "description": "List of numbers" } }, "required": ["numbers"] } } } ] messages = [{"role": "user", "content": "what is the mean of [1,3,5,7,9]?"}] # Step 1: Initial request with tools response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=False ) # Step 2: Get and append assistant response response_message = response.choices[0].message messages.append(response_message) tool_calls = response_message.tool_calls # Step 3: Process tool calls if any if tool_calls: for tool_call in tool_calls: tool_call_id = tool_call.id function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "calculate_mean": ``` -------------------------------- ### Install Dependencies and Start Custom Development Server Source: https://dev.writer.com/framework/custom-components Installs project dependencies and starts the development server with support for custom component templates. Ensure Node and npm are installed. ```sh cd ui npm install npm run custom.dev ``` -------------------------------- ### Install Framework Source: https://dev.writer.com/framework/quickstart-tutorial Install the Framework package using pip. This is the initial step before starting any Framework project. ```bash pip install "writer" ``` -------------------------------- ### Test Writer Framework Installation Source: https://dev.writer.com/framework/quickstart Run this command after installation to verify the setup. It creates a 'hello' subfolder and launches a visual editor via a local URL. ```bash writer hello ``` -------------------------------- ### Complete External API Call Example (Python) Source: https://dev.writer.com/home/tool-calling This Python example shows a full workflow of using the Writer AI SDK to call an external API for word pronunciation. It includes defining the tool, making the initial request, processing the tool call, and getting the final response. ```python import requests import json from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() def get_word_pronunciation(word): url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}" try: response = requests.get(url) if response.status_code == 200: return json.dumps(response.json()[0]['phonetics']) else: return f"Failed to retrieve word pronunciation. Status code: {response.status_code}" except Exception as e: return f"Error fetching word pronunciation: {str(e)}" tools = [ { "type": "function", "function": { "name": "get_word_pronunciation", "description": "A function that will return JSON containing the phonetic pronunciation of an English word", "parameters": { "type": "object", "properties": { "word": { "type": "string", "description": "The word to get the phonetic pronunciation for", } }, "required": ["word"], }, }, } ] messages = [{"role": "user", "content": "what is the phonetic pronunciation of the word 'epitome' in English?"}] # Step 1: Initial request response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=False ) # Step 2: Append assistant response response_message = response.choices[0].message messages.append(response_message) tool_calls = response_message.tool_calls # Step 3: Process tool calls if tool_calls: for tool_call in tool_calls: tool_call_id = tool_call.id function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "get_word_pronunciation": function_response = get_word_pronunciation(function_args["word"]) # Append tool result messages.append({ "role": "tool", "tool_call_id": tool_call_id, "name": function_name, "content": function_response, }) # Step 4: Get final response final_response = client.chat.chat( model="palmyra-x5", messages=messages, stream=False ) final_content = final_response.choices[0].message.content # Step 5: Append final response messages.append({ "role": "assistant", "content": final_content }) print(f"Final response: {final_content}") # The conversation history is now complete and ready for additional turns ``` -------------------------------- ### Create and Start Local Agent Development Source: https://dev.writer.com/agent-builder/sync-agent Initiate a new local agent project and immediately start the local development server. This is the starting point for local-to-cloud workflow. ```bash writer create my-local-agent cd my-local-agent writer edit . ``` -------------------------------- ### Example Log Output Source: https://dev.writer.com/framework/cloud-deploy Shows an example of the log output fetched from a deployed application, including timestamps and log levels. ```bash 2024-06-11 09:27:02.190646+00:00 [INFO] Starting container entrypoint... 2024-06-11 09:27:03.798148+00:00 [INFO] BuildService - Downloading build files... ... ``` -------------------------------- ### Install Writer SDK for Node.js Source: https://dev.writer.com/home/sdks Install the Writer SDK for Node.js using npm. Ensure you have Node.js and npm installed. ```sh npm install writer-sdk ``` -------------------------------- ### Install Writer Framework Source: https://dev.writer.com/framework/quickstart Use this command to install the Writer Framework and its dependencies via pip. It's recommended to use a virtual environment. ```bash pip install writer ``` -------------------------------- ### Install Instructor with Writer Support Source: https://dev.writer.com/home/integrations/instructor Install the Instructor library with Writer support using pip. This command ensures you have the necessary components for using Instructor with the Writer API. ```bash pip install instructor[writer] ``` -------------------------------- ### Dockerfile for Framework Application Source: https://dev.writer.com/framework/deploy-with-docker This Dockerfile provides a base setup for building a Docker image for your Framework application. It installs dependencies, sets the working directory, and configures the entry point. ```docker FROM python:3.10-bullseye RUN apt-get update -y && mkdir /app RUN apt-get install build-essential cmake python3-dev -y COPY . /app WORKDIR /app RUN pip3 install poetry RUN poetry config virtualenvs.create false RUN poetry install --only main ENTRYPOINT [ "writer", "run" ] EXPOSE 8080 CMD [ ".", "--port", "8080", "--host", "0.0.0.0" ] ``` -------------------------------- ### Complete External API Call Example Source: https://dev.writer.com/home/tool-calling This snippet shows the full process of handling tool calls, executing an external API (get_word_pronunciation), and then getting a final response from the assistant. ```javascript messages.push(responseMessage); const toolCalls = responseMessage.tool_calls; // Step 3: Process tool calls if (toolCalls && toolCalls.length > 0) { for (const toolCall of toolCalls) { const toolCallId = toolCall.id; const functionName = toolCall.function.name; const functionArgs = JSON.parse(toolCall.function.arguments); if (functionName === "get_word_pronunciation") { const functionResponse = await getWordPronunciation(functionArgs.word); // Append tool result messages.push({ role: "tool", tool_call_id: toolCallId, name: functionName, content: functionResponse, }); } } // Step 4: Get final response const finalResponse = await client.chat.chat({ model: "palmyra-x5", messages: messages, stream: false }); const finalContent = finalResponse.choices[0].message.content; // Step 5: Append final response messages.push({ role: "assistant", content: finalContent }); console.log(`Final response: ${finalContent}`); } } main(); ``` -------------------------------- ### Enable Server Setup in Edit Mode Source: https://dev.writer.com/framework/authentication Command to enable the server setup module when running the writer in edit mode, which is necessary for authentication to be active during editing. ```bash writer edit --enable-server-setup ``` -------------------------------- ### Complete Streaming Code Example with Tool Calls Source: https://dev.writer.com/home/tool-calling This comprehensive example demonstrates initializing the Writer client, defining tools for calculations, making an initial request with tools, and processing a streaming response to collect multiple tool calls and regular content. ```python import json import math from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() def calculate_mean(numbers: list) -> float: if not numbers: raise ValueError("Cannot calculate mean of an empty list") return sum(numbers) / len(numbers) def calculate_standard_deviation(numbers: list) -> float: if len(numbers) < 2: raise ValueError("Cannot calculate standard deviation with fewer than 2 numbers") mean = calculate_mean(numbers) variance = sum((x - mean) ** 2 for x in numbers) / len(numbers) return math.sqrt(variance) tools = [ { "type": "function", "function": { "name": "calculate_mean", "description": "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "description": "List of numbers to calculate the mean for" } }, "required": ["numbers"] } } }, { "type": "function", "function": { "name": "calculate_standard_deviation", "description": "Calculate the standard deviation of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "description": "List of numbers to calculate the standard deviation for" } }, "required": ["numbers"] } } } ] messages = [{"role": "user", "content": "What are the mean and standard deviation of [10, 20, 30, 40, 50]?"}] # Step 1: Initial request with tools response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=True ) # Step 2: Process streaming response to collect multiple tool calls streaming_content = "" function_calls = [] for chunk in response: choice = chunk.choices[0] if choice.delta: # Collect tool calls as they stream in if choice.delta.tool_calls: for tool_call in choice.delta.tool_calls: if tool_call.id: # Start a new function call function_calls.append({ "name": "", "arguments": "", "call_id": tool_call.id }) if tool_call.function: # Append to the most recent function call if function_calls: function_calls[-1]["name"] += tool_call.function.name or "" function_calls[-1]["arguments"] += tool_call.function.arguments or "" # Collect regular content (for cases where no tools are called) ``` -------------------------------- ### Complete non-streaming code example with tool definitions Source: https://dev.writer.com/home/tool-calling This example shows the full process from defining tools to making an initial request and preparing for tool call processing. ```python import json import math from writerai import Writer # Initialize the Writer client. If you don't pass the `apiKey` parameter, # the client looks for the `WRITER_API_KEY` environment variable. client = Writer() def calculate_mean(numbers: list) -> float: if not numbers: raise ValueError("Cannot calculate mean of an empty list") return sum(numbers) / len(numbers) def calculate_standard_deviation(numbers: list) -> float: if len(numbers) < 2: raise ValueError("Cannot calculate standard deviation with fewer than 2 numbers") mean = calculate_mean(numbers) variance = sum((x - mean) ** 2 for x in numbers) / len(numbers) return math.sqrt(variance) tools = [ { "type": "function", "function": { "name": "calculate_mean", "description": "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "description": "List of numbers to calculate the mean for" } }, "required": ["numbers"] } } }, { "type": "function", "function": { "name": "calculate_standard_deviation", "description": "Calculate the standard deviation of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "description": "List of numbers to calculate the standard deviation for" } }, "required": ["numbers"] } } } ] messages = [{"role": "user", "content": "What are the mean and standard deviation of [10, 20, 30, 40, 50]?"}] # Step 1: Initial request with tools response = client.chat.chat( model="palmyra-x5", messages=messages, tools=tools, tool_choice="auto", stream=False ) # Step 2: Get and append assistant response response_message = response.choices[0].message messages.append(response_message) tool_calls = response_message.tool_calls # Step 3: Process tool calls if any if tool_calls: for tool_call in tool_calls: tool_call_id = tool_call.id ``` -------------------------------- ### Start Back-End Server for Custom Components Source: https://dev.writer.com/framework/custom-components Starts the Framework back-end server on a specified port, which is required for the front-end development server to function fully. Recommended for testing new templates. ```sh writer create customtester writer edit customtester --port 5000 ``` -------------------------------- ### Install Project Requirements Source: https://dev.writer.com/framework/quickstart-tutorial Install project dependencies, including scikit-learn, by first creating a requirements.txt file and then running pip install. This ensures all necessary libraries are available. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Writer Framework Source: https://dev.writer.com/agent-builder/local-development Install the Writer Framework package within a virtual environment. This package provides tools for local agent development and deployment. ```bash python3 -m venv venv source venv/bin/activate pip install writer ``` -------------------------------- ### Install and Run MCP Server with npx Source: https://dev.writer.com/home/mcp-server Install and run the latest version of the Writer MCP server using npx. Ensure the WRITER_API_KEY environment variable is set beforehand. ```bash npx -y writer-sdk-mcp@latest ``` -------------------------------- ### Configure Webserver with server_setup.py Source: https://dev.writer.com/framework/custom-server Use `server_setup.py` to configure authentication, add custom routes, and middlewares before the writer server starts. This file is executed before `main.py`. ```python # server_setup.py import typing import writer.serve if typing.TYPE_CHECKING: from fastapi import FastAPI # Returns the FastAPI application associated with the writer server. asgi_app: FastAPI = writer.serve.app @asgi_app.get("/probes/healthcheck") def hello(): return "1" ``` -------------------------------- ### Chatbot System Prompt Example Source: https://dev.writer.com/agent-builder/chatbot-tutorial Defines the persona and instructions for the chatbot. Use this to guide the model's behavior and response style. ```text You are a helpful assistant for Writer's developer platform. Use the provided documentation to answer questions about Writer's APIs, SDKs, and Agent Builder. Be clear and concise, include code examples when helpful, and reference specific docs when appropriate. If you're unsure about something, say so and suggest checking the documentation directly. ``` -------------------------------- ### Create Writer Application with Template Source: https://dev.writer.com/framework/product-description-generator Run this command to create a new project using a specified template. Replace 'product-description-app' with your desired project name and 'pdg-tutorial' with the template name. ```bash writer create product-description-app --template=pdg-tutorial ``` -------------------------------- ### Python Chat Completion Request Source: https://dev.writer.com/api-reference/completion-api/chat-completion Example of how to make a chat completion request using the Writer SDK in Python. Ensure you have the SDK installed and your API key configured. ```python import os from writerai import Writer client = Writer( # This is the default and can be omitted api_key=os.environ.get("WRITER_API_KEY"), ) chat = client.chat.chat( messages=[{ "content": "Write a memo summarizing this earnings report.", "role": "user", }], model="palmyra-x5", ) print(chat.id) ``` -------------------------------- ### Create and Initialize Project with Poetry Source: https://dev.writer.com/home/integrations/instructor Sets up a new project directory and initializes Poetry for dependency management. ```bash mkdir instructor-and-writer-tutorial cd instructor-and-writer-tutorial poetry init -y ``` -------------------------------- ### JavaScript Chat Completion Request Source: https://dev.writer.com/api-reference/completion-api/chat-completion Example of how to make a chat completion request using the Writer SDK in JavaScript. Ensure you have the SDK installed and your API key configured. ```javascript import Writer from 'writer-sdk'; const client = new Writer({ apiKey: process.env['WRITER_API_KEY'], // This is the default and can be omitted }); async function main() { const chat = await client.chat.chat({ messages: [{ content: 'Write a memo summarizing this earnings report.', role: 'user' }], model: 'palmyra-x5', }); console.log(chat.id); } main(); ``` -------------------------------- ### Set Up Environment Variables Source: https://dev.writer.com/agent-builder/sync-agent Create a `.env` file in your local project directory to store your Writer API key. Then, source the file to activate the environment variables for your session. ```bash # .env export WRITER_API_KEY="[your_api_key]" ``` ```bash source .env ``` -------------------------------- ### Delete File using JavaScript SDK Source: https://dev.writer.com/api-reference/file-api/delete-file This JavaScript example demonstrates how to use the Writer SDK to delete a file. Ensure you have the SDK installed and your API key is set. ```JavaScript import Writer from 'writer-sdk'; const client = new Writer({ apiKey: process.env['WRITER_API_KEY'], // This is the default and can be omitted }); async function main() { const file = await client.files.delete('file_id'); console.log(file.id); } main(); ``` -------------------------------- ### Example Deployment Output Source: https://dev.writer.com/framework/cloud-deploy Illustrates the typical output during the deployment process, including package creation, warnings, file packing, upload status, and successful deployment with a URL. ```bash Creating deployment package from path: /path/to/your/app [WARNING] Dockerfile found in project root. This will be ignored in the deployment package. Packing file: pyproject.toml Packing file: README.md ... Uploading package to deployment server Package uploaded. Building... ... Deployment successful URL: https://your_app_url ``` -------------------------------- ### Clone Repository and Navigate to Project Source: https://dev.writer.com/framework/release-notes-generator Clone the framework-tutorials repository and navigate to the starting directory for the release notes generator application. ```sh git clone https://github.com/writer/framework-tutorials.git cd framework-tutorials/release-notes-generator/start ``` -------------------------------- ### Create New Framework App with ai-starter Template Source: https://dev.writer.com/framework/quickstart Generate a new application structure using the 'ai-starter' template. This command creates a 'hello-world' folder with essential app files. ```sh writer create hello-world --template=ai-starter ``` -------------------------------- ### Update Graph using Python SDK Source: https://dev.writer.com/api-reference/kg-api/update-graph This Python example shows how to update a Knowledge Graph using the Writer SDK. Ensure you have the `writerai` package installed and your API key configured. ```Python import os from writerai import Writer client = Writer( # This is the default and can be omitted api_key=os.environ.get("WRITER_API_KEY"), ) graph = client.graphs.update( graph_id="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e", name="name", description="description", ) print(graph.id) ``` -------------------------------- ### Project Imports and Setup Source: https://dev.writer.com/home/integrations/instructor Imports essential libraries for the project and loads environment variables. Includes explanations for each import's purpose. ```python import asyncio import csv import json import os from typing import Annotated, Type, Iterable, List import instructor from dotenv import load_dotenv from pydantic import BaseModel, AfterValidator, Field from writerai import Writer, AsyncWriter load_dotenv() ``` -------------------------------- ### Retrieve Application Graphs using JavaScript SDK Source: https://dev.writer.com/api-reference/application-api/get-application-graphs This JavaScript example demonstrates how to use the writer-sdk to fetch Knowledge Graphs for a no-code agent. Ensure you have the SDK installed and your API key configured. ```JavaScript import Writer from 'writer-sdk'; const client = new Writer({ apiKey: process.env['WRITER_API_KEY'], // This is the default and can be omitted }); async function main() { const applicationGraphsResponse = await client.applications.graphs.list('application_id'); console.log(applicationGraphsResponse.graph_ids); } main(); ``` -------------------------------- ### Retrieve Single Async Job with JavaScript SDK Source: https://dev.writer.com/api-reference/application-api/get-single-async-job This JavaScript example demonstrates how to retrieve a single job using the Writer SDK. Ensure you have the `writer-sdk` installed and your API key is set as an environment variable `WRITER_API_KEY`. ```javascript import Writer from 'writer-sdk'; const client = new Writer({ apiKey: process.env['WRITER_API_KEY'], // This is the default and can be omitted }); async function main() { const applicationGenerateAsyncResponse = await client.applications.jobs.retrieve( '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e', ); console.log(applicationGenerateAsyncResponse.id); } main(); ``` -------------------------------- ### Start Local Development Source: https://dev.writer.com/agent-builder/local-development Use this bash command to initiate the local development server for your agent. This command also provides the URL for accessing your agent locally. ```bash writer edit my-agent ``` -------------------------------- ### Auth0 Server Setup Source: https://dev.writer.com/framework/authentication Initializes the Auth0 authentication client with necessary credentials and registers it with the writer server. Ensure your application is registered in Auth0. ```python import os import writer.serve import writer.auth oidc = writer.auth.Auth0( client_id="xxxxxxx", client_secret="xxxxxxxxxxxxx", domain="xxx-xxxxx.eu.auth0.com", host_url=os.getenv('HOST_URL', "http://localhost:5000") ) writer.serve.register_auth(oidc) ``` -------------------------------- ### Customer Support Chatbot Configuration Source: https://dev.writer.com/blueprints/chatreply This example configures the Chat Reply block for a customer support chatbot. It sets a system prompt to guide the AI's behavior and specifies how to handle routing to human agents. The user's message is passed directly from the Chatbot interface. ```JSON { "conversation_object": "@{chat}", "system_prompt": "You are a helpful customer support assistant. Be friendly and professional. \n\nIMPORTANT: If you encounter any of the following situations, clearly indicate that you need to route to a human agent:\n- Complex technical issues beyond your capabilities\n- Requests for account modifications or sensitive information\n- Complaints that require escalation\n- Situations where you're unsure or need human judgment\n- Requests for supervisor or manager assistance\n\nWhen routing to human, use phrases like:\n- \"I need to connect you with a human agent for this request\"\n- \"Let me escalate this to our support team\"\n- \"This requires human assistance, let me transfer you\"\n- \"I'll need to route this to a specialist\"\n\nFor routine questions and simple requests, provide helpful responses directly.", "message": "@{payload}" } ``` -------------------------------- ### Initialize Base UI with Framework Source: https://dev.writer.com/framework/backend-driven-ui Sets up a UI manager to configure UI components at application startup, creating a component set accessible across all sessions. Use this for initial UI configuration. ```python import writer as wf with wf.init_ui() as ui: with ui.Page(id="my-page"): ui.Header({"text": "Hello World!"}) ui.ColumnContainer(id="column-container") ``` -------------------------------- ### Install Writer SDK for Python Source: https://dev.writer.com/home/sdks Install the Writer SDK for Python using pip. Ensure you have Python 3.7+ and pip installed. ```sh pip install writer-sdk ``` -------------------------------- ### Markdown Theme Example Source: https://dev.writer.com/AGENTS An example of a markdown code block with a theme attribute. ```markdown ```markdown theme={null} This guide shows you how to [specific action]. After completing these steps, you can [concrete outcome]. ``` ``` -------------------------------- ### Disable Server Setup Hook Source: https://dev.writer.com/framework/custom-server To disable the server setup hook, pass `enable_server_setup=False` to the `get_asgi_app` function. ```python asgi_app = writer.serve.get_asgi_app(app_path, mode, enable_server_setup=False) ``` -------------------------------- ### Run Globally Installed MCP Server Source: https://dev.writer.com/home/mcp-server Run the MCP server after installing it globally. Ensure the WRITER_API_KEY environment variable is set. ```bash mcp-server ``` -------------------------------- ### Install LangChain Writer and Python Dotenv Source: https://dev.writer.com/home/integrations/langchain Install the necessary Python packages for the Writer LangChain integration and environment variable management. ```bash pip install langchain-writer python-dotenv ``` -------------------------------- ### Create and Navigate Project Directory Source: https://dev.writer.com/framework/quickstart-tutorial Create a new Framework project named 'logistic_regression' and navigate into its directory. This sets up the basic project structure. ```bash writer create logistic_regression cd logistic_regression ``` -------------------------------- ### Download File using JavaScript SDK Source: https://dev.writer.com/api-reference/file-api/download-file This JavaScript example demonstrates how to download a file using the `writer-sdk`. It shows how to initialize the client, call the download method, and access the file content as a blob. ```JavaScript import Writer from 'writer-sdk'; const client = new Writer({ apiKey: process.env['WRITER_API_KEY'], // This is the default and can be omitted }); async function main() { const response = await client.files.download('file_id'); console.log(response); const content = await response.blob(); console.log(content); } main(); ``` -------------------------------- ### Install OpenLLMetry SDK Source: https://dev.writer.com/home/integrations/openllmetry Install the traceloop-sdk package using pip. This command is used to add the necessary library to your Python environment. ```bash pip install traceloop-sdk ``` -------------------------------- ### Download File using Python SDK Source: https://dev.writer.com/api-reference/file-api/download-file This Python example shows how to download a file using the `writerai` library. It includes initializing the client, calling the download method, and reading the file content. ```Python import os from writerai import Writer client = Writer( # This is the default and can be omitted api_key=os.environ.get("WRITER_API_KEY"), ) response = client.files.download( "file_id", ) print(response) content = response.read() print(content) ``` -------------------------------- ### Start Docker Compose Services Source: https://dev.writer.com/agent-builder/deploy-with-docker Starts the services defined in the docker-compose.yml file, building the image if necessary and running the agent container. ```bash docker compose up ``` -------------------------------- ### Streaming Response Chunk Example Source: https://dev.writer.com/home/applications An example of a server-sent event chunk for streaming responses. Contains 'delta' with 'content' and 'stages' information. ```json data: {'delta': {'title': None, 'content': None, 'stages': [{'id': 'a5d81590-0120-4404-948b-8075e3610f51', 'content': 'Initiating a research assistant: 🚗 Automotive assistant', 'sources': None}]}} ``` -------------------------------- ### Create New Local Project Source: https://dev.writer.com/agent-builder/sync-agent Use this command to create a new local project directory for your agent. Navigate into the created directory to proceed with agent setup. ```bash writer create my-cloud-agent cd my-cloud-agent ``` -------------------------------- ### Install Strands Agents with Writer Dependency Source: https://dev.writer.com/home/integrations/strands Install the Strands Agents SDK with the optional Writer dependency to enable the use of Writer models. ```bash pip install 'strands-agents[writer]' ``` -------------------------------- ### Initialize Writer Client and Define Tools in JavaScript Source: https://dev.writer.com/home/tool-calling This JavaScript snippet demonstrates initializing the Writer client and defining a list of available tools, including their names, descriptions, parameters, and required arguments. It also includes helper functions for calculating mean and standard deviation. ```javascript import { Writer } from "writer-sdk"; // Initialize the Writer client. If you don't pass the `apiKey` parameter, // the client looks for the `WRITER_API_KEY` environment variable. const client = new Writer(); function calculateMean(numbers) { if (numbers.length === 0) { throw new Error("Cannot calculate mean of an empty array"); } return numbers.reduce((sum, num) => sum + num, 0) / numbers.length; } function calculateStandardDeviation(numbers) { if (numbers.length < 2) { throw new Error("Cannot calculate standard deviation with fewer than 2 numbers"); } const mean = calculateMean(numbers); const variance = numbers.reduce((sum, num) => sum + Math.pow(num - mean, 2), 0) / numbers.length; return Math.sqrt(variance); } const tools = [ { type: "function", function: { name: "calculate_mean", description: "Calculate the mean (average) of a list of numbers. Use this when asked for the average or mean of numbers.", parameters: { type: "object", properties: { numbers: { type: "array", items: { type: "number" }, description: "List of numbers to calculate the mean for" } }, required: ["numbers"] } } }, { type: "function", function: { name: "calculate_standard_deviation", description: "Calculate the standard deviation of a list of numbers. Use this when asked for standard deviation, variance, or statistical spread of numbers.", parameters: { type: "object", properties: { numbers: { type: "array", items: { type: "number" }, description: "List of numbers to calculate the standard deviation for" } }, required: ["numbers"] } } } ]; ``` -------------------------------- ### Serve Multiple Framework Apps Simultaneously Source: https://dev.writer.com/framework/custom-server Serve multiple Framework apps on different paths by obtaining separate ASGI apps using `get_asgi_app` and mounting them onto a root FastAPI app. This example mounts two apps on `/app1` and `/app2`. ```python import uvicorn import writer.serve from fastapi import FastAPI, Response root_asgi_app = FastAPI(lifespan=writer.serve.lifespan) sub_asgi_app_1 = writer.serve.get_asgi_app("../app1", "run") sub_asgi_app_2 = writer.serve.get_asgi_app("../app2", "run") root_asgi_app.mount("/app1", sub_asgi_app_1) root_asgi_app.mount("/app2", sub_asgi_app_2) @root_asgi_app.get("/") async def init(): return Response("""