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

[Suggestion] Add token counting to BaseLM #437

Merged
merged 1 commit into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions dspy/backends/lm/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@ def __call__(
) -> list[str]:
"""Generates `n` predictions for the signature output."""
...

@abstractmethod
def count_tokens(self, prompt: str) -> int:
"""Counts the number of tokens for a specific prompt."""
...
10 changes: 8 additions & 2 deletions dspy/backends/lm/litellm.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import typing as t

from litellm import completion
from litellm import completion, token_counter
from pydantic import Field


from .base import BaseLM


class LiteLLM(BaseLM):
STANDARD_PARAMS = {
STANDARD_PARAMS: t.Dict[str, t.Union[float, int]] = {
"temperature": 0.0,
"max_tokens": 150,
"top_p": 1,
Expand All @@ -33,3 +33,9 @@ def __call__(
)
choices = [c for c in response["choices"] if c["finish_reason"] != "length"]
return [c["message"]["content"] for c in choices]

def count_tokens(self, prompt: str) -> int:
"""Counts the number of tokens for a specific prompt."""
return token_counter(
model=self.model, messages=[{"role": "user", "content": prompt}]
)
Loading