repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
TokenValidator.deleteKey
public deleteKey(kid: string) { this.cacheWrapper?.cache.del(kid); }
/** * Deletes a key from the cache. * @param {string} kid The key ID to delete from the cache. */
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/functions/middleware/tokenValidator.ts#L163-L165
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
ConsultantApiService.getApiConsultantForBaseConsultant
async getApiConsultantForBaseConsultant(consultant: Consultant, assignments: Assignment[]): Promise<ApiConsultant> { const result = { id: consultant.id, name: consultant.name, email: consultant.email, phone: consultant.phone, consultantPhotoUrl: consultant.consultantPhotoUrl, location: consultant.location, skills: consultant.skills, certifications: consultant.certifications, roles: consultant.roles, projects: [], forecastThisMonth: 0, forecastNextMonth: 0, deliveredLastMonth: 0, deliveredThisMonth: 0 } assignments = assignments.filter((a) => a.consultantId === consultant.id); result.forecastThisMonth = 0; result.forecastNextMonth = 0; result.deliveredLastMonth = 0; result.deliveredThisMonth = 0; for (let assignment of assignments) { const project = await ProjectDbService.getProjectById(assignment.projectId); const { lastMonthHours: forecastLastMonth, thisMonthHours: forecastThisMonth, nextMonthHours: forecastNextMonth } = this.findHours(assignment.forecast); const { lastMonthHours: deliveredLastMonth, thisMonthHours: deliveredThisMonth, nextMonthHours: deliveredNextMonth } = this.findHours(assignment.delivered); result.projects.push({ projectName: project.name, projectDescription: project.description, projectLocation: project.location, mapUrl: project.mapUrl, clientName: project.clientName, clientContact: project.clientContact, clientEmail: project.clientEmail, role: assignment.role, forecastThisMonth: forecastThisMonth, forecastNextMonth: forecastNextMonth, deliveredLastMonth: deliveredLastMonth, deliveredThisMonth: deliveredThisMonth }); result.forecastThisMonth += forecastThisMonth; result.forecastNextMonth += forecastNextMonth; result.deliveredLastMonth += deliveredLastMonth; result.deliveredThisMonth += deliveredThisMonth; } return result; }
// Augment a base consultant to get an ApiConsultant
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/services/ConsultantApiService.ts#L85-L140
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
ConsultantApiService.findHours
private findHours(hours: HoursEntry[]): { lastMonthHours: number, thisMonthHours: number, nextMonthHours: number } { const now = new Date(); const thisMonth = now.getMonth(); const thisYear = now.getFullYear(); const lastMonth = thisMonth === 0 ? 11 : thisMonth - 1; const lastYear = thisMonth === 0 ? thisYear - 1 : thisYear; const nextMonth = thisMonth === 11 ? 0 : thisMonth + 1; const nextYear = thisMonth === 11 ? thisYear + 1 : thisYear; const result = { lastMonthHours: hours.find((h) => h.month === lastMonth + 1 && h.year === lastYear)?.hours || 0, thisMonthHours: hours.find((h) => h.month === thisMonth + 1 && h.year === thisYear)?.hours || 0, nextMonthHours: hours.find((h) => h.month === nextMonth + 1 && h.year === nextYear)?.hours || 0 }; return result; }
// Extract this and next month's hours from an array of HoursEntry
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/services/ConsultantApiService.ts#L143-L160
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
Identity.validateRequest
public async validateRequest(req: HttpRequest): Promise<ApiConsultant> { // Default user used for unauthenticated testing let userId = "1"; let userName = "Avery Howard"; let userEmail = "avery@treyresearch.com"; // Try to validate the token and get user's basic information try { const { AAD_APP_CLIENT_ID, AAD_APP_TENANT_ID } = process.env; const token = req.headers.get("Authorization")?.split(" ")[1]; if (!token) { throw new HttpError(401, "Authorization token not found"); } // Get the JWKS URL for the Microsoft Entra common tenant const entraJwksUri = await getEntraJwksUri(AAD_APP_TENANT_ID, CloudType.Public); // Create a new token validator with the JWKS URL const validator = new TokenValidator({ jwksUri: entraJwksUri, }); // create a new token validator for the Microsoft Entra common tenant // if (!this.validator) { // // We need a new validator object which we will continue to use on subsequent // // requests so it can cache the Entra ID signing keys // // For multitenant, use: // // const entraJwksUri = await getEntraJwksUri(); // const entraJwksUri = await getEntraJwksUri(AAD_APP_TENANT_ID); // this.validator = new TokenValidator({ // jwksUri: entraJwksUri // }); // console.log ("Token validator created"); // } // Use these options for single-tenant applications const options: ValidateTokenOptions = { allowedTenants: [AAD_APP_TENANT_ID], audience: `${AAD_APP_CLIENT_ID}`, issuer: `https://login.microsoftonline.com/${AAD_APP_TENANT_ID}/v2.0`, scp: ["access_as_user"] }; // validate the token const validToken = await validator.validateToken(token, options); userId = validToken.oid; userName = validToken.name; userEmail = validToken.preferred_username; console.log(`Request ${this.requestNumber++}: Token is valid for user ${userName} (${userId})`); } catch (ex) { // Token is missing or invalid - return a 401 error console.error(ex); throw new HttpError(401, "Unauthorized"); } // Get the consultant record for this user; create one if necessary let consultant: ApiConsultant = null; try { consultant = await ConsultantApiService.getApiConsultantById(userId); } catch (ex) { if (ex.status !== 404) { throw ex; } // Consultant was not found, so we'll create one below consultant = null; } if (!consultant) consultant = await this.createConsultantForUser(userId, userName, userEmail); return consultant; }
// Number the requests for logging purposes
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/services/IdentityService.ts#L15-L88
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
ProjectApiService.getApiProject
async getApiProject(project: Project, assignments: Assignment[]): Promise<ApiProject> { const result = project as ApiProject; assignments = assignments.filter((a) => a.projectId === project.id); result.consultants = []; result.forecastThisMonth = 0; result.forecastNextMonth = 0; result.deliveredLastMonth = 0; result.deliveredThisMonth = 0; for (let assignment of assignments) { const consultant = await ConsultantDbService.getConsultantById(assignment.consultantId); const { lastMonthHours: forecastLastMonth, thisMonthHours: forecastThisMonth, nextMonthHours: forecastNextMonth } = this.findHours(assignment.forecast); const { lastMonthHours: deliveredLastMonth, thisMonthHours: deliveredThisMonth, nextMonthHours: deliveredNextMonth } = this.findHours(assignment.delivered); result.consultants.push({ consultantName: consultant.name, consultantLocation: consultant.location, role: assignment.role, forecastThisMonth: forecastThisMonth, forecastNextMonth: forecastNextMonth, deliveredLastMonth: deliveredLastMonth, deliveredThisMonth: deliveredThisMonth }); result.forecastThisMonth += forecastThisMonth; result.forecastNextMonth += forecastNextMonth; result.deliveredLastMonth += deliveredLastMonth; result.deliveredThisMonth += deliveredThisMonth; } return result; }
// Augment a project to get an ApiProject
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/services/ProjectApiService.ts#L57-L94
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
ProjectApiService.findHours
private findHours(hours: HoursEntry[]): { lastMonthHours: number, thisMonthHours: number, nextMonthHours: number } { const now = new Date(); const thisMonth = now.getMonth(); const thisYear = now.getFullYear(); const lastMonth = thisMonth === 0 ? 11 : thisMonth - 1; const lastYear = thisMonth === 0 ? thisYear - 1 : thisYear; const nextMonth = thisMonth === 11 ? 0 : thisMonth + 1; const nextYear = thisMonth === 11 ? thisYear + 1 : thisYear; const result = { lastMonthHours: hours.find((h) => h.month === lastMonth + 1 && h.year === lastYear)?.hours || 0, thisMonthHours: hours.find((h) => h.month === thisMonth + 1 && h.year === thisYear)?.hours || 0, nextMonthHours: hours.find((h) => h.month === nextMonth + 1 && h.year === nextYear)?.hours || 0 }; return result; }
// Extract this and next month's hours from an array of HoursEntry
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research-auth/src/services/ProjectApiService.ts#L97-L114
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
ConsultantApiService.getApiConsultantForBaseConsultant
async getApiConsultantForBaseConsultant(consultant: Consultant, assignments: Assignment[]): Promise<ApiConsultant> { const result = { id: consultant.id, name: consultant.name, email: consultant.email, phone: consultant.phone, consultantPhotoUrl: consultant.consultantPhotoUrl, location: consultant.location, skills: consultant.skills, certifications: consultant.certifications, roles: consultant.roles, projects: [], forecastThisMonth: 0, forecastNextMonth: 0, deliveredLastMonth: 0, deliveredThisMonth: 0 } assignments = assignments.filter((a) => a.consultantId === consultant.id); result.forecastThisMonth = 0; result.forecastNextMonth = 0; result.deliveredLastMonth = 0; result.deliveredThisMonth = 0; for (let assignment of assignments) { const project = await ProjectDbService.getProjectById(assignment.projectId); const { lastMonthHours: forecastLastMonth, thisMonthHours: forecastThisMonth, nextMonthHours: forecastNextMonth } = this.findHours(assignment.forecast); const { lastMonthHours: deliveredLastMonth, thisMonthHours: deliveredThisMonth, nextMonthHours: deliveredNextMonth } = this.findHours(assignment.delivered); result.projects.push({ projectName: project.name, projectDescription: project.description, projectLocation: project.location, mapUrl: project.mapUrl, clientName: project.clientName, clientContact: project.clientContact, clientEmail: project.clientEmail, role: assignment.role, forecastThisMonth: forecastThisMonth, forecastNextMonth: forecastNextMonth, deliveredLastMonth: deliveredLastMonth, deliveredThisMonth: deliveredThisMonth }); result.forecastThisMonth += forecastThisMonth; result.forecastNextMonth += forecastNextMonth; result.deliveredLastMonth += deliveredLastMonth; result.deliveredThisMonth += deliveredThisMonth; } return result; }
// Augment a base consultant to get an ApiConsultant
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research/src/services/ConsultantApiService.ts#L85-L140
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
ConsultantApiService.findHours
private findHours(hours: HoursEntry[]): { lastMonthHours: number, thisMonthHours: number, nextMonthHours: number } { const now = new Date(); const thisMonth = now.getMonth(); const thisYear = now.getFullYear(); const lastMonth = thisMonth === 0 ? 11 : thisMonth - 1; const lastYear = thisMonth === 0 ? thisYear - 1 : thisYear; const nextMonth = thisMonth === 11 ? 0 : thisMonth + 1; const nextYear = thisMonth === 11 ? thisYear + 1 : thisYear; const result = { lastMonthHours: hours.find((h) => h.month === lastMonth + 1 && h.year === lastYear)?.hours || 0, thisMonthHours: hours.find((h) => h.month === thisMonth + 1 && h.year === thisYear)?.hours || 0, nextMonthHours: hours.find((h) => h.month === nextMonth + 1 && h.year === nextYear)?.hours || 0 }; return result; }
// Extract this and next month's hours from an array of HoursEntry
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research/src/services/ConsultantApiService.ts#L143-L160
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
Identity.validateRequest
public async validateRequest(req: HttpRequest): Promise<ApiConsultant> { // Default user used for unauthenticated testing let userId = "1"; let userName = "Avery Howard"; let userEmail = "avery@treyresearch.com"; // ** INSERT REQUEST VALIDATION HERE (see Lab E6) ** // Get the consultant record for this user; create one if necessary let consultant: ApiConsultant = null; try { consultant = await ConsultantApiService.getApiConsultantById(userId); } catch (ex) { if (ex.status !== 404) { throw ex; } // Consultant was not found, so we'll create one below consultant = null; } if (!consultant) consultant = await this.createConsultantForUser(userId, userName, userEmail); return consultant; }
// Number the requests for logging purposes
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research/src/services/IdentityService.ts#L13-L37
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
ProjectApiService.getApiProject
async getApiProject(project: Project, assignments: Assignment[]): Promise<ApiProject> { const result = project as ApiProject; assignments = assignments.filter((a) => a.projectId === project.id); result.consultants = []; result.forecastThisMonth = 0; result.forecastNextMonth = 0; result.deliveredLastMonth = 0; result.deliveredThisMonth = 0; for (let assignment of assignments) { const consultant = await ConsultantDbService.getConsultantById(assignment.consultantId); const { lastMonthHours: forecastLastMonth, thisMonthHours: forecastThisMonth, nextMonthHours: forecastNextMonth } = this.findHours(assignment.forecast); const { lastMonthHours: deliveredLastMonth, thisMonthHours: deliveredThisMonth, nextMonthHours: deliveredNextMonth } = this.findHours(assignment.delivered); result.consultants.push({ consultantName: consultant.name, consultantLocation: consultant.location, role: assignment.role, forecastThisMonth: forecastThisMonth, forecastNextMonth: forecastNextMonth, deliveredLastMonth: deliveredLastMonth, deliveredThisMonth: deliveredThisMonth }); result.forecastThisMonth += forecastThisMonth; result.forecastNextMonth += forecastNextMonth; result.deliveredLastMonth += deliveredLastMonth; result.deliveredThisMonth += deliveredThisMonth; } return result; }
// Augment a project to get an ApiProject
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research/src/services/ProjectApiService.ts#L57-L94
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
ProjectApiService.findHours
private findHours(hours: HoursEntry[]): { lastMonthHours: number, thisMonthHours: number, nextMonthHours: number } { const now = new Date(); const thisMonth = now.getMonth(); const thisYear = now.getFullYear(); const lastMonth = thisMonth === 0 ? 11 : thisMonth - 1; const lastYear = thisMonth === 0 ? thisYear - 1 : thisYear; const nextMonth = thisMonth === 11 ? 0 : thisMonth + 1; const nextYear = thisMonth === 11 ? thisYear + 1 : thisYear; const result = { lastMonthHours: hours.find((h) => h.month === lastMonth + 1 && h.year === lastYear)?.hours || 0, thisMonthHours: hours.find((h) => h.month === thisMonth + 1 && h.year === thisYear)?.hours || 0, nextMonthHours: hours.find((h) => h.month === nextMonth + 1 && h.year === nextYear)?.hours || 0 }; return result; }
// Extract this and next month's hours from an array of HoursEntry
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/cext-trey-research/src/services/ProjectApiService.ts#L97-L114
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
onTurnErrorHandler
const onTurnErrorHandler = async (context: TurnContext, error: Error) => { // This check writes out errors to console log .vs. app insights. // NOTE: In production environment, you should consider logging this to Azure // application insights. console.error(`\n [onTurnError] unhandled error: ${error}`); // Send a trace activity, which will be displayed in Bot Framework Emulator await context.sendTraceActivity( "OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError" ); // Send a message to the user await context.sendActivity(`The bot encountered unhandled error:\n ${error.message}`); await context.sendActivity("To continue to run this bot, please fix the bot source code."); };
// Catch-all for errors.
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-multiparam-ts/src/index.ts#L33-L50
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
onTurnErrorHandler
const onTurnErrorHandler = async (context: TurnContext, error: Error) => { // This check writes out errors to console log .vs. app insights. // NOTE: In production environment, you should consider logging this to Azure // application insights. console.error(`\n [onTurnError] unhandled error: ${error}`); // Send a trace activity, which will be displayed in Bot Framework Emulator await context.sendTraceActivity( "OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError" ); // Send a message to the user await context.sendActivity(`The bot encountered unhandled error:\n ${error.message}`); await context.sendActivity("To continue to run this bot, please fix the bot source code."); };
// Catch-all for errors.
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-action-ts/src/index.ts#L33-L50
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
SearchApp.handleTeamsMessagingExtensionQuery
public async handleTeamsMessagingExtensionQuery( context: TurnContext, query: MessagingExtensionQuery ): Promise<MessagingExtensionResponse> { switch (query.commandId) { case productSearchCommand.COMMAND_ID: { return productSearchCommand.handleTeamsMessagingExtensionQuery(context, query); } case discountedSearchCommand.COMMAND_ID: { return discountedSearchCommand.handleTeamsMessagingExtensionQuery(context, query); } case revenueSearchCommand.COMMAND_ID: { return revenueSearchCommand.handleTeamsMessagingExtensionQuery(context, query); } } }
// Handle search message extension
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-action-ts/src/searchApp.ts#L22-L39
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
SearchApp.onAdaptiveCardInvoke
public async onAdaptiveCardInvoke(context: TurnContext): Promise<AdaptiveCardInvokeResponse> { try { switch (context.activity.value.action.verb) { case 'ok': { return actionHandler.handleTeamsCardActionUpdateStock(context); } case 'restock': { return actionHandler.handleTeamsCardActionRestock(context); } case 'cancel': { return actionHandler.handleTeamsCardActionCancelRestock(context); } case 'edit': { return actionHandler.handleTeamsCardActionEditProduct(context); } case 'edit-save': { return actionHandler.handleTeamsCardActionSaveProduct(context); } case 'refresh': { return actionHandler.handleTeamsCardActionRefresh(context); } default: return CreateActionErrorResponse(400, 0, `ActionVerbNotSupported: ${context.activity.value.action.verb} is not a supported action verb.`); } } catch (err) { return CreateActionErrorResponse(500, 0, err.message); } }
// Handle adaptive card actions
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-action-ts/src/searchApp.ts#L42-L72
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
isMatchingStatus
function isMatchingStatus(inventoryStatusQuery: string, product: ProductEx): boolean { const query = inventoryStatusQuery.toLowerCase(); if (query.startsWith("out")) { // Out of stock return product.UnitsInStock === 0; } else if (query.startsWith("low")) { // Low stock return product.UnitsInStock <= product.ReorderLevel; } else if (query.startsWith("on")) { // On order return product.UnitsOnOrder > 0; } else { // In stock return product.UnitsInStock > 0; } }
// Returns true if the inventory status in a product matches the query using
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-action-ts/src/northwindDB/products.ts#L71-L87
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
isInRange
function isInRange(rangeExpression: string, value: number) { let result = false; // Return false if the expression is malformed if (rangeExpression.indexOf('-')< 0) { // If here, we have a single value or a malformed expression const val = Number(rangeExpression); if (!isNaN(val)) { result = value === val; } } else if (rangeExpression.indexOf('-') === rangeExpression.length-1) { // If here we have a single lower bound or a malformed expression const lowerBound = Number(rangeExpression.slice(0,-1)); if (!isNaN(lowerBound)) { result = value >= lowerBound; } } else { // If here we have a range or a malformed expression const bounds = rangeExpression.split('-'); const lowerBound = Number(bounds[0]); const upperBound = Number(bounds[1]); if (!isNaN(lowerBound) && !isNaN(upperBound)) { result = lowerBound <= value && upperBound >= value; } } return result; }
// Used to filter based on a range entered in the stockLevel parameter
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-action-ts/src/northwindDB/products.ts#L91-L117
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
getAllProductsEx
async function getAllProductsEx(): Promise<ProductEx[]> { // Ensure reference data are loaded categories = categories ?? await loadReferenceData<Category>(TABLE_NAME.CATEGORY); suppliers = suppliers ?? await loadReferenceData<Supplier>(TABLE_NAME.SUPPLIER); orderTotals = orderTotals ?? await loadOrderTotals(); // We always read the products fresh in case somebody made a change const result: ProductEx[] = []; const tableClient = TableClient.fromConnectionString(config.storageAccountConnectionString, TABLE_NAME.PRODUCT); const entities = tableClient.listEntities(); for await (const entity of entities) { const p = getProductExForEntity(entity); result.push(await p); } return result; }
// #endregion
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-action-ts/src/northwindDB/products.ts#L183-L201
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
onTurnErrorHandler
const onTurnErrorHandler = async (context: TurnContext, error: Error) => { // This check writes out errors to console log .vs. app insights. // NOTE: In production environment, you should consider logging this to Azure // application insights. console.error(`\n [onTurnError] unhandled error: ${error}`); // Send a trace activity, which will be displayed in Bot Framework Emulator await context.sendTraceActivity( "OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError" ); // Send a message to the user await context.sendActivity(`The bot encountered unhandled error:\n ${error.message}`); await context.sendActivity("To continue to run this bot, please fix the bot source code."); };
// Catch-all for errors.
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-ts/src/index.ts#L33-L50
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
SearchApp.handleTeamsMessagingExtensionQuery
public async handleTeamsMessagingExtensionQuery( context: TurnContext, query: MessagingExtensionQuery ): Promise<MessagingExtensionResponse> { switch (query.commandId) { case productSearchCommand.COMMAND_ID: { return productSearchCommand.handleTeamsMessagingExtensionQuery(context, query); } case discountedSearchCommand.COMMAND_ID: { return discountedSearchCommand.handleTeamsMessagingExtensionQuery(context, query); } } }
// Handle search message extension
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-ts/src/searchApp.ts#L20-L34
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
SearchApp.onAdaptiveCardInvoke
public async onAdaptiveCardInvoke(context: TurnContext): Promise<AdaptiveCardInvokeResponse> { try { switch (context.activity.value.action.verb) { case 'ok': { return actionHandler.handleTeamsCardActionUpdateStock(context); } case 'restock': { return actionHandler.handleTeamsCardActionRestock(context); } case 'cancel': { return actionHandler.handleTeamsCardActionCancelRestock(context); } case 'refresh': { return actionHandler.handleTeamsCardActionRefresh(context); } default: { console.log ('Unknown Invoke activity received'); return CreateActionErrorResponse(400, 0, `ActionVerbNotSupported: ${context.activity.value.action.verb} is not a supported action verb.`); } } } catch (err) { return CreateActionErrorResponse(500, 0, err.message); } }
// Handle adaptive card actions
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-ts/src/searchApp.ts#L37-L62
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
isMatchingStatus
function isMatchingStatus(inventoryStatusQuery: string, product: ProductEx): boolean { const query = inventoryStatusQuery.toLowerCase(); if (query.startsWith("out")) { // Out of stock return product.UnitsInStock === 0; } else if (query.startsWith("low")) { // Low stock return product.UnitsInStock <= product.ReorderLevel; } else if (query.startsWith("on")) { // On order return product.UnitsOnOrder > 0; } else { // In stock return product.UnitsInStock > 0; } }
// Returns true if the inventory status in a product matches the query using
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-ts/src/northwindDB/products.ts#L70-L86
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
isInRange
function isInRange(rangeExpression: string, value: number) { let result = false; // Return false if the expression is malformed if (rangeExpression.indexOf('-')< 0) { // If here, we have a single value or a malformed expression const val = Number(rangeExpression); if (!isNaN(val)) { result = value === val; } } else if (rangeExpression.indexOf('-') === rangeExpression.length-1) { // If here we have a single lower bound or a malformed expression const lowerBound = Number(rangeExpression.slice(0,-1)); if (!isNaN(lowerBound)) { result = value >= lowerBound; } } else { // If here we have a range or a malformed expression const bounds = rangeExpression.split('-'); const lowerBound = Number(bounds[0]); const upperBound = Number(bounds[1]); if (!isNaN(lowerBound) && !isNaN(upperBound)) { result = lowerBound <= value && upperBound >= value; } } return result; }
// Used to filter based on a range entered in the stockLevel parameter
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-ts/src/northwindDB/products.ts#L90-L116
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
getAllProductsEx
async function getAllProductsEx(): Promise<ProductEx[]> { await ensureReferenceDataLoaded(); // We always read the products fresh in case somebody made a change const result: ProductEx[] = []; const tableClient = TableClient.fromConnectionString(config.storageAccountConnectionString, TABLE_NAME.PRODUCT); const entities = tableClient.listEntities(); for await (const entity of entities) { const p = getProductExForEntity(entity); result.push(p); } return result; }
// #endregion
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-northwind-inventory-ts/src/northwindDB/products.ts#L188-L203
159c86a02b84a4ebba05ec606411afc76bf9d9ab
Microsoft-365-Copilot-Samples
github_2023
OfficeDev
typescript
onTurnErrorHandler
const onTurnErrorHandler = async (context: TurnContext, error: Error) => { // This check writes out errors to console log .vs. app insights. // NOTE: In production environment, you should consider logging this to Azure // application insights. console.error(`\n [onTurnError] unhandled error: ${error}`); // Send a trace activity, which will be displayed in Bot Framework Emulator await context.sendTraceActivity( "OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError" ); // Send a message to the user await context.sendActivity( `The bot encountered unhandled error:\n ${error.message}` ); await context.sendActivity( "To continue to run this bot, please fix the bot source code." ); };
// Catch-all for errors.
https://github.com/OfficeDev/Microsoft-365-Copilot-Samples/blob/159c86a02b84a4ebba05ec606411afc76bf9d9ab/samples/msgext-product-support-sso-ts/src/index.ts#L33-L54
159c86a02b84a4ebba05ec606411afc76bf9d9ab
smart-wallet
github_2023
passkeys-4337
typescript
UserOpBuilder.buildUserOp
async buildUserOp({ calls, maxFeePerGas, maxPriorityFeePerGas, keyId, }: { calls: Call[]; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint; keyId: Hex; }): Promise<UserOperationAsHex> { // calculate smart wallet address via Factory contract to know the sender const { account, publicKey } = await this._calculateSmartWalletAddress(keyId); // the keyId is the id tied to the user's public key // get bytecode const bytecode = await this.publicClient.getBytecode({ address: account, }); let initCode = toHex(new Uint8Array(0)); let initCodeGas = BigInt(0); if (bytecode === undefined) { // smart wallet does NOT already exists // calculate initCode and initCodeGas ({ initCode, initCodeGas } = await this._createInitCode(publicKey)); } // calculate nonce const nonce = await this._getNonce(account); // create callData const callData = this._addCallData(calls); // create user operation const userOp: UserOperation = { ...DEFAULT_USER_OP, sender: account, nonce, initCode, callData, maxFeePerGas, maxPriorityFeePerGas, }; // estimate gas for this partial user operation // real good article about the subject can be found here: // https://www.alchemy.com/blog/erc-4337-gas-estimation const { callGasLimit, verificationGasLimit, preVerificationGas } = await smartWallet.estimateUserOperationGas({ userOp: this.toParams(userOp), }); // set gas limits with the estimated values + some extra gas for safety userOp.callGasLimit = BigInt(callGasLimit); userOp.preVerificationGas = BigInt(preVerificationGas) * BigInt(10); userOp.verificationGasLimit = BigInt(verificationGasLimit) + BigInt(150_000) + BigInt(initCodeGas) + BigInt(1_000_000); // get userOp hash (with signature == 0x) by calling the entry point contract const userOpHash = await this._getUserOpHash(userOp); // version = 1 and validUntil = 0 in msgToSign are hardcoded const msgToSign = encodePacked(["uint8", "uint48", "bytes32"], [1, 0, userOpHash]); // get signature from webauthn const signature = await this.getSignature(msgToSign, keyId); return this.toParams({ ...userOp, signature }); }
// reference: https://ethereum.stackexchange.com/questions/150796/how-to-create-a-raw-erc-4337-useroperation-from-scratch-and-then-send-it-to-bund
https://github.com/passkeys-4337/smart-wallet/blob/f3aa9fd44646fde0316fc810e21cc553a9ed73e0/front/src/libs/smart-wallet/service/userOps/builder.ts#L54-L122
f3aa9fd44646fde0316fc810e21cc553a9ed73e0
openai-deno-build
github_2023
openai
typescript
APIPromise.asResponse
asResponse(): Promise<Response> { return this.responsePromise.then((p) => p.response); }
/** * Gets the raw `Response` instance instead of parsing the response * data. * * If you want to parse the response body but still get the `Response` * instance, you can use {@link withResponse()}. * * 👋 Getting the wrong TypeScript type for `Response`? * Try setting `"moduleResolution": "NodeNext"` if you can, * or add one of these imports before your first `import … from 'openai'`: * - `import 'openai/shims/node'` (if you're running on Node) * - `import 'openai/shims/web'` (otherwise) */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/core.ts#L155-L157
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
APIPromise.withResponse
async withResponse(): Promise< { data: T; response: Response; request_id: string | null | undefined } > { const [data, response] = await Promise.all([ this.parse(), this.asResponse(), ]); return { data, response, request_id: response.headers.get("x-request-id") }; }
/** * Gets the parsed response data, the raw `Response` instance and the ID of the request, * returned via the X-Request-ID header which is useful for debugging requests and reporting * issues to OpenAI. * * If you just want to get the raw `Response` instance without parsing it, * you can use {@link asResponse()}. * * 👋 Getting the wrong TypeScript type for `Response`? * Try setting `"moduleResolution": "NodeNext"` if you can, * or add one of these imports before your first `import … from 'openai'`: * - `import 'openai/shims/node'` (if you're running on Node) * - `import 'openai/shims/web'` (otherwise) */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/core.ts#L173-L181
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
getBrowserInfo
function getBrowserInfo(): BrowserInfo | null { if (typeof navigator === "undefined" || !navigator) { return null; } // NOTE: The order matters here! const browserPatterns = [ { key: "edge" as const, pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie" as const, pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie" as const, pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/, }, { key: "chrome" as const, pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/, }, { key: "firefox" as const, pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/, }, { key: "safari" as const, pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/, }, ]; // Find the FIRST matching browser for (const { key, pattern } of browserPatterns) { const match = pattern.exec(navigator.userAgent); if (match) { const major = match[1] || 0; const minor = match[2] || 0; const patch = match[3] || 0; return { browser: key, version: `${major}.${minor}.${patch}` }; } } return null; }
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/core.ts#L1085-L1126
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
applyHeadersMut
function applyHeadersMut(targetHeaders: Headers, newHeaders: Headers): void { for (const k in newHeaders) { if (!hasOwn(newHeaders, k)) continue; const lowerKey = k.toLowerCase(); if (!lowerKey) continue; const val = newHeaders[k]; if (val === null) { delete targetHeaders[lowerKey]; } else if (val !== undefined) { targetHeaders[lowerKey] = val; } } }
/** * Copies headers from "newHeaders" onto "targetHeaders", * using lower-case for all properties, * ignoring any keys with undefined values, * and deleting any keys with null values. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/core.ts#L1296-L1310
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
uuid4
const uuid4 = () => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; const v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); };
/** * https://stackoverflow.com/a/2117523 */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/core.ts#L1321-L1327
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
OpenAI.constructor
constructor({ baseURL = Core.readEnv("OPENAI_BASE_URL"), apiKey = Core.readEnv("OPENAI_API_KEY"), organization = Core.readEnv("OPENAI_ORG_ID") ?? null, project = Core.readEnv("OPENAI_PROJECT_ID") ?? null, ...opts }: ClientOptions = {}) { if (apiKey === undefined) { throw new Errors.OpenAIError( "The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).", ); } const options: ClientOptions = { apiKey, organization, project, ...opts, baseURL: baseURL || `https://api.openai.com/v1`, }; if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { throw new Errors.OpenAIError( "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`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n", ); } super({ baseURL: options.baseURL!, timeout: options.timeout ?? 600000, /* 10 minutes */ httpAgent: options.httpAgent, maxRetries: options.maxRetries, fetch: options.fetch, }); this._options = options; this.apiKey = apiKey; this.organization = organization; this.project = project; }
/** * API Client for interfacing with the OpenAI API. * * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/mod.ts#L115-L155
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
AzureOpenAI.constructor
constructor({ baseURL = Core.readEnv("OPENAI_BASE_URL"), apiKey = Core.readEnv("AZURE_OPENAI_API_KEY"), apiVersion = Core.readEnv("OPENAI_API_VERSION"), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts }: AzureClientOptions = {}) { if (!apiVersion) { throw new Errors.OpenAIError( "The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).", ); } if (typeof azureADTokenProvider === "function") { dangerouslyAllowBrowser = true; } if (!azureADTokenProvider && !apiKey) { throw new Errors.OpenAIError( "Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.", ); } if (azureADTokenProvider && apiKey) { throw new Errors.OpenAIError( "The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.", ); } // define a sentinel value to avoid any typing issues apiKey ??= API_KEY_SENTINEL; opts.defaultQuery = { ...opts.defaultQuery, "api-version": apiVersion }; if (!baseURL) { if (!endpoint) { endpoint = process.env["AZURE_OPENAI_ENDPOINT"]; } if (!endpoint) { throw new Errors.OpenAIError( "Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable", ); } baseURL = `${endpoint}/openai`; } else { if (endpoint) { throw new Errors.OpenAIError( "baseURL and endpoint are mutually exclusive", ); } } super({ apiKey, baseURL, ...opts, ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), }); this._azureADTokenProvider = azureADTokenProvider; this.apiVersion = apiVersion; this._deployment = deployment; }
/** * API Client for interfacing with the Azure OpenAI API. * * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/mod.ts#L416-L485
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Page.nextPageParams
nextPageParams(): null { return null; }
/** * This page represents a response that isn't actually paginated at the API level * so there will never be any next page params. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/pagination.ts#L47-L49
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
CursorPage.nextPageParams
nextPageParams(): Partial<CursorPageParams> | null { const info = this.nextPageInfo(); if (!info) return null; if ("params" in info) return info.params; const params = Object.fromEntries(info.url.searchParams); if (!Object.keys(params).length) return null; return params; }
// @deprecated Please use `nextPageInfo()` instead
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/pagination.ts#L86-L93
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Stream.fromReadableStream
static fromReadableStream<Item>( readableStream: ReadableStream, controller: AbortController, ) { let consumed = false; async function* iterLines(): AsyncGenerator<string, void, unknown> { const lineDecoder = new LineDecoder(); const iter = readableStreamAsyncIterable<Bytes>(readableStream); for await (const chunk of iter) { for (const line of lineDecoder.decode(chunk)) { yield line; } } for (const line of lineDecoder.flush()) { yield line; } } async function* iterator(): AsyncIterator<Item, any, undefined> { if (consumed) { throw new Error( "Cannot iterate over a consumed stream, use `.tee()` to split the stream.", ); } consumed = true; let done = false; try { for await (const line of iterLines()) { if (done) continue; if (line) yield JSON.parse(line); } done = true; } catch (e) { // If the user calls `stream.controller.abort()`, we should exit without throwing. if (e instanceof Error && e.name === "AbortError") return; throw e; } finally { // If the user `break`s, abort the ongoing request. if (!done) controller.abort(); } } return new Stream(iterator, controller); }
/** * Generates a Stream from a newline-separated ReadableStream * where each item is a JSON value. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/streaming.ts#L103-L149
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Stream.tee
tee(): [Stream<Item>, Stream<Item>] { const left: Array<Promise<IteratorResult<Item>>> = []; const right: Array<Promise<IteratorResult<Item>>> = []; const iterator = this.iterator(); const teeIterator = ( queue: Array<Promise<IteratorResult<Item>>>, ): AsyncIterator<Item> => { return { next: () => { if (queue.length === 0) { const result = iterator.next(); left.push(result); right.push(result); } return queue.shift()!; }, }; }; return [ new Stream(() => teeIterator(left), this.controller), new Stream(() => teeIterator(right), this.controller), ]; }
/** * Splits the stream into two streams which can be * independently read from at different speeds. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/streaming.ts#L159-L183
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Stream.toReadableStream
toReadableStream(): ReadableStream { const self = this; let iter: AsyncIterator<Item>; const encoder = new TextEncoder(); return new ReadableStream({ async start() { iter = self[Symbol.asyncIterator](); }, async pull(ctrl: any) { try { const { value, done } = await iter.next(); if (done) return ctrl.close(); const bytes = encoder.encode(JSON.stringify(value) + "\n"); ctrl.enqueue(bytes); } catch (err) { ctrl.error(err); } }, async cancel() { await iter.return?.(); }, }); }
/** * Converts this stream to a newline-separated ReadableStream of * JSON stringified values in the stream * which can be turned back into a Stream with `Stream.fromReadableStream()`. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/streaming.ts#L190-L215
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
parseJSON
function parseJSON(jsonString: string, allowPartial: number = Allow.ALL): any { if (typeof jsonString !== "string") { throw new TypeError(`expecting str, got ${typeof jsonString}`); } if (!jsonString.trim()) { throw new Error(`${jsonString} is empty`); } return _parseJSON(jsonString.trim(), allowPartial); }
/** * Parse incomplete JSON * @param {string} jsonString Partial JSON to be parsed * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details * @returns The parsed JSON * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) * @throws {MalformedJSON} If the JSON is malformed */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/_vendor/partial-json-parser/parser.ts#L47-L55
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
partialParse
const partialParse = (input: string) => parseJSON(input, Allow.ALL ^ Allow.NUM);
// using this function with malformed JSON is undefined behavior
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/_vendor/partial-json-parser/parser.ts#L276-L276
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
processRegExp
const processRegExp = ( regexOrFunction: RegExp | (() => RegExp), refs: Refs, ): string => { const regex = typeof regexOrFunction === "function" ? regexOrFunction() : regexOrFunction; if (!refs.applyRegexFlags || !regex.flags) return regex.source; // Currently handled flags const flags = { i: regex.flags.includes("i"), // Case-insensitive m: regex.flags.includes("m"), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes("s"), // `.` matches newlines }; // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i = 0; i < source.length; i++) { if (isEscaped) { pattern += source[i]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i].match(/[a-z]/)) { if (inCharRange) { pattern += source[i]; pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); inCharRange = false; } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { pattern += source[i]; inCharRange = true; } else { pattern += `${source[i]}${source[i].toUpperCase()}`; } continue; } } else if (source[i].match(/[a-z]/)) { pattern += `[${source[i]}${source[i].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i] === "^") { pattern += `(^|(?<=[\r\n]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r\n]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } try { const regexTest = new RegExp(pattern); } catch { console.warn( `Could not convert regex pattern at ${ refs.currentPath.join( "/", ) } to a flag-independent form! Falling back to the flag-ignorant source`, ); return regex.source; } return pattern; };
// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/_vendor/zod-to-json-schema/parsers/string.ts#L365-L456
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
LineDecoder.constructor
constructor() { this.buffer = []; this.trailingCR = false; }
// TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types.
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/internal/decoders/line.ts#L20-L23
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
AbstractChatCompletionRunner.finalChatCompletion
async finalChatCompletion(): Promise<ParsedChatCompletion<ParsedT>> { await this.done(); const completion = this._chatCompletions[this._chatCompletions.length - 1]; if (!completion) { throw new OpenAIError("stream ended without producing a ChatCompletion"); } return completion; }
/** * @returns a promise that resolves with the final ChatCompletion, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletion. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/AbstractChatCompletionRunner.ts#L98-L105
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
AbstractChatCompletionRunner.finalContent
async finalContent(): Promise<string | null> { await this.done(); return this.#getFinalContent(); }
/** * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/AbstractChatCompletionRunner.ts#L115-L118
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
AbstractChatCompletionRunner.finalMessage
async finalMessage(): Promise<ChatCompletionMessage> { await this.done(); return this.#getFinalMessage(); }
/** * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/AbstractChatCompletionRunner.ts#L148-L151
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
AbstractChatCompletionRunner.finalFunctionCall
async finalFunctionCall(): Promise< ChatCompletionMessage.FunctionCall | undefined > { await this.done(); return this.#getFinalFunctionCall(); }
/** * @returns a promise that resolves with the content of the final FunctionCall, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/AbstractChatCompletionRunner.ts#L171-L176
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
ChatCompletionRunner.runFunctions
static runFunctions( client: OpenAI, params: ChatCompletionFunctionRunnerParams<any[]>, options?: RunnerOptions, ): ChatCompletionRunner<null> { const runner = new ChatCompletionRunner(); const opts = { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "runFunctions", }, }; runner._run(() => runner._runFunctions(client, params, opts)); return runner; }
/** @deprecated - please use `runTools` instead. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/ChatCompletionRunner.ts#L52-L67
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
ChatCompletionStream.fromReadableStream
static fromReadableStream( stream: ReadableStream, ): ChatCompletionStream<null> { const runner = new ChatCompletionStream(null); runner._run(() => runner._fromReadableStream(stream)); return runner; }
/** * Intended for use on the frontend, consuming a stream produced with * `.toReadableStream()` on the backend. * * Note that messages sent to the model do not appear in `.on('message')` * in this context. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/ChatCompletionStream.ts#L161-L167
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
assertIsEmpty
function assertIsEmpty<T extends {}>( obj: AssertIsEmpty<T>, ): asserts obj is AssertIsEmpty<T> { return; }
/** * Ensures the given argument is an empty object, useful for * asserting that all known properties on an object have been * destructured. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/ChatCompletionStream.ts#L978-L982
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
ChatCompletionStreamingRunner.runFunctions
static runFunctions<T extends (string | object)[]>( client: OpenAI, params: ChatCompletionStreamingFunctionRunnerParams<T>, options?: RunnerOptions, ): ChatCompletionStreamingRunner<null> { const runner = new ChatCompletionStreamingRunner(null); const opts = { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "runFunctions", }, }; runner._run(() => runner._runFunctions(client, params, opts)); return runner; }
/** @deprecated - please use `runTools` instead. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/ChatCompletionStreamingRunner.ts#L62-L77
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
EventStream.on
on<Event extends keyof EventTypes>( event: Event, listener: EventListener<EventTypes, Event>, ): this { const listeners: EventListeners<EventTypes, Event> = this.#listeners[event] || (this.#listeners[event] = []); listeners.push({ listener }); return this; }
/** * Adds the listener function to the end of the listeners array for the event. * No checks are made to see if the listener has already been added. Multiple calls passing * the same combination of event and listener will result in the listener being added, and * called, multiple times. * @returns this ChatCompletionStream, so that calls can be chained */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/EventStream.ts#L82-L90
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
EventStream.off
off<Event extends keyof EventTypes>( event: Event, listener: EventListener<EventTypes, Event>, ): this { const listeners = this.#listeners[event]; if (!listeners) return this; const index = listeners.findIndex((l) => l.listener === listener); if (index >= 0) listeners.splice(index, 1); return this; }
/** * Removes the specified listener from the listener array for the event. * off() will remove, at most, one instance of a listener from the listener array. If any single * listener has been added multiple times to the listener array for the specified event, then * off() must be called multiple times to remove each instance. * @returns this ChatCompletionStream, so that calls can be chained */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/EventStream.ts#L99-L108
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
EventStream.once
once<Event extends keyof EventTypes>( event: Event, listener: EventListener<EventTypes, Event>, ): this { const listeners: EventListeners<EventTypes, Event> = this.#listeners[event] || (this.#listeners[event] = []); listeners.push({ listener, once: true }); return this; }
/** * Adds a one-time listener function for the event. The next time the event is triggered, * this listener is removed and then invoked. * @returns this ChatCompletionStream, so that calls can be chained */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/EventStream.ts#L115-L123
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
EventStream.emitted
emitted<Event extends keyof EventTypes>( event: Event, ): Promise< EventParameters<EventTypes, Event> extends [infer Param] ? Param : EventParameters<EventTypes, Event> extends [] ? void : EventParameters<EventTypes, Event> > { return new Promise((resolve, reject) => { this.#catchingPromiseCreated = true; if (event !== "error") this.once("error", reject); this.once(event, resolve as any); }); }
/** * This is similar to `.once()`, but returns a Promise that resolves the next time * the event is triggered, instead of calling a listener callback. * @returns a Promise that resolves the next time given event is triggered, * or rejects if an error is emitted. (If you request the 'error' event, * returns a promise that resolves with the error). * * Example: * * const message = await stream.emitted('message') // rejects if the stream errors */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/lib/EventStream.ts#L136-L148
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Batches.create
create( body: BatchCreateParams, options?: Core.RequestOptions, ): Core.APIPromise<Batch> { return this._client.post("/batches", { body, ...options }); }
/** * Creates and executes a batch from an uploaded file of requests */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/batches.ts#L13-L18
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Batches.retrieve
retrieve( batchId: string, options?: Core.RequestOptions, ): Core.APIPromise<Batch> { return this._client.get(`/batches/${batchId}`, options); }
/** * Retrieves a batch. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/batches.ts#L23-L28
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Batches.cancel
cancel( batchId: string, options?: Core.RequestOptions, ): Core.APIPromise<Batch> { return this._client.post(`/batches/${batchId}/cancel`, options); }
/** * Cancels an in-progress batch. The batch will be in status `cancelling` for up to * 10 minutes, before changing to `cancelled`, where it will have partial results * (if any) available in the output file. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/batches.ts#L56-L61
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Embeddings.create
create( body: EmbeddingCreateParams, options?: Core.RequestOptions, ): Core.APIPromise<CreateEmbeddingResponse> { return this._client.post("/embeddings", { body, ...options }); }
/** * Creates an embedding vector representing the input text. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/embeddings.ts#L11-L16
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Files.create
create( body: FileCreateParams, options?: Core.RequestOptions, ): Core.APIPromise<FileObject> { return this._client.post( "/files", Core.multipartFormRequestOptions({ body, ...options }), ); }
/** * Upload a file that can be used across various endpoints. Individual files can be * up to 512 MB, and the size of all files uploaded by one organization can be up * to 100 GB. * * The Assistants API supports files up to 2 million tokens and of specific file * types. See the * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for * details. * * The Fine-tuning API only supports `.jsonl` files. The input also has certain * required formats for fine-tuning * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) * models. * * The Batch API only supports `.jsonl` files up to 100 MB in size. The input also * has a specific required * [format](https://platform.openai.com/docs/api-reference/batch/request-input). * * Please [contact us](https://help.openai.com/) if you need to increase these * storage limits. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/files.ts#L36-L44
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Files.retrieve
retrieve( fileId: string, options?: Core.RequestOptions, ): Core.APIPromise<FileObject> { return this._client.get(`/files/${fileId}`, options); }
/** * Returns information about a specific file. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/files.ts#L49-L54
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Files.del
del( fileId: string, options?: Core.RequestOptions, ): Core.APIPromise<FileDeleted> { return this._client.delete(`/files/${fileId}`, options); }
/** * Delete a file. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/files.ts#L82-L87
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Files.content
content( fileId: string, options?: Core.RequestOptions, ): Core.APIPromise<Response> { return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true, }); }
/** * Returns the contents of the specified file. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/files.ts#L92-L100
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Files.retrieveContent
retrieveContent( fileId: string, options?: Core.RequestOptions, ): Core.APIPromise<string> { return this._client.get(`/files/${fileId}/content`, { ...options, headers: { Accept: "application/json", ...options?.headers }, }); }
/** * Returns the contents of the specified file. * * @deprecated The `.content()` method should be used instead */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/files.ts#L107-L115
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Files.waitForProcessing
async waitForProcessing( id: string, { pollInterval = 5000, maxWait = 30 * 60 * 1000 }: { pollInterval?: number; maxWait?: number; } = {}, ): Promise<FileObject> { const TERMINAL_STATES = new Set(["processed", "error", "deleted"]); const start = Date.now(); let file = await this.retrieve(id); while (!file.status || !TERMINAL_STATES.has(file.status)) { await sleep(pollInterval); file = await this.retrieve(id); if (Date.now() - start > maxWait) { throw new APIConnectionTimeoutError({ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, }); } } return file; }
/** * Waits for the given file to be processed, default timeout is 30 mins. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/files.ts#L120-L145
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Images.createVariation
createVariation( body: ImageCreateVariationParams, options?: Core.RequestOptions, ): Core.APIPromise<ImagesResponse> { return this._client.post( "/images/variations", Core.multipartFormRequestOptions({ body, ...options }), ); }
/** * Creates a variation of a given image. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/images.ts#L11-L19
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Images.edit
edit( body: ImageEditParams, options?: Core.RequestOptions, ): Core.APIPromise<ImagesResponse> { return this._client.post( "/images/edits", Core.multipartFormRequestOptions({ body, ...options }), ); }
/** * Creates an edited or extended image given an original image and a prompt. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/images.ts#L24-L32
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Images.generate
generate( body: ImageGenerateParams, options?: Core.RequestOptions, ): Core.APIPromise<ImagesResponse> { return this._client.post("/images/generations", { body, ...options }); }
/** * Creates an image given a prompt. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/images.ts#L37-L42
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Models.retrieve
retrieve( model: string, options?: Core.RequestOptions, ): Core.APIPromise<Model> { return this._client.get(`/models/${model}`, options); }
/** * Retrieves a model instance, providing basic information about the model such as * the owner and permissioning. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/models.ts#L13-L18
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Models.list
list(options?: Core.RequestOptions): Core.PagePromise<ModelsPage, Model> { return this._client.getAPIList("/models", ModelsPage, options); }
/** * Lists the currently available models, and provides basic information about each * one such as the owner and availability. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/models.ts#L24-L26
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Models.del
del( model: string, options?: Core.RequestOptions, ): Core.APIPromise<ModelDeleted> { return this._client.delete(`/models/${model}`, options); }
/** * Delete a fine-tuned model. You must have the Owner role in your organization to * delete a model. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/models.ts#L32-L37
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Moderations.create
create( body: ModerationCreateParams, options?: Core.RequestOptions, ): Core.APIPromise<ModerationCreateResponse> { return this._client.post("/moderations", { body, ...options }); }
/** * Classifies if text and/or image inputs are potentially harmful. Learn more in * the [moderation guide](https://platform.openai.com/docs/guides/moderation). */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/moderations.ts#L12-L17
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Speech.create
create( body: SpeechCreateParams, options?: Core.RequestOptions, ): Core.APIPromise<Response> { return this._client.post("/audio/speech", { body, ...options, __binaryResponse: true, }); }
/** * Generates audio from the input text. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/audio/speech.ts#L12-L21
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Assistants.create
create( body: AssistantCreateParams, options?: Core.RequestOptions, ): Core.APIPromise<Assistant> { return this._client.post("/assistants", { body, ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Create an assistant with a model and instructions. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/assistants.ts#L20-L29
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Assistants.retrieve
retrieve( assistantId: string, options?: Core.RequestOptions, ): Core.APIPromise<Assistant> { return this._client.get(`/assistants/${assistantId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Retrieves an assistant. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/assistants.ts#L34-L42
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Assistants.update
update( assistantId: string, body: AssistantUpdateParams, options?: Core.RequestOptions, ): Core.APIPromise<Assistant> { return this._client.post(`/assistants/${assistantId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Modifies an assistant. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/assistants.ts#L47-L57
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Assistants.del
del( assistantId: string, options?: Core.RequestOptions, ): Core.APIPromise<AssistantDeleted> { return this._client.delete(`/assistants/${assistantId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Delete an assistant. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/assistants.ts#L86-L94
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Completions.stream
stream< Params extends ChatCompletionStreamParams, ParsedT = ExtractParsedContentFromParams<Params>, >( body: Params, options?: Core.RequestOptions, ): ChatCompletionStream<ParsedT> { return ChatCompletionStream.createChatCompletion( this._client, body, options, ); }
/** * Creates a chat completion stream */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/chat/completions.ts#L180-L192
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Messages.create
create( threadId: string, body: MessageCreateParams, options?: Core.RequestOptions, ): Core.APIPromise<Message> { return this._client.post(`/threads/${threadId}/messages`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Create a message. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/messages.ts#L14-L24
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Messages.retrieve
retrieve( threadId: string, messageId: string, options?: Core.RequestOptions, ): Core.APIPromise<Message> { return this._client.get(`/threads/${threadId}/messages/${messageId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Retrieve a message. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/messages.ts#L29-L38
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Messages.update
update( threadId: string, messageId: string, body: MessageUpdateParams, options?: Core.RequestOptions, ): Core.APIPromise<Message> { return this._client.post(`/threads/${threadId}/messages/${messageId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Modifies a message. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/messages.ts#L43-L54
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Messages.del
del( threadId: string, messageId: string, options?: Core.RequestOptions, ): Core.APIPromise<MessageDeleted> { return this._client.delete(`/threads/${threadId}/messages/${messageId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Deletes a message. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/messages.ts#L90-L99
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Threads.retrieve
retrieve( threadId: string, options?: Core.RequestOptions, ): Core.APIPromise<Thread> { return this._client.get(`/threads/${threadId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Retrieves a thread. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/threads.ts#L49-L57
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Threads.update
update( threadId: string, body: ThreadUpdateParams, options?: Core.RequestOptions, ): Core.APIPromise<Thread> { return this._client.post(`/threads/${threadId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Modifies a thread. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/threads.ts#L62-L72
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Threads.del
del( threadId: string, options?: Core.RequestOptions, ): Core.APIPromise<ThreadDeleted> { return this._client.delete(`/threads/${threadId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Delete a thread. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/threads.ts#L77-L85
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Threads.createAndRunPoll
async createAndRunPoll( body: ThreadCreateAndRunParamsNonStreaming, options?: Core.RequestOptions & { pollIntervalMs?: number }, ): Promise<Threads.Run> { const run = await this.createAndRun(body, options); return await this.runs.poll(run.thread_id, run.id, options); }
/** * A helper to create a thread, start a run and then poll for a terminal state. * More information on Run lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/threads.ts#L123-L129
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Threads.createAndRunStream
createAndRunStream( body: ThreadCreateAndRunParamsBaseStream, options?: Core.RequestOptions, ): AssistantStream { return AssistantStream.createThreadAssistantStream( body, this._client.beta.threads, options, ); }
/** * Create a thread and stream the run back */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/threads.ts#L134-L143
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.retrieve
retrieve( threadId: string, runId: string, options?: Core.RequestOptions, ): Core.APIPromise<Run> { return this._client.get(`/threads/${threadId}/runs/${runId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Retrieves a run. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L63-L72
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.update
update( threadId: string, runId: string, body: RunUpdateParams, options?: Core.RequestOptions, ): Core.APIPromise<Run> { return this._client.post(`/threads/${threadId}/runs/${runId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Modifies a run. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L77-L88
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.cancel
cancel( threadId: string, runId: string, options?: Core.RequestOptions, ): Core.APIPromise<Run> { return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Cancels a run that is `in_progress`. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L120-L129
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.createAndPoll
async createAndPoll( threadId: string, body: RunCreateParamsNonStreaming, options?: Core.RequestOptions & { pollIntervalMs?: number }, ): Promise<Run> { const run = await this.create(threadId, body, options); return await this.poll(threadId, run.id, options); }
/** * A helper to create a run an poll for a terminal state. More information on Run * lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L136-L143
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.createAndStream
createAndStream( threadId: string, body: RunCreateParamsBaseStream, options?: Core.RequestOptions, ): AssistantStream { return AssistantStream.createAssistantStream( threadId, this._client.beta.threads.runs, body, options, ); }
/** * Create a Run stream * * @deprecated use `stream` instead */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L150-L161
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.poll
async poll( threadId: string, runId: string, options?: Core.RequestOptions & { pollIntervalMs?: number }, ): Promise<Run> { const headers: { [key: string]: string } = { ...options?.headers, "X-Stainless-Poll-Helper": "true", }; if (options?.pollIntervalMs) { headers["X-Stainless-Custom-Poll-Interval"] = options.pollIntervalMs .toString(); } while (true) { const { data: run, response } = await this.retrieve(threadId, runId, { ...options, headers: { ...options?.headers, ...headers }, }).withResponse(); switch (run.status) { //If we are in any sort of intermediate state we poll case "queued": case "in_progress": case "cancelling": let sleepInterval = 5000; if (options?.pollIntervalMs) { sleepInterval = options.pollIntervalMs; } else { const headerInterval = response.headers.get("openai-poll-after-ms"); if (headerInterval) { const headerIntervalMs = parseInt(headerInterval); if (!isNaN(headerIntervalMs)) { sleepInterval = headerIntervalMs; } } } await sleep(sleepInterval); break; //We return the run in any terminal state. case "requires_action": case "incomplete": case "cancelled": case "completed": case "failed": case "expired": return run; } } }
/** * A helper to poll a run status until it reaches a terminal state. More * information on Run lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L168-L219
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.stream
stream( threadId: string, body: RunCreateParamsBaseStream, options?: Core.RequestOptions, ): AssistantStream { return AssistantStream.createAssistantStream( threadId, this._client.beta.threads.runs, body, options, ); }
/** * Create a Run stream */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L224-L235
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.submitToolOutputsAndPoll
async submitToolOutputsAndPoll( threadId: string, runId: string, body: RunSubmitToolOutputsParamsNonStreaming, options?: Core.RequestOptions & { pollIntervalMs?: number }, ): Promise<Run> { const run = await this.submitToolOutputs(threadId, runId, body, options); return await this.poll(threadId, run.id, options); }
/** * A helper to submit a tool output to a run and poll for a terminal run state. * More information on Run lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L285-L293
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
Runs.submitToolOutputsStream
submitToolOutputsStream( threadId: string, runId: string, body: RunSubmitToolOutputsParamsStream, options?: Core.RequestOptions, ): AssistantStream { return AssistantStream.createToolAssistantStream( threadId, runId, this._client.beta.threads.runs, body, options, ); }
/** * Submit the tool outputs from a previous run and stream the run to a terminal * state. More information on Run lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/threads/runs/runs.ts#L300-L313
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
FileBatches.create
create( vectorStoreId: string, body: FileBatchCreateParams, options?: Core.RequestOptions, ): Core.APIPromise<VectorStoreFileBatch> { return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }); }
/** * Create a vector store file batch. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/vector-stores/file-batches.ts#L19-L29
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
FileBatches.retrieve
retrieve( vectorStoreId: string, batchId: string, options?: Core.RequestOptions, ): Core.APIPromise<VectorStoreFileBatch> { return this._client.get( `/vector_stores/${vectorStoreId}/file_batches/${batchId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }, ); }
/** * Retrieves a vector store file batch. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/vector-stores/file-batches.ts#L34-L46
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
FileBatches.cancel
cancel( vectorStoreId: string, batchId: string, options?: Core.RequestOptions, ): Core.APIPromise<VectorStoreFileBatch> { return this._client.post( `/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, { ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }, }, ); }
/** * Cancel a vector store file batch. This attempts to cancel the processing of * files in this batch as soon as possible. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/vector-stores/file-batches.ts#L52-L64
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
FileBatches.createAndPoll
async createAndPoll( vectorStoreId: string, body: FileBatchCreateParams, options?: Core.RequestOptions & { pollIntervalMs?: number }, ): Promise<VectorStoreFileBatch> { const batch = await this.create(vectorStoreId, body); return await this.poll(vectorStoreId, batch.id, options); }
/** * Create a vector store batch and poll until all files have been processed. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/vector-stores/file-batches.ts#L69-L76
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe
openai-deno-build
github_2023
openai
typescript
FileBatches.poll
async poll( vectorStoreId: string, batchId: string, options?: Core.RequestOptions & { pollIntervalMs?: number }, ): Promise<VectorStoreFileBatch> { const headers: { [key: string]: string } = { ...options?.headers, "X-Stainless-Poll-Helper": "true", }; if (options?.pollIntervalMs) { headers["X-Stainless-Custom-Poll-Interval"] = options.pollIntervalMs .toString(); } while (true) { const { data: batch, response } = await this.retrieve( vectorStoreId, batchId, { ...options, headers, }, ).withResponse(); switch (batch.status) { case "in_progress": let sleepInterval = 5000; if (options?.pollIntervalMs) { sleepInterval = options.pollIntervalMs; } else { const headerInterval = response.headers.get("openai-poll-after-ms"); if (headerInterval) { const headerIntervalMs = parseInt(headerInterval); if (!isNaN(headerIntervalMs)) { sleepInterval = headerIntervalMs; } } } await sleep(sleepInterval); break; case "failed": case "cancelled": case "completed": return batch; } } }
/** * Wait for the given file batch to be processed. * * Note: this will return even if one of the files failed to process, you need to * check batch.file_counts.failed_count to handle this case. */
https://github.com/openai/openai-deno-build/blob/28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe/resources/beta/vector-stores/file-batches.ts#L118-L165
28ffdaa2c107c98db5eec50cf284f4fd37ad8fbe