diff --git a/README.md b/README.md index aad0251..1051c44 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,6 @@ See the NPM package here: Read our Current Documentation: - [https://docs.pieces.app](https://docs.pieces.app) -- **Developer docs coming soon** ## Table of Contents @@ -17,24 +16,23 @@ Read our Current Documentation: - [Installing](#installing) - [Pieces OS](#pieces-os) - [Downloading NPM Package](#downloading-npm-package) - - [Creating Project Base](#creating-the-base-of-your-project) - - [Installing Package Dependencies with NPM](#install-package-dependencies-with-npm) - [Running Your Project](#running-your-project-for-the-first-time) -- [Create Connect() Function](#creating-connect-function) +- [Creating a Copilot](#creating-a-copilot) +- [Connecting Your Application](#connecting-your-application) + - [Use Pieces.QGPTStreamInput](#use-piecesqgptstreaminput) + - [Receive QGPT Answers](#receiving-answers-with-piecesqgptquestionanswer) - [Connecting your Application](#connecting-your-application) - - [View Output in Browser](#view-console-output-in-your-browser) -- [Asset + /assets](#getting-started-with-asset--assets) - - [Asset](#asset) - - [SeededAsset](#seededasset) -- [/assets/create](#assetscreate) -- [/assets/snapshot](#assets-snapshot-assetssnapshot) -- [/asset/update](#using-assetupdate) -- [Refresh Your Snapshot](#refresh-your-snapshot) -- [/assets/delete](#delete-using-assetsdelete) +- [Pieces.AssetApi() & Pieces.AssetsApi()](#getting-started-with-piecesassetapi--piecesassetsapi) + - [Create New Asset Using Pieces.AssetsApi().assetsCreateNewAsset()](#piecesassetsapiassetscreatenewasset) +- [Get Asset Snapshot](#get-assets-snapshot-piecesassetsapiassetssnapshot) +- [Update a Snippets Data](#using-piecesassetapiassetupdate-to-rename-snippet) +- [Refresh Your assetsSnapshot()](#refresh-your-snapshot) +- [Delete an Asset](#delete-using-piecesassetsapiassetsdeleteasset) +- [Search your Assets](#use-piecessearchapi) ## Operating System Support -Currently, Pieces OS is utilized as the primary backend service with Pieces for Developers that powers all of the features that can be used there. Both programs are designed for full support by all operating systems, although our Linux Platform is available, it leans towards a 'heavily supported beta' and may experience incremental issues on specific flavors of linux. +Currently, Pieces OS is utilized as the primary backend service with Pieces for Developers that powers all the features that can be used there. Both programs are designed for full support by all operating systems, although our Linux Platform is available, it leans towards a 'heavily supported beta' and may experience incremental issues on specific flavors of linux. ## Configuration & Setup with NPM @@ -118,61 +116,31 @@ import * as pieces from '@pieces.app/pieces-os-client' > **If you are having issues with your installation, it is likely due to a conflict in Typescript versions - `npm uninstall typescript` - then go back and perform all other npm installations before reinstalling typescript again**. -### Creating the base of your project -Let's get started with the base of your new React project where we will learn about manipulating Pieces OS and creating our own assets locally on device. +## Creating a Project from Scratch +Let's get started with the base of your new React project! We will do this by learning more about manipulating Pieces OS and creating our own assets locally on device. First, we will create a directory for you project along with some dependancy setup: -##### **How your .tsconfig should look when you are done:** -```json -{ - "compilerOptions": { - "target": "es2020", - "module": "CommonJS", - "allowJs": true, - "checkJs": true, - "maxNodeModuleJsDepth": 1, - "forceConsistentCasingInFileNames": true, - "strict": false, - "skipLibCheck": true, - "jsx": "react" - }, - "exclude": ["node_modules"] -} -``` +1. Create a directory for your project called (or the name of your choice) +2. Open up a Terminal at the root of that directory, and run `npm uninstall typescript` to ensure you are starting fresh + - (optional) run `nvm install --lts` to check your version of Node +3. From that same terminal window, use the `prefix` parameter in your installation command to install your dependencies: `npm install --prefix ./ @pieces.app/pieces-os-copilot` -### Install Package Dependencies with npm - -#### Need this if you are going to work with ts files +4. Install Dependencies with NPM with these three commands: ```bash -npm install typescript -``` - -I also recommend installing `ts-node` to get the proper commands running and to run individual test files directly from cmd line. Here is that: +npm install typescript && npm install ts-node -```bash -npm install ts-node -``` - -Then getting the types package for node can also be super beneficially and in some cases needed to work in this environment: - -```bash +# Useful types package npm install -D tslib @types/node ``` -I ended up also installing a few react libraries to get a more visual experience while learning about the api itself. - -Here are those npm commands for `@types`: +5 (optional) additional npm packages ```bash -npm install @types/react && npm install @types/react-dom -``` - -Along with the typing, you will need to install the full packages for react, react-dom, and react scripts to properly get started in this project. +npm install @types/react && npm install @types/react-dom -```bash npm install react && npm install react-dom && npm install react-scripts ``` -And last but not least it's a good idea to add a few scripts into your `package.json` to help with development: +6. Add these scripts into your `package.json` to help with development, and be sure to save after adding them: ```json { @@ -210,7 +178,7 @@ Once you open `index.tsx` you should follow these steps to get your base Applica 1. Import the full react library at the top of your file, along with a single import from `react-dom`, and the createRoot method: ```tsx import * as React from "react"; - import {createRoot} from "react-dom/client"; + import { createRoot } from "react-dom/client"; import { render } from 'react-dom'; ``` @@ -226,7 +194,7 @@ Once you open `index.tsx` you should follow these steps to get your base Applica 3. And then add these last two lines to target the `root` element by using the ID that is on it: ```tsx - const rootElement = document.getElementById("root"); + const rootElement = document.getElementById("root") as Element; const root = createRoot(rootElement); ``` @@ -238,8 +206,7 @@ Once you open `index.tsx` you should follow these steps to get your base Applica Everything has been added. We are nearly there and will need to perform a final few checks before starting our dev project. 1. Be sure that Pieces OS is running -2. Double check that the port is `localhost:1000` -3. (optional) Run another npm install (because it never hurts) +2. (optional) Run another npm install (because it never hurts) Now that everything is ready to go, lets run this command here: @@ -250,10 +217,34 @@ npm run start And after a few seconds you should be able to see in your Chrome browser (or your primary browser) a blank window that looks like this: -![Getting a 200 Back on Connect](/assets/success_connect.png) - ##### **You have now successfully set up your dev environment, and will be ready to test different endpoints inside of Pieces OS.** +## Creating a Copilot +The following examples show how to use the Pieces Copilot and some of the endpoints available. Read more about the copilot on this article: [Creating your own Open Source Copilot](https://code.pieces.app/blog/build-your-own-open-source-copilot-with-pieces). + +### Use Pieces.QGPTStreamInput +You can query the Pieces Copilot out of the box (after installation) with no application context set. The stream input is structured as a question object, containing a query and a parameter for relevance called `relevant`: + +```typescript +const input: Pieces.QGPTStreamInput = { + question: { + query, + relevant: {iterable: []} + }, +} +```` + +Then you can use a number of stream listeners to inside of [something like a websocket like seen here](https://jwaf.pieces.cloud/?p=c79e46aa7a) to deal with any JSON configuration. + +### Receiving Answers with Pieces.QGPTQuestionAnswer +When you get a response back from the copilot after asking a question, you may need to type it accordingly to access the appropriate properties. Here would be an example if getting back the first answer message following a question that was sent over: + +```typescript +const answer: Pieces.QGPTQuestionAnswer | undefined = result.question?.answers.iterable[0]; +``` + +Read more on the specifics of the Pieces Copilot logic and [endpoints on this copilot specific repo](https://github.com/pieces-app/pieces-copilot-vanilla-typescript-example). + ## Connecting your Application When Pieces OS is running in the background of your machine, it is communicating with other local applications that use Pieces software, and up until recently only supporting internally built tools. @@ -263,16 +254,14 @@ to avoid any issues with other applications.== ### Creating `Application` The `application` model describes what application a format or analytics event originated from. This is passed along when initializing your dev environment and creates a connection to Pieces OS. -To create the `Application` object for your project, you will need to make sure that you have the following three things: +To create the `Application` object for your project, you will need to make sure that you have the following two things: -1. Create a `tracked_application` json object to hold your post request data -2. Define your `url` for the `/connect` function -3. Output using `console.log()` following your `connect()` method is complete +1. Create a `tracked_application` json object to hold your formatted data +2. Output using `console.log()` following your `connect()` method is complete ***We will go over the different usages in each of these steps one at a time to bring up any specificities that may need a deeper explanation.*** - -#### `tracked_application` +#### Using `tracked_application` Connecting your application here is as easy as a single **POST** request and can be done via the Response interface of the **Fetch Api**. Remember that you can name this whatever you would like to, just be sure to include the updated variable name in the `options` down below. > When creating the `tracked_application` item, you will need to use a type that is not available inside the current `npm_deployment`. @@ -289,16 +278,17 @@ const tracked_application = { } ``` -- **name**: Brave +- **name**: OpenSource - **platform**: Depending on your current environment, you need to set the platform parameter to match your current operating system. Select between `.Macos`, `.Windows`, `.Linux` +- **version**: A string value that can be any string value and can be used to track the application you are building > **Imports** > Be sure to double-check that you have the following import added to the first few lines of your `index.tsx` file if you have not already: `import * as Pieces from "@pieces.app/pieces-os-client";` -### Creating `connect()` Function +### Connect using `Pieces.ConnectorApi()` and `tracked_application` When your program starts, it needs to connect to Pieces OS to gain access to any functional data and to exchange information on the `localhost:1000` route. Now that you have your `tracked_application` - lets get into the details. -Start by defining you connect function and the prepare the `connectorApi` on `Pieces.ConnectorApi().connect()` passing in the `tracked_applicaition` we created above: +Start by defining you connect function and prepare the `connectorApi` on `Pieces.ConnectorApi().connect()` passing in the `tracked_applicaition` we created above: ```tsx export async function connect(): Promise { @@ -315,7 +305,7 @@ Here is the entire connect function for you to double-check your work: ```tsx const tracked_application = { - name: Pieces.ApplicationNameEnum.Unknown, + name: Pieces.ApplicationNameEnum.OpenSource, version: '0.0.1', platform: Pieces.PlatformEnum.Macos, } @@ -342,7 +332,7 @@ Inside your terminal at the root directory of your project, use NPM to run one o npm run start ``` -And you should have the same content in the main browser window as before once this completes. But if you open up your inspector using `cmd+option+i` or `ctrl+shift+c` you will see this inside of your console: +And you should have the same content in the main browser window as before once this completes. But if you open up your inspector using `cmd + option + i` or `ctrl + shift + c` you will see this inside of your console: ![Console Output](assets/image.png) @@ -350,14 +340,16 @@ This includes both the full OS response object with all the data that you will n Follow along with these next steps to learn about **assets and formats,** two things that are very important for managing any form of data with Pieces OS. -## Getting Started with `Asset` + `/assets` -**Asset** is a very important models who's primary purpose is to manage the seeded data that comes in to the application, and is stored inside of Pieces OS. Each asset is a identifiable piece of saved data, or pre-seeded data. +## Getting Started with `Pieces.AssetApi` + `Pieces.AssetsApi` -**Assets** is equally important, but instead of containing a single asset with parameters storing data on it, Assets serves as the list of `type: Asset` objects that are stored there. Also you will find the operations for adding, deleting, searching, and other functions that are related to referencing a number of different snippets to make a comparison. For instance: +First lets define what these two things are: -> If I want to create a snippet (lets call it `var`), I need to send this to the master `Assets` list, you would first create `var` itself with the proper formats and data added to the `var` object, then send the newly created SeededAsset over to the Assets list (assets/create). Then you will receive the asset back as the response from the server. Cool, right? +* **Asset**: a very important models who's primary purpose is to manage the seeded data that comes in to the application, and is stored inside of Pieces OS. Each asset is a identifiable piece of saved data, or pre-seeded data. + +* **Assets**: equally important, but instead of containing a single asset with parameters storing data on it, Assets serves as the list of `type: Asset` objects that are stored there. Also you will find the operations for adding, deleting, searching, and other functions that are related to referencing a number of different snippets to make a comparison. For instance: + +If I want to create a snippet (lets call it `var`), I need to send this to the master `Assets` list, you would first create `var` itself with the proper formats and data added to the `var` object, then send the newly created SeededAsset over to the Assets list (assets/create). Then you will receive the asset back as the response from the server. Cool, right? -> **HEY! Read this.** > Traditionally, `Assets` is a linear list of flat `Asset` objects stored in an array or list. > > **You can use identifiers to get a specific asset from the asset list called a UUID.** But you'll learn more about that later on. @@ -368,11 +360,7 @@ Initially when creating your application, you will have no snippets saved to you > Check out `localhost:1000/assets` while Pieces OS is running to see the empty object that is there. #### **Creating your First Asset** -While creating an asset, there are some required parameters that you will need to be sure to include the proper **format** data. - -> **Explaining Format** -> -> For each `Asset` object, each required parameter must be included, and the Asset must be seeded before it is sent to be created. +While creating an asset, there are some required parameters that you will need to be sure to include the proper **format** data. For each `Asset` object, each required parameter must be included, and the Asset must be seeded before it is sent to be created. #### SeededAsset This seed data will become the asset. You can use this structure to provide data to Pieces OS, and will include fewer parameters than what you will get back in your response. Lets get started with the seeded asset formatting before we pass this over to `/Assets`. @@ -403,16 +391,16 @@ connect().then(__ => { ``` -### `/assets/create` +### `Pieces.AssetsApi().assetsCreateNewAsset()` Now before continuing forward, we will need to prepare the `create()` function to connect to the proper `Assets/create` endpoint. Create slightly differs from connect, since previously our json object did not require any new data that was returned back from the server. In this case **we will need to include the application data that was returned back from our initial call to `/connect`.** The `create()` function needs to accomplish a few things: 1. Create a new asset using our simple `SeededAsset` configuration that we just created as the `seed` object -2. Send a POST request to the new `http://localhost:1000/assets/create` with out data +2. Send request via `Pieces.AssetsApi().assetsCreateNewAsset()` 3. Return the response back after this is completed -Here is what the `create()` function looks like in its entirety: +Here is what the `createAsset()` function looks like in its entirety: ```tsx function createAsset() { @@ -453,10 +441,10 @@ Once you receive your response back from Pieces OS, you will notice the drastic The response back will look similar to the following: [https://jwaf.pieces.cloud/?p=24e242a85e](https://jwaf.pieces.cloud/?p=24e242a85e) -## Assets Snapshot (assets/snapshot) -Now when you follow this guide, you will be receiving this data back from inside your console in the browser. But if you would like to view your data incrementally through the full browser window, you can navigate to `http://localhost:1000/assets` to view a full list of snippets that have been saved. +## Get Assets Snapshot `Pieces.AssetsApi().assetsSnapshot()` +Now when you follow this guide, you will be receiving this data back from inside your console in the browser. But if you would like to view your data incrementally through the full browser window, you can navigate to `http://localhost:1000/assets` to view a full list of snippets that have been saved in your browser, or you could log to the console using `Pieces.AssetsApi().assetsSnapshot()`. + -As you move through your assets there are a number of things you may need your full assets list for without needing all of your data. (for example: the list view and carousel views in Pieces for Developers) To get your assets snapshot, you can use this to list each asset: @@ -471,7 +459,7 @@ new Pieces.AssetsApi().assetsSnapshot({}).then(_assetList => { Each asset will have and ID on it that can be used to match a singular asset here. Very useful when trying to get a specific asset from your full assetsSnapshot. -## Using asset/update +## Using `Pieces.AssetApi().assetUpdate()` to Rename Snippet Individual assets can be manipulated with a number of different properties and metadata. You can add **titles**, **annotations**, **tags**, **links**, **anchors**, and much more all through this single endpoint. To use it properly first use the assetSnapshot to get your asset using its ID property, and store your asset in a variable in your `.then()`. You can then adjust any of the properties on this asset you have stored on `_asset`, then pass into `requestParameters` on the `assetUpdate` endpoint. Check out this code block with an example of how to rename an asset: @@ -557,7 +545,7 @@ function refreshSnippetList() { I added this to the top level for reactivity inside the main `App()` call. You can choose to place this in a different location if you are not in need of any reactive data. -## Delete Using /assets/delete +## Delete Using `Pieces.AssetsApi().assetsDeleteAsset()` Assets can be deleted from your Assets list entirely by passing them into the `assetsDeleteAsset` endpoint. Just like the above example to rename a specific asset, you will need the ID of the asset that you are trying to remove. In order to get that you will need to use assetSnapshot in tandem with your delete endpoint: @@ -573,17 +561,33 @@ Assets can be deleted from your Assets list entirely by passing them into the `a After a successful delete, you may have to reload your browser window in order to see the updated snippet list. - > **Recommendation** > We use [JSON Viewer](https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh) internally when developing and **recommend** using some form of web based extension that assists with reading JSON DATA +## Use `Pieces.SearchApi()` +The search API can be used to filter or search through snippets that have been saved, then perform specific actions on them based on a set of rules. Here is a brief example of searching where `query: "page"` is your search term: + +```typescript +new Pieces.SearchApi().fullTextSearch({ query: "page" }).then( searchedAssets => { + + // get the "ID" or identifier of the first match on the string you passed in as the query: + let firstSearchMatchAssetIdentifier = searchedAssets.iterable[0].identifier; + + let matchName: String; + + // take that identifier to get your assets name using the Pieces.AssetApi() + new Pieces.AssetApi().assetSnapshot({asset: firstSearchMatchAssetIdentifier}).then((asset) => { + // assign that name to the matchName variable: + matchName = asset.name; + console.log(matchName); + }) + // then you can do whatever you would like with that match: + return matchName; +}) +``` ## Conclusion -This is a very simple guide on how to get up and running using the @pieces.app/pieces-os-client npm package and create a web environment that you can build on top of. **Fork this repo** to get started and learn about the depth of possibilities you have with Pieces OS. - -More guides will be coming soon around: -- Creating a personal Copilot that understands your context -- Examples on `/search` endpoints -- Improvements to the project structure + UI -- Testing custom implementations and combining endpoints -- ...more! +This is a very simple guide on how to get up and running using the @pieces.app/pieces-os-client npm package and create a web environment that you can build on top of along with examples on how to use some of the specific endpoints as well. **Fork this repo** to get started and learn about the depth of possibilities you have with Pieces OS. + +To continue learning about the endpoints, other supported languages, and more documentation, check out the [OpenSource repo](https://github.com/pieces-app/opensource). +