-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: adding basic similarity search as tool
- Loading branch information
1 parent
0e93021
commit 205ff82
Showing
5 changed files
with
53 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\ToolBox\Tool; | ||
|
||
use PhpLlm\LlmChain\Document\Document; | ||
use PhpLlm\LlmChain\EmbeddingModel; | ||
use PhpLlm\LlmChain\Store\VectorStoreInterface; | ||
use PhpLlm\LlmChain\ToolBox\AsTool; | ||
|
||
#[AsTool('similarity_search', description: 'Searches for documents similar to a query or sentence.')] | ||
final class SimilaritySearch | ||
{ | ||
/** | ||
* @var Document[] | ||
*/ | ||
public array $usedDocuments = []; | ||
|
||
public function __construct( | ||
private readonly EmbeddingModel $embedding, | ||
private readonly VectorStoreInterface $vectorStore, | ||
) { | ||
} | ||
|
||
/** | ||
* @param string $searchTerm string used for similarity search | ||
*/ | ||
public function __invoke(string $searchTerm): string | ||
{ | ||
$vector = $this->embedding->create($searchTerm); | ||
$this->usedDocuments = $this->vectorStore->query($vector); | ||
|
||
if (0 === count($this->usedDocuments)) { | ||
return 'No results found'; | ||
} | ||
|
||
$result = 'Found documents with following information:'.PHP_EOL; | ||
foreach ($this->usedDocuments as $document) { | ||
$result .= json_encode($document->metadata); | ||
} | ||
|
||
return $result; | ||
} | ||
} |