Skip to content

Commit f2f3d8d

Browse files
committed
Added Cohere example [skip ci]
1 parent 22d51a5 commit f2f3d8d

3 files changed

Lines changed: 52 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ And follow the instructions for your database library:
3232
Or check out some examples:
3333

3434
- [Embeddings](examples/openai/example.js) with OpenAI
35+
- [Binary embeddings](examples/cohere/example.js) with Cohere
3536
- [Sentence embeddings](examples/transformers/example.js) with Transformers.js
3637
- [Hybrid search](examples/hybrid-search/example.js) with Transformers.js
3738
- [Recommendations](examples/disco/example.js) with Disco

examples/cohere/example.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { CohereClient } from 'cohere-ai';
2+
import pg from 'pg';
3+
import pgvector from 'pgvector/pg';
4+
5+
const client = new pg.Client({database: 'pgvector_example'});
6+
await client.connect();
7+
8+
await client.query('CREATE EXTENSION IF NOT EXISTS vector');
9+
await pgvector.registerTypes(client);
10+
11+
await client.query('DROP TABLE IF EXISTS documents');
12+
await client.query('CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding bit(1024))');
13+
14+
async function fetchEmbeddings(texts, inputType) {
15+
const cohere = new CohereClient();
16+
const response = await cohere.embed({
17+
texts: texts,
18+
model: 'embed-english-v3.0',
19+
inputType: inputType,
20+
embeddingTypes: ['ubinary']
21+
});
22+
return response.embeddings.ubinary.map((e) => e.map((v) => v.toString(2).padStart(8, '0')).join(''));
23+
}
24+
25+
const input = [
26+
'The dog is barking',
27+
'The cat is purring',
28+
'The bear is growling'
29+
];
30+
const embeddings = await fetchEmbeddings(input, 'search_document');
31+
for (let [i, content] of input.entries()) {
32+
await client.query('INSERT INTO documents (content, embedding) VALUES ($1, $2)', [content, embeddings[i]]);
33+
}
34+
35+
const query = 'forest';
36+
const queryEmbedding = (await fetchEmbeddings([query], 'search_query'))[0];
37+
const { rows } = await client.query('SELECT * FROM documents ORDER BY embedding <~> $1 LIMIT 5', [queryEmbedding]);
38+
for (let row of rows) {
39+
console.log(row.content);
40+
}
41+
42+
await client.end();

examples/cohere/package.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"private": true,
3+
"type": "module",
4+
"dependencies": {
5+
"cohere-ai": "^7.10.6",
6+
"pg": "^8.11.3",
7+
"pgvector": "file:../.."
8+
}
9+
}

0 commit comments

Comments
 (0)