Skip to content
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

feat: Ollama support #148

Merged
merged 6 commits into from
Feb 15, 2025
Merged

feat: Ollama support #148

merged 6 commits into from
Feb 15, 2025

Conversation

AAClause
Copy link
Member

@AAClause AAClause commented Aug 11, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new integration with the "Ollama" provider for enhanced AI interactions, including chat completions and advanced text/image processing.
    • Enabled dynamic retrieval of available AI models with flexible configuration options.
  • Chores

    • Updated project dependencies to include the ollama package for the new provider integration.

@AAClause AAClause added this to the v0.1a6 milestone Aug 25, 2024
@AAClause AAClause force-pushed the ollamaProvider branch 2 times, most recently from 6be1b51 to 01b03c0 Compare September 4, 2024 05:55
@AAClause AAClause modified the milestones: v0.1a6, v0.1a7 Sep 15, 2024
@AAClause AAClause modified the milestones: v0.1a9, v0.1a10 Nov 3, 2024
@AAClause AAClause force-pushed the ollamaProvider branch 2 times, most recently from 4926864 to 5943160 Compare February 9, 2025 18:24
@AAClause AAClause changed the base branch from master to customBaseURL February 9, 2025 18:25
@AAClause AAClause marked this pull request as ready for review February 14, 2025 18:44
@AAClause AAClause requested a review from clementb49 February 15, 2025 08:34
Base automatically changed from customBaseURL to master February 15, 2025 09:46
Copy link
Contributor

coderabbitai bot commented Feb 15, 2025

Walkthrough

This update adds support for integrating with the Ollama API. A new provider instance for "Ollama" is registered in the provider module, and an accompanying engine class (OllamaEngine) is implemented for handling interactions such as model retrieval, message preparation, and chat completions (including streaming responses). In addition, a new dependency on the ollama package (version ^0.4.7) has been added to the project configuration.

Changes

File(s) Change Summary
basilisk/provider.py
basilisk/provider_engine/ollama_engine.py
Added new Ollama integration components. The provider file registers a new "Ollama" instance, and the engine file introduces the OllamaEngine class with methods for model retrieval, client initialization, chat completion (with streaming and non-streaming responses), and message preparation.
pyproject.toml Introduced a new dependency: Added ollama = "^0.4.7" under the dependencies section.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant E as OllamaEngine
    participant C as Ollama Client
    participant A as Ollama API

    U->>E: Request chat completion
    E->>E: Prepare message request
    E->>C: Call chat(parameters)
    C->>A: Send chat request
    A-->>C: Return response (streaming/non-streaming)
    C-->>E: Deliver chat response
    E-->>U: Provide chat completion result
Loading

Possibly related PRs

  • feat(provider_engine): add DeepSeek integration #501: The changes in the main PR, which add a new Provider instance for "Ollama" in basilisk/provider.py, are related to the retrieved PR that also adds a new Provider instance for "DeepSeek" in the same file, indicating a similar modification pattern.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9f87065 and dfbae03.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • basilisk/provider.py (1 hunks)
  • basilisk/provider_engine/ollama_engine.py (1 hunks)
  • pyproject.toml (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
basilisk/provider_engine/ollama_engine.py

1-1: No such file or directory (os error 2)

(E902)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build_app / build_windows (x64)
🔇 Additional comments (8)
basilisk/provider_engine/ollama_engine.py (6)

1-2: Well-structured module docstring.
This docstring clearly states the purpose of the Ollama provider engine.

🧰 Tools
🪛 Ruff (0.8.2)

1-1: No such file or directory (os error 2)

(E902)


23-25: Class definition appears clear and concise.
The OllamaEngine class is a straightforward extension of BaseEngine, with a docstring that provides a succinct overview.


26-30: Confirm IMAGE support alignment.
You've declared ProviderCapability.IMAGE here. However, the engine only supports local image attachments in practice. If that's intentional, this is fine; otherwise, consider clarifying the partial image support in the class docstring.


64-75: Simple and effective property for client creation.
This property correctly handles the base URL override. No immediate concerns.


144-157: Straightforward streaming response handling.
This method efficiently iterates and yields content chunks. Implementation looks clean and correct for streaming.


158-176: Non-streaming response assignment is clear.
The method cleanly updates the MessageBlock with the assistant's content. No issues spotted.

basilisk/provider.py (1)

119-129: New provider registration looks good.
Ollama is set to run locally on the default port. If this is intentional, great. Otherwise, consider verifying that this is the desired default base URL or if HTTPS is possible.

pyproject.toml (1)

54-54: New dependency version check.
Verify ^0.4.7 meets all required capabilities and security patches for your application.

Comment on lines +31 to +63
@cached_property
@measure_time
def models(self) -> list[ProviderAIModel]:
"""Get Ollama models.

Returns:
A list of provider AI models.
"""
models = []
models_list = self.client.list().models
for model in models_list:
info = self.client.show(model.model)
context_length = 0
description = json.dumps(info.modelinfo, indent=2)
description += f"\n\n{info.license}"
for k, v in info.modelinfo.items():
if k.endswith("context_length"):
context_length = v
models.append(
ProviderAIModel(
id=model.model,
name=model.model,
description=description,
context_window=context_length,
max_output_tokens=0,
max_temperature=2,
default_temperature=1,
vision=True,
)
)

return models

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Validate handling of nullable or missing fields.
The logic for parsing info.license and info.modelinfo (especially context length) looks good. However, consider robust error handling or a helpful fallback if these fields are missing or unexpected in the Ollama response.

Comment on lines 77 to 107
def completion(
self,
new_block: MessageBlock,
conversation: Conversation,
system_message: Message | None,
**kwargs,
) -> ChatResponse | Iterator[ChatResponse]:
"""Get completion from Ollama.

Args:
new_block: The new message block.
conversation: The conversation instance.
system_message: The system message, if any.
**kwargs: Additional keyword arguments.

Returns:
The chat response or an iterator of chat responses.
"""
super().completion(new_block, conversation, system_message, **kwargs)
params = {
"model": new_block.model.model_id,
"messages": self.get_messages(
new_block, conversation, system_message
),
# "temperature": new_block.temperature,
# "top_p": new_block.top_p,
"stream": new_block.stream,
}
params.update(kwargs)
return self.client.chat(**params)

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider exposing temperature or top_p parameters.
You've commented out the temperature and top_p fields. If future usage requires them, ensure they are implemented consistently or removed if not needed.

Comment on lines 108 to 141
def prepare_message_request(self, message: Message):
"""Prepare message request for Ollama.

Args:
message: The message to prepare.

Returns:
The prepared message request.
"""
super().prepare_message_request(message)
images = []
if message.attachments:
for attachment in message.attachments:
location = str(attachment.location)
# TODO: fix `attachment.type` (currently returns IMAGE_UNKNOWN instead of IMAGE_LOCAL)
# best way: `if attachment.type != ImageFileTypes.IMAGE_LOCAL:``
if (
location.startswith("http")
or location.startswith("data:")
or location.startswith("memory://")
):
log.warning(
f"Received unsupported image type: {attachment.type}, {attachment.location}"
)
raise NotImplementedError(
"Only local images are supported for Ollama"
)
images.append(attachment.location)
return {
"role": message.role.value,
"content": message.content,
"images": images,
}

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Partial local-image-only support.
The direct raise of NotImplementedError for non-local images is a pragmatic approach for now. If you plan to expand to remote images, consider returning a structured error or partial fallback.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dfbae03 and 6e5da4b.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • basilisk/provider.py (1 hunks)
  • basilisk/provider_engine/ollama_engine.py (1 hunks)
  • pyproject.toml (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
basilisk/provider_engine/ollama_engine.py

1-1: No such file or directory (os error 2)

(E902)

🔇 Additional comments (5)
basilisk/provider_engine/ollama_engine.py (4)

42-49: Validate handling of nullable or missing fields.

The logic here doesn't account for the possibility that info.license or info.modelinfo might be absent or malformed in certain Ollama responses. Consider robust error handling or a fallback if these fields are missing or unexpected.


101-102: Consider exposing temperature or top_p parameters.

You’ve commented out the temperature and top_p fields. If future usage requires them, ensure they’re implemented consistently or removed if not needed.


125-135: Partial local-image-only support.

Raising NotImplementedError for non-local images is a pragmatic approach for now. If you plan to expand support for remote images, consider returning a structured error or fallback for a more graceful user experience.


158-175: Verify existence of response keys to avoid KeyError.

The code directly accesses response["message"]["content"] without fallback checks. If the response is missing the "message" or "content" keys, it will crash. Consider safe lookups or fallback logic to ensure reliability.

pyproject.toml (1)

54-54:

✅ Verification successful

Verify the added Ollama dependency.

Ensure the version ^0.4.7 is valid, up to date, and free of vulnerabilities.

Use this script to check for the latest version and any advisories:


🏁 Script executed:

#!/bin/bash
# Check the latest version from PyPI:
curl -s https://pypi.org/pypi/ollama/json | jq '.info.version'

# Check for security advisories:
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: PIP, package: "ollama") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}
'

Length of output: 411


Ollama dependency verified: using version ^0.4.7 is up to date and secure.

The dependency check shows that the installed version matches the latest release from PyPI (0.4.7) and no security advisories were reported via the GitHub API.

No changes are necessary.

Comment on lines +119 to +129
Provider(
id="ollama",
name="Ollama",
base_url="http://127.0.0.1:11434",
api_type=ProviderAPIType.OLLAMA,
organization_mode_available=False,
require_api_key=False,
env_var_name_api_key="OLLAMA_API_KEY",
engine_cls_path="basilisk.provider_engine.ollama_engine.OllamaEngine",
allow_custom_base_url=True,
),
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider robust handling of local vs. remote usage.

With require_api_key=False and a local base URL, the provider relies on an accessible local Ollama instance. If a remote configuration is desired in the future, consider providing fallback or guidance for scenarios where the local server is not running, improving user experience.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e5da4b and 110905e.

📒 Files selected for processing (1)
  • basilisk/provider_engine/ollama_engine.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
basilisk/provider_engine/ollama_engine.py

1-1: No such file or directory (os error 2)

(E902)

🔇 Additional comments (3)
basilisk/provider_engine/ollama_engine.py (3)

32-64: Handle missing info.license or info.modelinfo.
If the license or modelinfo fields are unexpectedly missing, this code might fail. Consider providing a fallback or more robust error handling.


57-58: Consider making temperature parameters user-configurable.

These default temperature values are defined but never exposed. If you plan to leverage them, consider allowing developers to override or adjust them via configuration or parameters. Otherwise, remove them to reduce clutter.


107-133: Support or gracefully handle remote images.

Currently, remote images cause an immediate NotImplementedError. If you need future support for remote images, consider implementing a structured fallback or partial handling rather than a hard failure.

Comment on lines +24 to +30
class OllamaEngine(BaseEngine):
"""Engine implementation for Ollama API integration."""

capabilities: set[ProviderCapability] = {
ProviderCapability.TEXT,
ProviderCapability.IMAGE,
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add unit tests for the new engine.

This engine class is critical for Ollama API integration yet it lacks direct test coverage. Please consider adding corresponding tests to maintain code reliability and facilitate future refactoring.

Would you like me to provide an initial test file scaffold for OllamaEngine?

Comment on lines +164 to +167
role=MessageRoleEnum.ASSISTANT,
content=response["message"]["content"],
)
return new_block
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add fallback or error handling for missing content in responses.

This line can raise a KeyError if "message" or "content" are absent from the response. Consider adding a safe fallback or raising a more descriptive error for debugging.

Here’s a potential fix:

- content=response["message"]["content"],
+ content=response.get("message", {}).get("content") or ""
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
role=MessageRoleEnum.ASSISTANT,
content=response["message"]["content"],
)
return new_block
role=MessageRoleEnum.ASSISTANT,
- content=response["message"]["content"],
+ content=response.get("message", {}).get("content") or "",
)
return new_block

@AAClause AAClause merged commit f1da849 into master Feb 15, 2025
9 of 10 checks passed
@AAClause AAClause deleted the ollamaProvider branch February 15, 2025 17:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants