|
| 1 | +# Implementing a Collector |
| 2 | + |
| 3 | +This guide demonstrates how to implement a new Collector for the peerBench SDK. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +Collectors are responsible for taking a source input and creating a structured data that later can be used by the Generators to generate new Prompts. |
| 8 | + |
| 9 | +## Basic Example |
| 10 | + |
| 11 | +Here's a simple collector implementation that demonstrates the basic structure: |
| 12 | + |
| 13 | +```typescript |
| 14 | +import { AbstractCollector } from "@/collectors/abstract/abstract-collector"; |
| 15 | + |
| 16 | +interface MyCollectedData { |
| 17 | + id: string; |
| 18 | + title: string; |
| 19 | + content: string; |
| 20 | + metadata: Record<string, any>; |
| 21 | +} |
| 22 | + |
| 23 | +export class SimpleAPICollector extends AbstractCollector<MyCollectedData[]> { |
| 24 | + readonly identifier = "simple-api-collector"; |
| 25 | + |
| 26 | + async collect( |
| 27 | + source: unknown, |
| 28 | + options?: Record<string, any> |
| 29 | + ): Promise<MyCollectedData[] | undefined> { |
| 30 | + // Type guard for input validation |
| 31 | + if (typeof source !== "string") { |
| 32 | + throw new Error("Source must be a string URL"); |
| 33 | + } |
| 34 | + |
| 35 | + // Fetch data from external source |
| 36 | + const response = await fetch(source); |
| 37 | + if (!response.ok) { |
| 38 | + throw new Error(`HTTP ${response.status}: ${response.statusText}`); |
| 39 | + } |
| 40 | + |
| 41 | + // Parse and transform the response |
| 42 | + const rawData = await response.json(); |
| 43 | + return this.transformData(rawData); |
| 44 | + } |
| 45 | + |
| 46 | + private transformData(rawData: any): MyCollectedData[] { |
| 47 | + return rawData.map((item: any) => ({ |
| 48 | + id: item.id, |
| 49 | + title: item.title, |
| 50 | + content: item.content, |
| 51 | + metadata: item.metadata || {}, |
| 52 | + })); |
| 53 | + } |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +### Required Properties |
| 58 | + |
| 59 | +**`readonly identifier: string`** |
| 60 | + |
| 61 | +- A unique string that identifies your Collector |
| 62 | +- Should be descriptive and unique across all Collectors |
| 63 | +- Useful when you try to find this Collector among the others |
| 64 | + |
| 65 | +### Abstract Methods |
| 66 | + |
| 67 | +**`async collect(source: unknown, options?: Record<string, any>): Promise<T | undefined>`** |
| 68 | + |
| 69 | +- This is the main collection method you must implement |
| 70 | +- Takes a `source` as the input |
| 71 | +- Interpretation of what `source` parameter is depends on the implementation |
| 72 | +- For example if it is a URL, you should validate that it is a real URL string and fetch data from it |
| 73 | +- Or if it is a file path, you should be checking that file is exist |
| 74 | +- Optional `options` parameter for configurable collection behavior |
| 75 | +- Must return data matching your Collector's output type `T`, or `undefined` if the process fails |
| 76 | +- The generic type `T` represents what your collector **outputs** |
| 77 | + |
| 78 | +## Advanced Patterns |
| 79 | + |
| 80 | +### RSS Feed Collector |
| 81 | + |
| 82 | +For RSS feeds, extend `AbstractRSSCollector` instead: |
| 83 | + |
| 84 | +```typescript |
| 85 | +import { AbstractRSSCollector } from "@/collectors/abstract/abstract-rss-collector"; |
| 86 | +import { z } from "zod"; |
| 87 | + |
| 88 | +export class MyRSSCollector extends AbstractRSSCollector<MyRSSData[]> { |
| 89 | + readonly identifier = "my-rss-collector"; |
| 90 | + |
| 91 | + // Define the expected RSS structure using Zod |
| 92 | + feedSchema = z.object({ |
| 93 | + rss: z.object({ |
| 94 | + channel: z.object({ |
| 95 | + title: z.string(), |
| 96 | + item: z.array( |
| 97 | + z.object({ |
| 98 | + title: z.string(), |
| 99 | + description: z.string(), |
| 100 | + link: z.string(), |
| 101 | + pubDate: z.string(), |
| 102 | + }) |
| 103 | + ), |
| 104 | + }), |
| 105 | + }), |
| 106 | + }); |
| 107 | + |
| 108 | + async collect(url: string): Promise<MyRSSData[] | undefined> { |
| 109 | + const feed = await this.parseFeedXML(await this.fetchFeed(url)); |
| 110 | + |
| 111 | + // Process the validated RSS data |
| 112 | + return feed.rss.channel.item.map((item) => ({ |
| 113 | + title: item.title, |
| 114 | + description: item.description, |
| 115 | + link: item.link, |
| 116 | + publishedAt: new Date(item.pubDate), |
| 117 | + })); |
| 118 | + } |
| 119 | +} |
| 120 | +``` |
| 121 | + |
| 122 | +### Collector with Authentication |
| 123 | + |
| 124 | +For APIs requiring authentication: |
| 125 | + |
| 126 | +```typescript |
| 127 | +export class AuthenticatedAPICollector extends AbstractCollector<MyData[]> { |
| 128 | + readonly identifier = "authenticated-api"; |
| 129 | + |
| 130 | + async collect( |
| 131 | + source: unknown, |
| 132 | + options: { |
| 133 | + includeSensitiveContent?: boolean; |
| 134 | + limit?: number; |
| 135 | + sortBy?: "relevance" | "date" | "popularity"; |
| 136 | + language?: string; |
| 137 | + } = {} |
| 138 | + ): Promise<MyData[] | undefined> { |
| 139 | + if (typeof source !== "string") { |
| 140 | + throw new Error("Source must be a search query string"); |
| 141 | + } |
| 142 | + |
| 143 | + // Build the API request parameters using options |
| 144 | + const params = new URLSearchParams(); |
| 145 | + params.set("q", source); |
| 146 | + |
| 147 | + // Apply options to customize the API request |
| 148 | + if (options.includeSensitiveContent) { |
| 149 | + params.set("sensitive", "true"); |
| 150 | + } |
| 151 | + if (options.limit) { |
| 152 | + params.set("limit", options.limit.toString()); |
| 153 | + } |
| 154 | + if (options.sortBy) { |
| 155 | + params.set("sortBy", options.sortBy); |
| 156 | + } |
| 157 | + if (options.language) { |
| 158 | + params.set("language", options.language); |
| 159 | + } |
| 160 | + |
| 161 | + const headers = { |
| 162 | + Authorization: `Bearer ${this.apiKey}`, |
| 163 | + "Content-Type": "application/json", |
| 164 | + }; |
| 165 | + |
| 166 | + const response = await fetch( |
| 167 | + `${this.baseUrl}/search?${params.toString()}`, |
| 168 | + { headers } |
| 169 | + ); |
| 170 | + |
| 171 | + if (!response.ok) { |
| 172 | + throw new Error(`API request failed: ${response.status}`); |
| 173 | + } |
| 174 | + |
| 175 | + const data = await response.json(); |
| 176 | + return this.transformData(data, options.limit); |
| 177 | + } |
| 178 | + |
| 179 | + private transformData(rawData: any, limit?: number): MyData[] { |
| 180 | + let results = rawData.results?.map(this.mapToMyData) || []; |
| 181 | + |
| 182 | + if (limit && results.length > limit) { |
| 183 | + results = results.slice(0, limit); |
| 184 | + } |
| 185 | + |
| 186 | + return results; |
| 187 | + } |
| 188 | +} |
| 189 | +``` |
| 190 | + |
| 191 | +## Examples |
| 192 | + |
| 193 | +See the `examples/collectors/` directory for complete working examples: |
| 194 | + |
| 195 | +- `file-system-collector.ts` - Local file collection |
| 196 | +- `news-api-collector.ts` - API-based collection |
| 197 | + |
| 198 | +These examples demonstrate real-world implementations and can serve as templates for your own collectors. |
| 199 | + |
| 200 | +## What's Next? |
| 201 | + |
| 202 | +Now that you understand how to implement a Collector, you're ready to learn about the next component in the peerBench SDK: **Generators**. |
| 203 | + |
| 204 | +**Next Documentation**: [Implementing a Generator](./implementing-a-generator.md) |
0 commit comments