-
Notifications
You must be signed in to change notification settings - Fork 955
Feature/cog 1358 local ollama model support for cognee #555
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Vasilije1990
merged 8 commits into
dev
from
feature/cog-1358-local-ollama-model-support-for-cognee
Feb 19, 2025
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d69c208
feat: implements separate adapter for ollama
hajdul88 def9828
feat: implements separate embedding engine for ollama
hajdul88 cd66421
feat: integrates OllamaApiAdapter into get llm client
hajdul88 843c25f
feat: adds huggingface tokenizer parameter to config (only ollama emb…
hajdul88 bb4f469
Merge branch 'dev' into feature/cog-1358-local-ollama-model-support-f…
hajdul88 927b758
Merge branch 'dev' into feature/cog-1358-local-ollama-model-support-f…
Vasilije1990 93b04ab
Remove testing part
Vasilije1990 2325a88
Remove testing part
Vasilije1990 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
101 changes: 101 additions & 0 deletions
101
cognee/infrastructure/databases/vector/embeddings/OllamaEmbeddingEngine.py
This file contains hidden or 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,101 @@ | ||
| import asyncio | ||
| import httpx | ||
| import logging | ||
| from typing import List, Optional | ||
| import os | ||
|
|
||
| from cognee.infrastructure.databases.vector.embeddings.EmbeddingEngine import EmbeddingEngine | ||
| from cognee.infrastructure.databases.exceptions.EmbeddingException import EmbeddingException | ||
| from cognee.infrastructure.llm.tokenizer.HuggingFace import HuggingFaceTokenizer | ||
|
|
||
| logger = logging.getLogger("OllamaEmbeddingEngine") | ||
|
|
||
|
|
||
| class OllamaEmbeddingEngine(EmbeddingEngine): | ||
| model: str | ||
| dimensions: int | ||
| max_tokens: int | ||
| endpoint: str | ||
| mock: bool | ||
| huggingface_tokenizer_name: str | ||
|
|
||
| MAX_RETRIES = 5 | ||
|
|
||
| def __init__( | ||
| self, | ||
| model: Optional[str] = "avr/sfr-embedding-mistral:latest", | ||
| dimensions: Optional[int] = 1024, | ||
| max_tokens: int = 512, | ||
| endpoint: Optional[str] = "http://localhost:11434/api/embeddings", | ||
| huggingface_tokenizer: str = "Salesforce/SFR-Embedding-Mistral", | ||
| ): | ||
| self.model = model | ||
| self.dimensions = dimensions | ||
| self.max_tokens = max_tokens | ||
| self.endpoint = endpoint | ||
| self.huggingface_tokenizer_name = huggingface_tokenizer | ||
| self.tokenizer = self.get_tokenizer() | ||
|
|
||
| enable_mocking = os.getenv("MOCK_EMBEDDING", "false") | ||
| if isinstance(enable_mocking, bool): | ||
| enable_mocking = str(enable_mocking).lower() | ||
| self.mock = enable_mocking in ("true", "1", "yes") | ||
|
|
||
| async def embed_text(self, text: List[str]) -> List[List[float]]: | ||
| """ | ||
| Given a list of text prompts, returns a list of embedding vectors. | ||
| """ | ||
| if self.mock: | ||
| return [[0.0] * self.dimensions for _ in text] | ||
|
|
||
| embeddings = [] | ||
| async with httpx.AsyncClient() as client: | ||
| for prompt in text: | ||
| embedding = await self._get_embedding(client, prompt) | ||
| embeddings.append(embedding) | ||
| return embeddings | ||
|
|
||
| async def _get_embedding(self, client: httpx.AsyncClient, prompt: str) -> List[float]: | ||
| """ | ||
| Internal method to call the Ollama embeddings endpoint for a single prompt. | ||
| """ | ||
| payload = { | ||
| "model": self.model, | ||
| "prompt": prompt, | ||
| } | ||
| headers = {} | ||
| api_key = os.getenv("LLM_API_KEY") | ||
| if api_key: | ||
| headers["Authorization"] = f"Bearer {api_key}" | ||
|
|
||
| retries = 0 | ||
| while retries < self.MAX_RETRIES: | ||
| try: | ||
| response = await client.post( | ||
| self.endpoint, json=payload, headers=headers, timeout=60.0 | ||
| ) | ||
| response.raise_for_status() | ||
| data = response.json() | ||
| return data["embedding"] | ||
| except httpx.HTTPStatusError as e: | ||
| logger.error(f"HTTP error on attempt {retries + 1}: {e}") | ||
| retries += 1 | ||
| await asyncio.sleep(min(2**retries, 60)) | ||
| except Exception as e: | ||
| logger.error(f"Error on attempt {retries + 1}: {e}") | ||
| retries += 1 | ||
| await asyncio.sleep(min(2**retries, 60)) | ||
| raise EmbeddingException( | ||
| f"Failed to embed text using model {self.model} after {self.MAX_RETRIES} retries" | ||
| ) | ||
|
|
||
| def get_vector_size(self) -> int: | ||
| return self.dimensions | ||
|
|
||
| def get_tokenizer(self): | ||
| logger.debug("Loading HuggingfaceTokenizer for OllamaEmbeddingEngine...") | ||
| tokenizer = HuggingFaceTokenizer( | ||
| model=self.huggingface_tokenizer_name, max_tokens=self.max_tokens | ||
| ) | ||
| logger.debug("Tokenizer loaded for OllamaEmbeddingEngine") | ||
| return tokenizer |
This file contains hidden or 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 hidden or 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 hidden or 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
Empty file.
This file contains hidden or 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,44 @@ | ||
| from typing import Type | ||
| from pydantic import BaseModel | ||
| import instructor | ||
| from cognee.infrastructure.llm.llm_interface import LLMInterface | ||
| from cognee.infrastructure.llm.config import get_llm_config | ||
| from openai import OpenAI | ||
|
|
||
|
|
||
| class OllamaAPIAdapter(LLMInterface): | ||
| """Adapter for a Generic API LLM provider using instructor with an OpenAI backend.""" | ||
|
|
||
| def __init__(self, endpoint: str, api_key: str, model: str, name: str, max_tokens: int): | ||
| self.name = name | ||
| self.model = model | ||
| self.api_key = api_key | ||
| self.endpoint = endpoint | ||
| self.max_tokens = max_tokens | ||
|
|
||
| self.aclient = instructor.from_openai( | ||
| OpenAI(base_url=self.endpoint, api_key=self.api_key), mode=instructor.Mode.JSON | ||
| ) | ||
|
|
||
| async def acreate_structured_output( | ||
| self, text_input: str, system_prompt: str, response_model: Type[BaseModel] | ||
| ) -> BaseModel: | ||
| """Generate a structured output from the LLM using the provided text and system prompt.""" | ||
|
|
||
| response = self.aclient.chat.completions.create( | ||
| model=self.model, | ||
| messages=[ | ||
| { | ||
| "role": "user", | ||
| "content": f"Use the given format to extract information from the following input: {text_input}", | ||
| }, | ||
| { | ||
| "role": "system", | ||
| "content": system_prompt, | ||
| }, | ||
| ], | ||
| max_retries=5, | ||
| response_model=response_model, | ||
| ) | ||
|
|
||
| return response | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add error handling and configuration options.
The method should handle API errors and allow configuration of model parameters.
async def acreate_structured_output( self, text_input: str, system_prompt: str, response_model: Type[BaseModel] ) -> BaseModel: - """Generate a structured output from the LLM using the provided text and system prompt.""" + """Generate a structured output from Ollama using the provided text and system prompt. + + Args: + text_input: The input text to process + system_prompt: The system prompt to guide the model + response_model: Pydantic model for response structure + + Returns: + BaseModel: Structured response matching response_model + + Raises: + OpenAIError: If API call fails + ValueError: If input validation fails + """ + if not text_input or not system_prompt: + raise ValueError("text_input and system_prompt are required") - response = self.aclient.chat.completions.create( - model=self.model, - messages=[ - { - "role": "user", - "content": f"Use the given format to extract information from the following input: {text_input}", - }, - { - "role": "system", - "content": system_prompt, - }, - ], - max_retries=5, - response_model=response_model, - ) + try: + response = await self.aclient.chat.completions.create( + model=self.model, + messages=[ + { + "role": "user", + "content": f"Use the given format to extract information from the following input: {text_input}", + }, + { + "role": "system", + "content": system_prompt, + }, + ], + max_retries=5, + response_model=response_model, + temperature=0.7, # Add configurable parameters + timeout=30, # Add timeout + ) + return response + except Exception as e: + raise OpenAIError(f"Failed to generate structured output: {str(e)}") - return response📝 Committable suggestion