45 Commits

Author SHA1 Message Date
kennethreitz 451ab798a4 refactor: Update Gemini provider to handle conversation-based completions and add structured response 2024-10-31 13:16:19 -04:00
kennethreitz 3505c8758d docs: Remove Google Gemini provider from README 2024-10-31 13:10:17 -04:00
kennethreitz 308886e608 refactor: update Gemini provider to handle conversation-based completions and remove unused variable 2024-10-31 13:10:03 -04:00
kennethreitz 9c18d726d5 refactor: update Gemini provider to handle conversation-based completions
This commit updates the Gemini provider in the `simplemind` module to handle conversation-based completions. Previously, the provider raised a `NotImplementedError` when attempting to send a conversation. Now, the provider properly converts the messages to Gemini's format and sends them to establish context. It also sends the final message and retrieves the response. The response is then used to create a properly formatted `Message` instance.

Refactor the `send_conversation` method in the `Gemini` class to handle conversation-based completions.

Fixes #<issue_number>
2024-10-31 13:08:20 -04:00
kennethreitz 8f43b660ea refactor: update return value in Gemini provider
The return value in the Gemini provider's `generate_text` method was updated from `response.result` to `response.text`. This change ensures consistency and clarity in the codebase.
2024-10-31 13:04:40 -04:00
kennethreitz 222d3025b1 fix: update Gemini provider to handle unimplemented features and improve error handling 2024-10-31 12:09:23 -04:00
kennethreitz fb6c4c289b docs: remove Google Gemini provider from README 2024-10-31 12:09:17 -04:00
kennethreitz c28e2a3839 refactor: update import paths for find_provider and Message 2024-10-31 11:58:05 -04:00
kennethreitz 2bed7221b3 Merge pull request #22 from Siddhesh-Agarwal/main
Added Gemini Provider
2024-10-31 11:55:47 -04:00
Siddhesh Agarwal 1504edad78 removed ABC as parent class 2024-10-31 20:50:17 +05:30
Siddhesh Agarwal fd7289c8d3 recommended changes 2024-10-31 20:40:21 +05:30
Siddhesh Agarwal c4674fc98f recommended changes 2024-10-31 20:39:24 +05:30
Siddhesh Agarwal 25806221eb removed test file 2024-10-31 19:40:56 +05:30
Siddhesh Agarwal 5505a3e18d improved type hinting 2024-10-31 18:42:54 +05:30
Siddhesh Agarwal 48291c37c5 added dependency + requires python is now 3.10 2024-10-31 18:13:10 +05:30
Siddhesh Agarwal 4b2b094ea6 moved to cached_property from property 2024-10-31 17:08:14 +05:30
Siddhesh Agarwal 33e4046ac3 ran isort on all files 2024-10-31 16:58:47 +05:30
Siddhesh Agarwal 7fe8e91111 Update README.md 2024-10-31 14:24:41 +05:30
Siddhesh Agarwal 42fc0e6bc5 coderabbit suggestions fix 2024-10-31 12:58:00 +05:30
Siddhesh Agarwal ec4f6f9c06 updated env template 2024-10-31 12:21:21 +05:30
Siddhesh Agarwal 499d3b3e14 Added Gemini API Key to settings + imported Gemini Provider 2024-10-31 12:18:51 +05:30
Siddhesh Agarwal dd2f5a46d2 added support for gemini 2024-10-31 11:56:21 +05:30
Siddhesh Agarwal bd0c739c9a improved type hinting 2024-10-31 11:42:38 +05:30
kennethreitz 473a054afa Update README.md 2024-10-30 20:25:39 -04:00
kennethreitz 55c28a2356 Delete t.py 2024-10-30 19:39:24 -04:00
kennethreitz 9bd1653b5e Update README.md 2024-10-30 19:35:48 -04:00
kennethreitz 59401c4be4 Update README.md 2024-10-30 19:33:22 -04:00
kennethreitz 20ad9437e5 Update README.md 2024-10-30 19:32:19 -04:00
kennethreitz 9db95cc87b Update README.md 2024-10-30 19:31:50 -04:00
kennethreitz d711afec68 Update README.md 2024-10-30 19:30:19 -04:00
kennethreitz 9d7fd4cce5 Update README.md 2024-10-30 19:29:36 -04:00
kennethreitz 4aa470bb20 Update README.md 2024-10-30 19:25:28 -04:00
kennethreitz 88e118cb53 Update README.md 2024-10-30 19:25:00 -04:00
kennethreitz 73316c32a3 Update README.md 2024-10-30 19:24:45 -04:00
kennethreitz e1331822aa Update README.md 2024-10-30 19:24:35 -04:00
kennethreitz baee6e9959 Update README.md 2024-10-30 19:22:27 -04:00
kennethreitz 8096609c2e Update README.md 2024-10-30 19:22:03 -04:00
kennethreitz 4225f61df3 Update README.md 2024-10-30 19:21:40 -04:00
kennethreitz 034e967ecb Update README.md 2024-10-30 19:20:56 -04:00
kennethreitz f9c4cce9a4 logo 2024-10-30 19:19:19 -04:00
kennethreitz 78f6649969 Update README.md 2024-10-30 19:17:44 -04:00
kennethreitz 4f1e52b1f8 Update CHANGELOG to clarify purpose of Session class as managing repeatability 2024-10-30 19:14:19 -04:00
kennethreitz 74c09d5c87 Refactor create_conversation and generate_data functions to improve type hints and maintain consistency in return types 2024-10-30 19:07:04 -04:00
kennethreitz 1f66bac645 **kwargs consistiency 2024-10-30 18:46:33 -04:00
kennethreitz f828f9991b Refactor create_conversation function to accept additional keyword arguments for flexibility 2024-10-30 18:43:29 -04:00
24 changed files with 333 additions and 145 deletions
+4 -3
View File
@@ -1,5 +1,6 @@
export OPENAI_API_KEY=""
export ANTHROPIC_API_KEY=""
export XAI_API_KEY=""
export OLLAMA_HOST_URL=""
export GEMINI_API_KEY=""
export GROQ_API_KEY=""
export OLLAMA_HOST_URL=""
export OPENAI_API_KEY=""
export XAI_API_KEY=""
+6 -1
View File
@@ -1,9 +1,14 @@
Release History
===============
## 0.1.5 (2024-10-31)
- Add Gemini provider.
- Add structured response to Gemini provider.
## 0.1.4 (2024-10-30)
- Introduce `Session` class to manage multiple conversations.
- Introduce `Session` class to manage repeatability.
- General improvements.
## 0.1.3 (2024-10-30)
+33 -33
View File
@@ -1,18 +1,17 @@
# SimpleMind: AI for Humans™
# Simplemind: AI for Humans™
**Keep it simple, keep it human.**
Simplemind is AI library designed to simplify your experience with AI APIs in Python. Inspired by a "for humans" philosophy, it abstracts away complexity, giving developers an intuitive and human-friendly way to interact with powerful AI capabilities.
![simplemind](https://github.com/user-attachments/assets/36df2103-2583-4958-ad5e-19cda7740256)
[![Auto Wiki](https://img.shields.io/badge/Auto_Wiki-Mutable.ai-blue)](https://mutable.ai/kennethreitz/simplemind)
SimpleMind is an AI library designed to simplify your experience with AI APIs in Python. Inspired by a "for humans" philosophy, it abstracts away complexity, giving developers an intuitive and human-friendly way to interact with powerful AI capabilities.
With SimpleMind, tapping into AI is as easy as a friendly conversation.
```bash
$ pip install simplemind
```
**Note**: SimpleMind is currently in beta. We welcome feedback and contributions to help make it even better.
## Features
With Simplemind, tapping into AI is as easy as a friendly conversation.
- **Easy-to-use AI tools**: SimpleMind provides simple interfaces to popular AI services.
- **Human-centered design**: The library prioritizes readability and usability—no need to be an expert to start experimenting.
- **Minimal configuration**: Get started quickly, without worrying about configuration headaches.
@@ -21,23 +20,29 @@ $ pip install simplemind
To specify a specific provider or model, you can use the `llm_provider` and `llm_model` parameters when calling: `generate_text`, `generate_data`, or `create_conversation`.
- **[OpenAI's GPT](https://openai.com/gpt)**
- **[Anthropic's Claude](https://www.anthropic.com/claude)**
- **[xAI's Grok](https://x.ai/)**
- **[Groq's Groq](https://groq.com/)**
- **[Ollama](https://ollama.com)**
- [**Anthropic's Claude**](https://www.anthropic.com/claude)
- [**Google's Gemini**](https://gemini.google/)
- [**Groq's Groq**](https://groq.com/)
- [**Ollama**](https://ollama.com)
- [**OpenAI's GPT**](https://openai.com/gpt)
- [**xAI's Grok**](https://x.ai/)
If you'd like to see SimpleMind support additional providers or models, please send a pull request!
If you want to see Simplemind support, additional providers or models, please request a pull!
## Why SimpleMind?
- **Intuitive**: Built with Pythonic simplicity and readability in mind.
- **For Humans**: Emphasizes a human-friendly interface, just like `requests` for HTTP.
- **Open Source**: SimpleMind is open source, and contributions are always welcome!
- **Open Source**: Simplemind is open source, and contributions are always welcome!
Also, why not? :)
## Quickstart
SimpleMind takes care of the complex API calls so you can focus on what matters—building, experimenting, and creating.
Simplemind takes care of the complex API calls so you can focus on what matters—building, experimenting, and creating.
```bash
$ pip install simplemind
```
First, authenticate your API keys by setting them in the environment variables:
@@ -47,7 +52,7 @@ $ export OPENAI_API_KEY="sk-..."
This pattern allows you to keep your API keys private and out of your codebase. Other supported environment variables: `ANTHROPIC_API_KEY`, `XAI_API_KEY`, and `GROQ_API_KEY`.
Next, import SimpleMind and start using it:
Next, import Simplemind and start using it:
```python
import simplemind as sm
@@ -56,7 +61,7 @@ import simplemind as sm
## Examples
Here are some examples of how to use SimpleMind:
Here are some examples of how to use Simplemind:
### Text Completion
@@ -114,8 +119,6 @@ To continue the conversation, you can call `conversation.send()` again, which re
You can use the `Session` class to set default parameters for all calls:
```python
import simplemind as sm
# Create a session with defaults
gpt_4o_mini = sm.Session(llm_provider="openai", llm_model="gpt-4o-mini")
@@ -138,10 +141,7 @@ response = gpt_4o_mini.generate_text(
Harnessing the power of Python, you can easily create your own plugins to add additional functionality to your conversations:
```python
import simplemind as sm
class SimpleMemoryPlugin:
class SimpleMemoryPlugin(sm.BasePlugin):
def __init__(self):
self.memories = [
"the earth has fictionally beeen destroyed.",
@@ -198,8 +198,12 @@ A reminder that in tales and fun,
The universe is never done.
```
Simple, yet effective.
Please see the [examples](examples) directory for executable examples.
-------------------
## Contributing
We welcome contributions of all kinds. Feel free to open issues for bug reports or feature requests, and submit pull requests to make SimpleMind even better.
@@ -211,11 +215,7 @@ To get started:
4. Submit a pull request.
## License
SimpleMind is licensed under the Apache 2.0 License.
Simplemind is licensed under the Apache 2.0 License.
## Acknowledgements
SimpleMind is inspired by the philosophy of "code for humans" and aims to make working with AI models accessible to all. Special thanks to the open-source community for their contributions and inspiration.
---------------
SimpleMind: Keep it simple, keep it human.
Simplemind is inspired by the philosophy of "code for humans" and aims to make working with AI models accessible to all. Special thanks to the open-source community for their contributions and inspiration.
+1 -1
View File
@@ -16,7 +16,7 @@ import simplemind
project = "simplemind"
copyright = "2024 Kenneth Reitz"
author = "Kenneth Reitz"
release = "v0.1.4"
release = "v0.1.5"
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
+7 -7
View File
@@ -1,14 +1,14 @@
from _context import sm
from pydantic import BaseModel
import openai
import faiss
import numpy as np
import os
import pickle
import faiss
import numpy as np
import openai
from _context import sm
from pydantic import BaseModel
class ContextualMemoryPlugin:
class ContextualMemoryPlugin(sm.BasePlugin):
def __init__(
self,
api_key: str,
+3 -4
View File
@@ -1,8 +1,7 @@
from typing import List, Iterator
from pydantic import BaseModel
from typing import Iterator, List
from _context import sm
from pydantic import BaseModel
class Movie(BaseModel):
@@ -25,7 +24,7 @@ class QuotesList(BaseModel):
quotes: List[MovieQuote]
def gen_quotes(n=10) -> Iterator[MovieQuote]:
def gen_quotes(n: int = 10) -> Iterator[MovieQuote]:
"""Generate a list of quotes from famous movies."""
for q in sm.generate_data(
+4 -2
View File
@@ -1,9 +1,11 @@
from _context import sm
class MathPlugin:
class MathPlugin(sm.BasePlugin):
def send_hook(self, conversation: sm.Conversation):
last_user_message = conversation.get_last_message(role="user")
if last_user_message is None:
return
if "calculate" in last_user_message.text.lower():
expression = last_user_message.text.lower().replace("calculate", "").strip()
try:
@@ -14,7 +16,7 @@ class MathPlugin:
except Exception:
conversation.add_message(
role="assistant",
text="I'm sorry, I couldn't compute that expression.",
text="I'm sorry, I couldn't compute that expression. Please try again.",
)
+3 -3
View File
@@ -1,8 +1,8 @@
from _context import sm
from pydantic import BaseModel
from typing import Literal
from _context import sm
from pydantic import BaseModel
class SentimentAnalysis(BaseModel):
sentiment: Literal["positive", "negative", "neutral"]
+1 -1
View File
@@ -1,7 +1,7 @@
from _context import sm
class SimpleMemoryPlugin(sm.BasePlugin):
class SimpleMemoryPlugin:
def __init__(self):
self.memories = [
"the earth has fictionally beeen destroyed.",
+3 -2
View File
@@ -1,6 +1,7 @@
import simplemind as sm
import time
import simplemind as sm
class ConversationPlugin(sm.BasePlugin):
def post_send_hook(self, conversation, response):
@@ -8,7 +9,7 @@ class ConversationPlugin(sm.BasePlugin):
print(f"{conversation.llm_model}:\n{response.text.strip()}\n\n------------\n")
def have_conversation(rounds=3):
def have_conversation(rounds: int = 3):
# Create two conversations - one for each AI
with (
sm.create_conversation(
Binary file not shown.

After

Width:  |  Height:  |  Size: 944 KiB

+3 -3
View File
@@ -1,10 +1,10 @@
[project]
name = "simplemind"
version = "0.1.4"
version = "0.1.5"
description = "An experimental client for AI providers that intends to replace LangChain and LangGraph for most common use cases."
readme = "README.md"
requires-python = ">=3.11"
dependencies = ["pydantic", "pydantic-settings", "instructor", "openai", "anthropic", "ollama", "groq"]
requires-python = ">=3.10"
dependencies = ["pydantic", "pydantic-settings", "instructor", "openai", "anthropic", "ollama", "groq", "google-generativeai"]
[build-system]
requires = ["hatchling"]
+27 -9
View File
@@ -1,8 +1,8 @@
from typing import List, Optional, Type
from typing import List, Type
from .models import Conversation, BasePlugin, BaseModel
from .utils import find_provider
from .models import BaseModel, BasePlugin, Conversation
from .settings import settings
from .utils import find_provider
class Session:
@@ -46,7 +46,7 @@ class Session:
**merged_kwargs,
)
def create_conversation(self, **kwargs) -> "Conversation":
def create_conversation(self, **kwargs) -> Conversation:
"""Create a conversation using the session's default provider and model."""
merged_kwargs = {**self.default_kwargs, **kwargs}
return create_conversation(
@@ -55,13 +55,18 @@ class Session:
def create_conversation(
llm_model=None, llm_provider=None, *, plugins: Optional[List[BasePlugin]] = None
):
*,
llm_model: str | None = None,
llm_provider: str | None = None,
plugins: List[BasePlugin] | None = None,
**kwargs,
) -> Conversation:
"""Create a new conversation."""
# Create the conversation.
conversation = Conversation(
llm_model=llm_model, llm_provider=llm_provider or settings.DEFAULT_LLM_PROVIDER
llm_model=llm_model,
llm_provider=llm_provider or settings.DEFAULT_LLM_PROVIDER,
)
# Add plugins to the conversation.
@@ -71,7 +76,14 @@ def create_conversation(
return conversation
def generate_data(prompt, *, llm_model=None, llm_provider=None, response_model=None):
def generate_data(
prompt: str,
*,
llm_model: str | None = None,
llm_provider: str | None = None,
response_model: Type[BaseModel],
**kwargs,
) -> BaseModel:
"""Generate structured data from a given prompt."""
# Find the provider.
@@ -85,7 +97,13 @@ def generate_data(prompt, *, llm_model=None, llm_provider=None, response_model=N
)
def generate_text(prompt, *, llm_model=None, llm_provider=None, **kwargs):
def generate_text(
prompt: str,
*,
llm_model: str | None = None,
llm_provider: str | None = None,
**kwargs,
) -> str:
"""Generate text from a given prompt."""
# Find the provider.
+37 -17
View File
@@ -1,18 +1,18 @@
from types import TracebackType
import uuid
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Field
from .utils import find_provider
MESSAGE_ROLE = Literal["system", "user", "assistant"]
class SMBaseModel(BaseModel):
"""The base SimpleMind model class."""
date_created: datetime = Field(default_factory=datetime.now)
def __str__(self):
@@ -22,34 +22,36 @@ class SMBaseModel(BaseModel):
return str(self)
class BasePlugin:
class BasePlugin(SMBaseModel):
"""The base conversation plugin class."""
# Plugin metadata.
meta: Dict[str, Any] = {}
def initialize_hook(self, conversation: "Conversation"):
def initialize_hook(self, conversation: "Conversation") -> Any:
"""Initialize a hook for the plugin."""
raise NotImplementedError
def cleanup_hook(self, conversation: "Conversation"):
def cleanup_hook(self, conversation: "Conversation") -> Any:
"""Cleanup a hook for the plugin."""
raise NotImplementedError
def add_message_hook(self, conversation: "Conversation", message: "Message"):
def add_message_hook(self, conversation: "Conversation", message: "Message") -> Any:
"""Add a message hook for the plugin."""
raise NotImplementedError
def pre_send_hook(self, conversation: "Conversation"):
def pre_send_hook(self, conversation: "Conversation") -> Any:
"""Pre-send hook for the plugin."""
raise NotImplementedError
def post_send_hook(self, conversation: "Conversation", response: "Message"):
def post_send_hook(self, conversation: "Conversation", response: "Message") -> Any:
"""Post-send hook for the plugin."""
raise NotImplementedError
class Message(SMBaseModel):
"""A message in a conversation."""
role: MESSAGE_ROLE
text: str
meta: Dict[str, Any] = {}
@@ -61,7 +63,16 @@ class Message(SMBaseModel):
return f"<Message role={self.role} text={self.text!r}>"
@classmethod
def from_raw_response(cls, *, text: str, raw):
def from_raw_response(cls, *, text: str, raw: Any) -> "Message":
"""Create a Message instance from a raw response.
Args:
text (str): The message text.
raw (Any): The raw response data.
Returns:
Message: A new Message instance.
"""
self = cls()
self.text = text
self.raw = raw
@@ -69,11 +80,13 @@ class Message(SMBaseModel):
class Conversation(SMBaseModel):
"""A conversation between a user and an assistant."""
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
messages: List[Message] = []
llm_model: Optional[str] = None
llm_provider: Optional[str] = None
plugins: List[Any] = []
plugins: List[BasePlugin] = []
def __str__(self):
return f"<Conversation id={self.id!r}>"
@@ -89,8 +102,13 @@ class Conversation(SMBaseModel):
return self
def __exit__(self, exc_type, exc_value, traceback):
# Execute all cleanup hooks.
def __exit__(
self,
exc_type: type[BaseException],
exc_value: BaseException,
traceback: TracebackType,
) -> None:
"""Execute all cleanup hooks."""
for plugin in self.plugins:
if hasattr(plugin, "cleanup_hook"):
try:
@@ -99,7 +117,7 @@ class Conversation(SMBaseModel):
pass
def prepend_system_message(
self, role: str, text: str, meta: Optional[Dict[str, Any]] = None
self, role: MESSAGE_ROLE, text: str, meta: Dict[str, Any] | None = None
):
"""Prepend a system message to the conversation."""
self.messages = [Message(role=role, text=text, meta=meta or {})] + self.messages
@@ -127,7 +145,9 @@ class Conversation(SMBaseModel):
self.messages.append(Message(role=role, text=text, meta=meta))
def send(
self, llm_model: Optional[str] = None, llm_provider: Optional[str] = None
self,
llm_model: str | None = None,
llm_provider: str | None = None,
) -> Message:
"""Send the conversation to the LLM."""
@@ -156,10 +176,10 @@ class Conversation(SMBaseModel):
return response
def get_last_message(self, role: MESSAGE_ROLE) -> Optional[Message]:
def get_last_message(self, role: MESSAGE_ROLE) -> Message | None:
"""Get the last message with the given role."""
return next((m for m in reversed(self.messages) if m.role == role), None)
def add_plugin(self, plugin: Any):
def add_plugin(self, plugin: BasePlugin) -> None:
"""Add a plugin to the conversation."""
self.plugins.append(plugin)
+3 -2
View File
@@ -2,9 +2,10 @@ from typing import List, Type
from ._base import BaseProvider
from .anthropic import Anthropic
from .gemini import Gemini
from .groq import Groq
from .openai import OpenAI
from .ollama import Ollama
from .openai import OpenAI
from .xai import XAI
providers: List[Type[BaseProvider]] = [Anthropic, Groq, OpenAI, Ollama, XAI]
providers: List[Type[BaseProvider]] = [Anthropic, Gemini, Groq, OpenAI, Ollama, XAI]
+9 -4
View File
@@ -1,6 +1,11 @@
from abc import ABC, abstractmethod
from functools import cached_property
from typing import Any, Type, TypeVar
from instructor import Instructor
from pydantic import BaseModel
T = TypeVar("T", bound=BaseModel)
class BaseProvider(ABC):
@@ -9,13 +14,13 @@ class BaseProvider(ABC):
NAME: str
DEFAULT_MODEL: str
@property
@cached_property
@abstractmethod
def client(self):
def client(self) -> Any:
"""The instructor client for the provider."""
raise NotImplementedError
@property
@cached_property
@abstractmethod
def structured_client(self) -> Instructor:
"""The structured client for the provider."""
@@ -27,7 +32,7 @@ class BaseProvider(ABC):
raise NotImplementedError
@abstractmethod
def structured_response(self, prompt: str, response_model, **kwargs):
def structured_response(self, prompt: str, response_model: Type[T], **kwargs) -> T:
"""Get a structured response."""
raise NotImplementedError
+13 -8
View File
@@ -1,10 +1,15 @@
from typing import Union
from functools import cached_property
from typing import Type, TypeVar
import anthropic
import instructor
from pydantic import BaseModel
from ._base import BaseProvider
from ..settings import settings
from ._base import BaseProvider
T = TypeVar("T", bound=BaseModel)
PROVIDER_NAME = "anthropic"
DEFAULT_MODEL = "claude-3-5-sonnet-20241022"
@@ -15,17 +20,17 @@ class Anthropic(BaseProvider):
NAME = PROVIDER_NAME
DEFAULT_MODEL = DEFAULT_MODEL
def __init__(self, api_key: Union[str, None] = None):
def __init__(self, api_key: str | None = None):
self.api_key = api_key or settings.get_api_key(PROVIDER_NAME)
@property
@cached_property
def client(self):
"""The raw Anthropic client."""
if not self.api_key:
raise ValueError("Anthropic API key is required")
return anthropic.Anthropic(api_key=self.api_key)
@property
@cached_property
def structured_client(self):
"""A client patched with Instructor."""
return instructor.from_anthropic(self.client)
@@ -57,13 +62,13 @@ class Anthropic(BaseProvider):
llm_provider=PROVIDER_NAME,
)
def structured_response(self, model, response_model, **kwargs):
def structured_response(self, model: str, response_model: Type[T], **kwargs) -> T:
response = self.structured_client.messages.create(
model=model, response_model=response_model or self.DEFAULT_MODEL, **kwargs
model=model or self.DEFAULT_MODEL, response_model=response_model, **kwargs
)
return response
def generate_text(self, prompt, *, llm_model, **kwargs):
def generate_text(self, prompt: str, *, llm_model: str, **kwargs):
messages = [
{"role": "user", "content": prompt},
]
+93
View File
@@ -0,0 +1,93 @@
# TODO: this is a placeholder file for the Gemini provider
# IT is not currently working as desired.
from functools import cached_property
from typing import Type, TypeVar
import google.generativeai as genai
import instructor
from pydantic import BaseModel
from ..settings import settings
from ._base import BaseProvider
PROVIDER_NAME = "gemini"
DEFAULT_MODEL = "models/gemini-1.5-flash-latest"
T = TypeVar("T", bound=BaseModel)
class Gemini(BaseProvider):
NAME = PROVIDER_NAME
DEFAULT_MODEL = DEFAULT_MODEL
def __init__(self, api_key: str | None = None):
self.api_key = api_key or settings.get_api_key(PROVIDER_NAME)
self.model_name = DEFAULT_MODEL
@cached_property
def client(self, model_name: str = DEFAULT_MODEL):
"""The raw Gemini client."""
if not self.api_key:
raise ValueError("Gemini API key is required")
self.model_name = model_name
return genai.GenerativeModel(model_name=self.model_name)
@cached_property
def structured_client(self):
"""A Gemini client patched with Instructor."""
return instructor.from_gemini(self.client)
def send_conversation(self, conversation: "Conversation") -> "Message":
"""Send a conversation to the Gemini API."""
from ..models import Message
# Convert messages to Gemini's format
chat = self.client.start_chat()
# Send all previous messages to establish context
for msg in conversation.messages[:-1]: # All messages except the last one
chat.send_message(msg.text)
# Send the final message and get response
try:
response = chat.send_message(conversation.messages[-1].text)
except Exception as e:
raise RuntimeError(f"Failed to send conversation to Gemini API: {e}") from e
# Create and return a properly formatted Message instance
return Message(
role="assistant",
text=response.text,
raw=response,
llm_model=self.model_name,
llm_provider=PROVIDER_NAME,
)
def structured_response(self, prompt: str, response_model: Type[T], **kwargs) -> T:
"""Send a structured response to the Gemini API."""
llm_model = kwargs.pop("llm_model", self.model_name)
try:
response = self.structured_client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
response_model=response_model,
**kwargs,
)
except Exception as e:
# Handle the exception appropriately, e.g., log the error or raise a custom exception
raise RuntimeError(
f"Failed to send structured response to Gemini API: {e}"
) from e
return response
def generate_text(self, prompt: str, **kwargs) -> str:
"""Generate text using the Gemini API."""
llm_model = kwargs.pop("llm_model", self.model_name)
try:
response = self.client.generate_content(prompt, **kwargs)
except Exception as e:
# Handle the exception appropriately, e.g., log the error or raise a custom exception
raise RuntimeError(f"Failed to generate text with Gemini API: {e}") from e
return response.text
+10 -6
View File
@@ -1,30 +1,34 @@
from typing import Union
from functools import cached_property
from typing import Type, TypeVar
import groq
import instructor
from pydantic import BaseModel
from ._base import BaseProvider
from ..settings import settings
from ._base import BaseProvider
PROVIDER_NAME = "groq"
DEFAULT_MODEL = "llama3-8b-8192"
T = TypeVar("T", bound=BaseModel)
class Groq(BaseProvider):
NAME = PROVIDER_NAME
DEFAULT_MODEL = DEFAULT_MODEL
def __init__(self, api_key: Union[str, None] = None):
def __init__(self, api_key: str | None = None):
self.api_key = api_key or settings.get_api_key(PROVIDER_NAME)
@property
@cached_property
def client(self):
"""The raw Groq client."""
if not self.api_key:
raise ValueError("Groq API key is required")
return groq.Groq(api_key=self.api_key)
@property
@cached_property
def structured_client(self):
"""A client patched with Instructor."""
return instructor.from_groq(self.client)
@@ -59,7 +63,7 @@ class Groq(BaseProvider):
llm_provider=PROVIDER_NAME,
)
def structured_response(self, prompt: str, response_model, **kwargs):
def structured_response(self, prompt: str, response_model: Type[T], **kwargs) -> T:
# Ensure messages are provided in kwargs
messages = [
{"role": "user", "content": prompt},
+23 -12
View File
@@ -1,9 +1,16 @@
import ollama as ol
import instructor
from openai import OpenAI
from functools import cached_property
from typing import Type, TypeVar
import instructor
import ollama as ol
from openai import OpenAI
from pydantic import BaseModel
from ._base import BaseProvider
from ..settings import settings
from ._base import BaseProvider
T = TypeVar("T", bound=BaseModel)
PROVIDER_NAME = "ollama"
DEFAULT_MODEL = "llama3.2"
@@ -15,18 +22,18 @@ class Ollama(BaseProvider):
DEFAULT_MODEL = DEFAULT_MODEL
TIMEOUT = DEFAULT_TIMEOUT
def __init__(self, host_url: str = None):
def __init__(self, host_url: str | None = None):
self.host_url = host_url or settings.OLLAMA_HOST_URL
@property
@cached_property
def client(self):
"""The raw Ollama client."""
if not self.host_url:
raise ValueError("No ollama host url provided")
return ol.Client(timeout=self.TIMEOUT, host=self.host_url)
@property
def structured_client(self):
@cached_property
def structured_client(self) -> instructor.Instructor:
"""A client patched with Instructor."""
return instructor.from_openai(
OpenAI(
@@ -36,7 +43,7 @@ class Ollama(BaseProvider):
mode=instructor.Mode.JSON,
)
def send_conversation(self, conversation: "Conversation"):
def send_conversation(self, conversation: "Conversation") -> "Message":
"""Send a conversation to the Ollama API."""
from ..models import Message
@@ -57,7 +64,10 @@ class Ollama(BaseProvider):
llm_provider=PROVIDER_NAME,
)
def structured_response(self, prompt, response_model, *, llm_model: str, **kwargs):
def structured_response(
self, prompt: str, response_model: Type[T], *, llm_model: str, **kwargs
) -> T:
"""Get a structured response from the Ollama API."""
messages = [
{"role": "user", "content": prompt},
]
@@ -70,7 +80,8 @@ class Ollama(BaseProvider):
)
return response
def generate_text(self, prompt, *, llm_model):
def generate_text(self, prompt: str, *, llm_model: str) -> str:
"""Generate text using the Ollama API."""
messages = [
{"role": "user", "content": prompt},
]
@@ -79,4 +90,4 @@ class Ollama(BaseProvider):
messages=messages, model=llm_model or self.DEFAULT_MODEL
)
return response.get("message").get("content")
return response.get("message", {}).get("content", "")
+20 -10
View File
@@ -1,10 +1,14 @@
from typing import Union
from functools import cached_property
from typing import Type, TypeVar
import instructor
import openai as oa
from pydantic import BaseModel
from ._base import BaseProvider
from ..settings import settings
from ._base import BaseProvider
T = TypeVar("T", bound=BaseModel)
PROVIDER_NAME = "openai"
DEFAULT_MODEL = "gpt-4o-mini"
@@ -14,17 +18,17 @@ class OpenAI(BaseProvider):
NAME = PROVIDER_NAME
DEFAULT_MODEL = DEFAULT_MODEL
def __init__(self, api_key: Union[str, None] = None):
def __init__(self, api_key: str | None = None):
self.api_key = api_key or settings.get_api_key(PROVIDER_NAME)
@property
@cached_property
def client(self):
"""The raw OpenAI client."""
if not self.api_key:
raise ValueError("OpenAI API key is required")
return oa.OpenAI(api_key=self.api_key)
@property
@cached_property
def structured_client(self):
"""A OpenAI client with Instructor."""
return instructor.from_openai(self.client)
@@ -53,12 +57,19 @@ class OpenAI(BaseProvider):
llm_provider=PROVIDER_NAME,
)
def structured_response(self, prompt, response_model, *, llm_model: str, **kwargs):
def structured_response(
self,
prompt: str,
response_model: Type[T],
*,
llm_model: str | None = None,
**kwargs,
) -> T:
"""Get a structured response from the OpenAI API."""
# Ensure messages are provided in kwargs
messages = [
{"role": "user", "content": prompt},
]
response = self.structured_client.chat.completions.create(
messages=messages,
model=llm_model or self.DEFAULT_MODEL,
@@ -67,13 +78,12 @@ class OpenAI(BaseProvider):
)
return response
def generate_text(self, prompt, *, llm_model, **kwargs):
def generate_text(self, prompt: str, *, llm_model: str | None = None, **kwargs):
"""Generate text using the OpenAI API."""
messages = [
{"role": "user", "content": prompt},
]
response = self.client.chat.completions.create(
messages=messages, model=llm_model or self.DEFAULT_MODEL, **kwargs
)
return response.choices[0].message.content
+7 -7
View File
@@ -1,10 +1,10 @@
from typing import Union
from functools import cached_property
import instructor
import openai as oa
from ._base import BaseProvider
from ..settings import settings
from ._base import BaseProvider
PROVIDER_NAME = "xai"
DEFAULT_MODEL = "grok-beta"
@@ -16,10 +16,10 @@ class XAI(BaseProvider):
NAME = PROVIDER_NAME
DEFAULT_MODEL = DEFAULT_MODEL
def __init__(self, api_key: Union[str, None] = None):
def __init__(self, api_key: str | None = None):
self.api_key = api_key or settings.get_api_key(PROVIDER_NAME)
@property
@cached_property
def client(self):
"""The raw OpenAI client."""
if not self.api_key:
@@ -29,7 +29,7 @@ class XAI(BaseProvider):
base_url=BASE_URL,
)
@property
@cached_property
def structured_client(self):
"""A client patched with Instructor."""
return instructor.from_openai(self.client)
@@ -60,10 +60,10 @@ class XAI(BaseProvider):
llm_provider=PROVIDER_NAME,
)
def structured_response(self, prompt: str, response_model, *, llm_model):
def structured_response(self, prompt: str, response_model, *, llm_model: str):
raise NotImplementedError("XAI does not support structured responses")
def generate_text(self, prompt, *, llm_model, **kwargs):
def generate_text(self, prompt: str, *, llm_model: str, **kwargs):
messages = [
{"role": "user", "content": prompt},
]
+14 -1
View File
@@ -1,8 +1,19 @@
from typing import Optional, Union
from typing import Literal, Optional, Union
from pydantic import Field, SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
logging_level = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
class LoggingConfig(BaseSettings):
"""The class that holds all the logging settings for the application."""
enabled: bool = Field(False, description="Enable logging")
level: logging_level = Field("INFO", description="The logging level")
model_config = SettingsConfigDict(extra="forbid")
class Settings(BaseSettings):
"""The class that holds all the API keys for the application."""
@@ -11,6 +22,7 @@ class Settings(BaseSettings):
None, description="API key for Anthropic"
)
GROQ_API_KEY: Optional[SecretStr] = Field(None, description="API key for Groq")
GEMINI_API_KEY: Optional[SecretStr] = Field(None, description="API key for Gemini")
OPENAI_API_KEY: Optional[SecretStr] = Field(None, description="API key for OpenAI")
OLLAMA_HOST_URL: Optional[str] = Field(
"http://127.0.0.1:11434", description="Fully qualified host URL for Ollama"
@@ -22,6 +34,7 @@ class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env", env_file_encoding="utf-8", case_sensitive=True, extra="ignore"
)
logging: LoggingConfig = LoggingConfig()
@field_validator("*", mode="before")
@classmethod
+9 -9
View File
@@ -1,24 +1,26 @@
import difflib
from typing import Optional, Type
from .providers import providers, BaseProvider
from .providers import BaseProvider, providers
_PROVIDER_NAMES = [provider.NAME.lower() for provider in providers]
def find_provider(provider_name: str) -> BaseProvider:
def find_provider(provider_name: str | None) -> BaseProvider:
"""
Find and instantiate a provider by name.
Parameters:
provider_name (Union[str, None]): The name of the provider to find.
provider_name (Union[str, None]): The name of the provider to find.
Returns:
An instance of the provider class if found.
An instance of the provider class if found.
Raises:
ValueError: If the provider is not found, with a suggestion for the closest match.
ValueError: If the provider is not specified or is not found, with a suggestion for the closest match.
"""
if provider_name is None:
raise ValueError("No provider specified.")
# Find the provider by name.
for provider_class in providers:
if provider_class.NAME.lower() == provider_name.lower():
@@ -29,10 +31,8 @@ def find_provider(provider_name: str) -> BaseProvider:
provider_found = difflib.get_close_matches(
provider_name.lower(), _PROVIDER_NAMES, n=1
)
if provider_found:
raise ValueError(
f"Provider {provider_name!r} not found. Did you mean {provider_found[0]!r}?"
)
else:
raise ValueError(f"Provider {provider_name} not found.")
raise ValueError(f"Provider {provider_name} not found.")