Skip to content

Commit

Permalink
Rename functions to AIFunctions
Browse files Browse the repository at this point in the history
  • Loading branch information
psykhi committed Mar 6, 2024
1 parent ae2ab3b commit 3bc57d1
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 99 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "opperai",
"version": "0.3.0",
"version": "0.3.1",
"description": "The official Node library for the OpperAi API",
"main": "dist/index.js",
"types": "dist/index.js",
Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/api-resource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ describe('APIResource', () => {

it('should close the stream when the generator is done', async () => {
// Mock async generator that immediately finishes
async function* asyncGenerator() { }
async function* asyncGenerator() {}

const iterator = asyncGenerator();
// @ts-expect-error Testing protected prop
Expand Down
4 changes: 1 addition & 3 deletions src/__tests__/client-jsdom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import Client from '../index';

describe('OpperAIClient jsdom', () => {
it('should throw an error if dangerouslyAllowBrowser is not set to true in a browser-like environment', () => {
expect(
() => new Client({ apiKey: 'test-api-key', dangerouslyAllowBrowser: false })
).toThrow(
expect(() => new Client({ apiKey: 'test-api-key', dangerouslyAllowBrowser: false })).toThrow(
"It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`"
);
});
Expand Down
70 changes: 35 additions & 35 deletions src/api-resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,11 @@ class APIResource {
* @returns A promise that resolves to the fetch response.
* @throws {APIError} If the response status is not 200.
*/
protected async doPost(url: string, body: string, controller?: AbortController | null | undefined) {
protected async doPost(
url: string,
body: string,
controller?: AbortController | null | undefined
) {
const headers = this._client.calcAuthorizationHeaders();

const response = await fetch(url, {
Expand All @@ -151,19 +155,21 @@ class APIResource {
return response;
}



/**
* This method sends a PUT request to the specified URL with the provided body.
* If an AbortController is provided, it will be used to cancel the request.
* The response is a promise that resolves to the fetch response.
* @param url - The URL to send the PUT request to.
* @param body - The body of the PUT request.
* @param controller - Optional AbortController to cancel the request.
* @returns A promise that resolves to the fetch response.
* @throws {APIError} If the response status is not 200.
*/
protected async doPut(url: string, body: string, controller?: AbortController | null | undefined) {
* This method sends a PUT request to the specified URL with the provided body.
* If an AbortController is provided, it will be used to cancel the request.
* The response is a promise that resolves to the fetch response.
* @param url - The URL to send the PUT request to.
* @param body - The body of the PUT request.
* @param controller - Optional AbortController to cancel the request.
* @returns A promise that resolves to the fetch response.
* @throws {APIError} If the response status is not 200.
*/
protected async doPut(
url: string,
body: string,
controller?: AbortController | null | undefined
) {
const headers = this._client.calcAuthorizationHeaders();

const response = await fetch(url, {
Expand Down Expand Up @@ -205,22 +211,19 @@ class APIResource {
});

if (!response.ok) {
throw new APIError(
response.status,
`Failed to fetch request ${url}: ${response.statusText}`
);
throw new APIError(response.status, `Failed to fetch request ${url}: ${response.statusText}`);
}

return response;
}

/**
* This method sends a DELETE request to the specified URL.
* The response is a promise that resolves to the fetch response.
* @param url - The URL to send the `DELETE` request to.
* @returns A promise that resolves to the fetch response.
* @throws {APIError} If the response status is not 200.
*/
* This method sends a DELETE request to the specified URL.
* The response is a promise that resolves to the fetch response.
* @param url - The URL to send the `DELETE` request to.
* @returns A promise that resolves to the fetch response.
* @throws {APIError} If the response status is not 200.
*/
protected async doDelete(url: string) {
const headers = this._client.calcAuthorizationHeaders();
console.log('headers', headers);
Expand All @@ -234,10 +237,7 @@ class APIResource {
console.log('response', response);

if (!response.ok) {
throw new APIError(
response.status,
`Failed to fetch request ${url}: ${response.statusText}`
);
throw new APIError(response.status, `Failed to fetch request ${url}: ${response.statusText}`);
}

return response;
Expand Down Expand Up @@ -289,28 +289,28 @@ class APIResource {
};
protected calcURLIndex = (id: number) => {
return `${this._client.baseURL}/v1/indexes/${id}`;
}
};
protected calcURLAddIndex = (id: number) => {
return `${this._client.baseURL}/v1/indexes/${id}/index`;
}
};
protected calcURLQueryIndex = (id: number) => {
return `${this._client.baseURL}/v1/indexes/${id}/query`;
}
};
protected calcURLCreateFunction = () => {
return `${this._client.baseURL}/api/v1/functions`;
}
};
protected calcURLGetFunctionByPath = (path: string) => {
return `${this._client.baseURL}/api/v1/functions/by_path/${path}`;
}
};
protected calcURLUpdateFunction = (id: number) => {
return `${this._client.baseURL}/api/v1/functions/${id}`;
}
};
protected calcURLEvents = () => {
return `${this._client.baseURL}/v1/events`;
}
};
protected calcURLEvent = (uuid: string) => {
return `${this.calcURLEvents()}/${uuid}`;
}
};
}

export default APIResource;
70 changes: 35 additions & 35 deletions src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,47 +3,47 @@ import { OpperError } from './errors';
import { Event } from './types';

class Events extends APIResource {
/**
* This method creates a new event in the OpperAI API.
* It sends a POST request to the events endpoint with the event data.
* @param event - The event data to be created.
* @returns A promise that resolves to the created event object.
* @throws {OpperError} If the response status is not 200.
*/
public async create(event: Event): Promise<Event> {
const response = await this.doPost(this.calcURLEvents(), JSON.stringify(event));

if (response.status !== 200) {
throw new OpperError(`Failed to create event: ${response.statusText}`);
}

const data = await response.json();

return data;
/**
* This method creates a new event in the OpperAI API.
* It sends a POST request to the events endpoint with the event data.
* @param event - The event data to be created.
* @returns A promise that resolves to the created event object.
* @throws {OpperError} If the response status is not 200.
*/
public async create(event: Event): Promise<Event> {
const response = await this.doPost(this.calcURLEvents(), JSON.stringify(event));

if (response.status !== 200) {
throw new OpperError(`Failed to create event: ${response.statusText}`);
}

/**
* This method updates an existing event in the OpperAI API.
* It sends a PUT request to the events endpoint with the event data.
* @param event - The event data to be updated.
* @returns A promise that resolves to the updated event object.
* @throws {OpperError} If the response status is not 200 or if the event does not have a uuid.
*/
public async update(event: Event): Promise<Event> {
if (!event.uuid) {
throw new OpperError('Event uuid is required for update');
}
const data = await response.json();

return data;
}

/**
* This method updates an existing event in the OpperAI API.
* It sends a PUT request to the events endpoint with the event data.
* @param event - The event data to be updated.
* @returns A promise that resolves to the updated event object.
* @throws {OpperError} If the response status is not 200 or if the event does not have a uuid.
*/
public async update(event: Event): Promise<Event> {
if (!event.uuid) {
throw new OpperError('Event uuid is required for update');
}

const response = await this.doPut(this.calcURLEvent(event.uuid), JSON.stringify(event));
const response = await this.doPut(this.calcURLEvent(event.uuid), JSON.stringify(event));

if (response.status !== 200) {
throw new OpperError(`Failed to update event: ${response.statusText}`);
}
if (response.status !== 200) {
throw new OpperError(`Failed to update event: ${response.statusText}`);
}

const data = await response.json();
const data = await response.json();

return data;
}
return data;
}
}

export default Events;
11 changes: 4 additions & 7 deletions src/functions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Chat, Function, OpperAIChatResponse, OpperAIStream } from './types';
import { AIFunction, Chat, OpperAIChatResponse, OpperAIStream } from './types';

import APIResource from './api-resource';
import { APIError, OpperError } from './errors';
Expand Down Expand Up @@ -32,7 +32,7 @@ class Functions extends APIResource {
};
}

public async update(f: Function): Promise<Function> {
public async update(f: AIFunction): Promise<AIFunction> {
if (!f.id) {
throw new OpperError('Function id is required');
}
Expand All @@ -43,17 +43,15 @@ class Functions extends APIResource {
return f;
}


public async create(f: Function, update: boolean = false): Promise<Function> {
public async create(f: AIFunction, update: boolean = false): Promise<AIFunction> {
try {
let response = await this.doGet(this.calcURLGetFunctionByPath(f.path));
const response = await this.doGet(this.calcURLGetFunctionByPath(f.path));
if (response.status === 200) {
if (!update) {
throw new OpperError(`Function with path ${f.path} already exists`);
}
return await this.update(f);
}

} catch (error) {
if (error instanceof APIError) {
if (error.status !== 404) {
Expand All @@ -73,7 +71,6 @@ class Functions extends APIResource {
throw new OpperError(`Failed to create function: ${response.statusText}`);
}


/**
* This method is a helper which can be used in node middleware
* to pipe the OpperAI chat stream directly to the client. See examples.
Expand Down
15 changes: 11 additions & 4 deletions src/indexes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Document, Filter, Index } from './types';

import APIResource from './api-resource';


class Indexes extends APIResource {
/**
* This method retrieves a list of indexes from the OpperAI API.
Expand Down Expand Up @@ -32,7 +31,7 @@ class Indexes extends APIResource {
}

public async create(name: string): Promise<Index> {
const response = await this.doPost(this.calcURLIndexes(), JSON.stringify({ "name": name }));
const response = await this.doPost(this.calcURLIndexes(), JSON.stringify({ name: name }));

const data = await response.json();

Expand All @@ -47,8 +46,16 @@ class Indexes extends APIResource {
await this.doPost(this.calcURLAddIndex(index.id), JSON.stringify(document));
}

public async retrieve(index: Index, query: string, k: number, filters: Filter[]): Promise<Document[]> {
const response = await this.doPost(this.calcURLQueryIndex(index.id), JSON.stringify({ q: query, k: k, filters: filters }));
public async retrieve(
index: Index,
query: string,
k: number,
filters: Filter[]
): Promise<Document[]> {
const response = await this.doPost(
this.calcURLQueryIndex(index.id),
JSON.stringify({ q: query, k: k, filters: filters })
);

const documents: Document[] = await response.json();

Expand Down
25 changes: 12 additions & 13 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ export type IndexFileData = {
original_filename: string;
size: number;
index_status:
| 'init'
| 'pending'
| 'uploading'
| 'indexing'
| 'success'
| 'indexed'
| 'error'
| 'failed'
| 'invalid';
| 'init'
| 'pending'
| 'uploading'
| 'indexing'
| 'success'
| 'indexed'
| 'error'
| 'failed'
| 'invalid';
n_vectors: number;
};

Expand All @@ -80,21 +80,20 @@ export interface Filter {
value: string | number | Array<string | number>;
}


export type Document = {
id?: string;
key?: string; // a unique key that one can use if you want to update the document
content: string;
metadata: Record<string, unknown>;
}
export type Function = {
};
export type AIFunction = {
id?: number;
path: string;
description: string;
instructions: string;
model?: string;
index_ids?: number[];
}
};

export type Event = {
uuid?: string;
Expand Down

0 comments on commit 3bc57d1

Please sign in to comment.