Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions functions/text-embedding/__tests__/handler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { createMockContext } from '../../../tests/helpers/mock-context';

const mockGenerateEmbedding = jest.fn();

jest.mock('@agentic-kit/ollama', () => {
return {
__esModule: true,
default: class OllamaClient {
constructor() {}
async generateEmbedding(text: string, model: string) {
return mockGenerateEmbedding(text, model);
}
},
};
});

const loadHandler = () => {
const mod = require('../handler');
return mod.default ?? mod;
};

describe('text-embedding handler', () => {
beforeEach(() => {
mockGenerateEmbedding.mockClear();
mockGenerateEmbedding.mockResolvedValue([0.1, 0.2, 0.3, 0.4, 0.5]);
});

it('should generate embedding for valid text', async () => {
const mockEmbedding = [0.1, 0.2, 0.3, 0.4, 0.5];
mockGenerateEmbedding.mockResolvedValue(mockEmbedding);

const handler = loadHandler();
const result = await handler(
{ text: 'Hello world' },
createMockContext({ env: { OLLAMA_URL: 'http://localhost:11434' } })
);

expect(result).toEqual({
embedding: mockEmbedding,
dimensions: 5,
model: 'nomic-embed-text:latest',
});
});

it('should use custom model when provided', async () => {
const mockEmbedding = [0.1, 0.2, 0.3];
mockGenerateEmbedding.mockResolvedValue(mockEmbedding);

const handler = loadHandler();
const result = await handler(
{ text: 'Test', model: 'mxbai-embed-large' },
createMockContext()
);

expect(result.model).toBe('mxbai-embed-large');
expect(mockGenerateEmbedding).toHaveBeenCalledWith('Test', 'mxbai-embed-large');
});

it('should use EMBEDDING_MODEL env var as default', async () => {
const mockEmbedding = [0.1, 0.2];
mockGenerateEmbedding.mockResolvedValue(mockEmbedding);

const handler = loadHandler();
const result = await handler(
{ text: 'Test' },
createMockContext({ env: { EMBEDDING_MODEL: 'all-minilm' } })
);

expect(result.model).toBe('all-minilm');
});

it('should throw error when text is missing', async () => {
const handler = loadHandler();
await expect(
handler({}, createMockContext())
).rejects.toThrow('Missing required param: text');
});

it('should throw error when text is not a string', async () => {
const handler = loadHandler();
await expect(
handler({ text: 123 }, createMockContext())
).rejects.toThrow('Missing required param: text');
});

it('should throw error when text is empty', async () => {
const handler = loadHandler();
await expect(
handler({ text: '' }, createMockContext())
).rejects.toThrow('Missing required param: text');
});

it('should return mock embedding in DRY_RUN mode', async () => {
const handler = loadHandler();
const result = await handler(
{ text: 'Test' },
createMockContext({ env: { TEXT_EMBEDDING_DRY_RUN: 'true' } })
);

expect(result).toEqual({
embedding: Array(768).fill(0),
dimensions: 768,
model: 'dry-run',
});
expect(mockGenerateEmbedding).not.toHaveBeenCalled();
});
});
10 changes: 10 additions & 0 deletions functions/text-embedding/handler.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "text-embedding",
"version": "1.0.0",
"type": "node-graphql",
"port": 8084,
"description": "Generate text embeddings using Ollama",
"dependencies": {
"@agentic-kit/ollama": "^1.0.3"
}
}
56 changes: 56 additions & 0 deletions functions/text-embedding/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import type { FunctionHandler } from '@constructive-io/fn-runtime';
import OllamaClient from '@agentic-kit/ollama';

interface Params {
text: string;
model?: string;
}

interface Result {
embedding: number[];
dimensions: number;
model: string;
}

const handler: FunctionHandler<Params, Result> = async (params, context) => {
const { log, env } = context;

const { text, model } = params;

if (!text || typeof text !== 'string') {
Copy link

Copilot AI Apr 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The text validation only rejects empty string, but allows whitespace-only values (e.g. ' '), since it doesn't trim. Other handlers treat whitespace-only strings as missing (e.g. isNonEmptyString(...).trim().length > 0). Consider using text.trim().length > 0 in the validation so the function doesn't generate embeddings for blank input.

Suggested change
if (!text || typeof text !== 'string') {
if (typeof text !== 'string' || text.trim().length === 0) {

Copilot uses AI. Check for mistakes.
throw new Error('Missing required param: text');
}

// DRY_RUN mode for CI testing - skip actual Ollama call
if (env.TEXT_EMBEDDING_DRY_RUN === 'true') {
log.info('[text-embedding] DRY_RUN mode, returning mock embedding');
return {
embedding: Array(768).fill(0),
dimensions: 768,
model: 'dry-run',
};
}

const ollamaUrl = env.OLLAMA_URL || 'http://localhost:11434';
const embeddingModel = model || env.EMBEDDING_MODEL || 'nomic-embed-text:latest';

log.info('[text-embedding] Generating embedding', {
textLength: text.length,
model: embeddingModel,
});

const ollama = new OllamaClient(ollamaUrl);
const embedding = await ollama.generateEmbedding(text, embeddingModel);

log.info('[text-embedding] Complete', {
dimensions: embedding.length,
});

return {
embedding,
dimensions: embedding.length,
model: embeddingModel,
};
};

export default handler;
5 changes: 5 additions & 0 deletions k8s/overlays/local-simple/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,8 @@ data:

SEND_EMAIL_DRY_RUN: "true"
SEND_VERIFICATION_LINK_DRY_RUN: "true"
TEXT_EMBEDDING_DRY_RUN: "true"

# AI/Embedding settings
OLLAMA_URL: "http://ollama.constructive-functions.svc.cluster.local:11434"
EMBEDDING_MODEL: "nomic-embed-text:latest"
26 changes: 26 additions & 0 deletions k8s/overlays/local-simple/ollama-pull-job.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
apiVersion: batch/v1
kind: Job
metadata:
name: ollama-pull-model
spec:
ttlSecondsAfterFinished: 300
template:
spec:
restartPolicy: OnFailure
initContainers:
- name: wait-for-ollama
image: busybox:1.36
command: ['sh', '-c', 'until nc -z ollama 11434; do echo "Waiting for Ollama..."; sleep 2; done']
containers:
- name: pull-model
image: curlimages/curl:8.5.0
command:
- sh
- -c
- |
echo "Pulling nomic-embed-text model..."
curl -X POST http://ollama:11434/api/pull \
-H "Content-Type: application/json" \
-d '{"name": "nomic-embed-text:latest"}' \
--max-time 600
echo "Model pull complete"
Comment on lines +20 to +26
Copy link

Copilot AI Apr 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pull job script doesn't fail on HTTP errors: curl will exit 0 on non-2xx responses unless --fail/--fail-with-body is used, so the Job can report success even when the model pull fails. Consider adding set -e(o) pipefail and using curl --fail-with-body (and optionally checking/printing the response) so failures surface and the job retries properly.

Copilot uses AI. Check for mistakes.
53 changes: 53 additions & 0 deletions k8s/overlays/local-simple/ollama.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: ollama
labels:
app: ollama
spec:
replicas: 1
selector:
matchLabels:
app: ollama
template:
metadata:
labels:
app: ollama
spec:
containers:
- name: ollama
image: ollama/ollama:latest
Copy link

Copilot AI Apr 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using the ollama/ollama:latest image tag makes the local dev environment non-reproducible (a new upstream release can silently change behavior). Consider pinning to a specific version tag (or digest) and updating it intentionally when needed.

Suggested change
image: ollama/ollama:latest
image: ollama/ollama:0.3.14

Copilot uses AI. Check for mistakes.
ports:
- name: http
containerPort: 11434
env:
- name: OLLAMA_HOST
value: "0.0.0.0"
resources:
requests:
cpu: "100m"
memory: "512Mi"
limits:
cpu: "1000m"
memory: "2Gi"
volumeMounts:
- name: ollama-data
mountPath: /root/.ollama
volumes:
- name: ollama-data
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
name: ollama
labels:
app: ollama
spec:
type: ClusterIP
selector:
app: ollama
ports:
- name: http
port: 11434
targetPort: http
Loading
Loading