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

Added New LLM Cohere #81

Merged
merged 4 commits into from
Oct 29, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions src/beyondllm/llms/cohere.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from beyondllm.llms.base import BaseLLMModel, ModelConfig
from typing import Any, Dict
from dataclasses import dataclass, field
import os
import cohere
Copy link
Member

Choose a reason for hiding this comment

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

import the cohere module inside load_llm refer to other LLMs. This needs to be under exception block


@dataclass
class CohereModel:
"""
Class representing a Language Model (LLM) model using Cohere.

Example:
```
>>> llm = CohereModel(api_key="<your_api_key>", model_kwargs={"temperature": 0.5})
```
or
```
>>> import os
>>> os.environ['COHERE_API_KEY'] = "***********" #replace with your key
>>> llm = CohereModel()
```
"""
api_key: str =" "
model_kwargs: dict = field(default_factory=lambda: {
"temperature": 0.5,
"top_p": 1,
"max_tokens": 2048,
})
madhavi-peddireddy marked this conversation as resolved.
Show resolved Hide resolved

def __post_init__(self):
if not self.api_key:
self.api_key = os.getenv('COHERE_API_KEY')
if not self.api_key:
raise ValueError("COHERE_API_KEY is not provided and not found in environment variables.")
self.load_llm()

def load_llm(self):
"""Load the Cohere client."""
try:
self.client = cohere.ClientV2(api_key=self.api_key)
except Exception as e:
raise Exception(f"Failed to initialize Cohere client: {str(e)}")

def predict(self, prompt: Any) -> str:
try:
response = self.client.chat(
model="command-r-plus-08-2024",
messages=[{"role": "user", "content": prompt}]
)
return response.message.content[0].text
except Exception as e:
raise Exception(f"Failed to generate prediction: {str(e)}")

@staticmethod
def load_from_kwargs(self, kwargs: Dict):
model_config = ModelConfig(**kwargs)
self.config = model_config
self.load_llm()

if __name__ == "__main__":
madhavi-peddireddy marked this conversation as resolved.
Show resolved Hide resolved
import os

# set the API key in an environment variable
os.environ['COHERE_API_KEY'] = " "

# Create an instance of CohereModel
llm = CohereModel()

# Make a prediction
prompt = "Write a Linkedin post on generative AI using emojis and symbols?"
response = llm.predict(prompt)

print(f"Response: {response}")