ollamaService.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { config } from '../config';
  2. export interface EmbeddingResponse {
  3. embedding: number[];
  4. }
  5. export class OllamaService {
  6. private baseUrl: string;
  7. private model: string;
  8. constructor() {
  9. this.baseUrl = config.ollama.url;
  10. this.model = config.ollama.embeddingModel;
  11. }
  12. async createEmbedding(text: string): Promise<number[]> {
  13. try {
  14. const response = await fetch(`${this.baseUrl}/api/embeddings`, {
  15. method: 'POST',
  16. headers: {
  17. 'Content-Type': 'application/json',
  18. },
  19. body: JSON.stringify({
  20. model: this.model,
  21. prompt: text,
  22. }),
  23. });
  24. if (!response.ok) {
  25. throw new Error(`Ollama API error: ${response.statusText}`);
  26. }
  27. const data: EmbeddingResponse = await response.json();
  28. return data.embedding;
  29. } catch (error) {
  30. console.error('Error creating embedding:', error);
  31. throw error;
  32. }
  33. }
  34. async createEmbeddings(texts: string[]): Promise<number[][]> {
  35. const embeddings: number[][] = [];
  36. console.log(`Creating embeddings for ${texts.length} texts...`);
  37. for (let i = 0; i < texts.length; i++) {
  38. const text = texts[i];
  39. const embedding = await this.createEmbedding(text);
  40. embeddings.push(embedding);
  41. // Progress indicator for large batches
  42. if ((i + 1) % 10 === 0 || i === texts.length - 1) {
  43. console.log(`Progress: ${i + 1}/${texts.length} embeddings created`);
  44. }
  45. }
  46. return embeddings;
  47. }
  48. }