-
Notifications
You must be signed in to change notification settings - Fork 9
added cost tracking #79
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
Open
kmaximk
wants to merge
1
commit into
master
Choose a base branch
from
feature/cost_tracking
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| from coolprompt.language_model.tracker import ( | ||
| OpenAITracker, | ||
| TrackedLLMWrapper, | ||
| create_chat_model, | ||
| model_tracker, | ||
| ) | ||
| from coolprompt.language_model.llm import DefaultLLM | ||
|
|
||
| __all__ = [ | ||
| "OpenAITracker", | ||
| "TrackedLLMWrapper", | ||
| "create_chat_model", | ||
| "model_tracker", | ||
| "DefaultLLM", | ||
| ] | ||
|
|
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,113 @@ | ||
| from langchain_community.callbacks import get_openai_callback | ||
|
|
||
| from langchain_core.language_models.base import BaseLanguageModel | ||
| from langchain_core.language_models.chat_models import BaseChatModel | ||
| from langchain_core.messages import BaseMessage | ||
| from langchain_openai import ChatOpenAI | ||
| from typing import Any | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. вынеси на самый верх from typing import Any |
||
|
|
||
|
|
||
| class OpenAITracker: | ||
| _instance = None | ||
|
|
||
| def __new__(cls): | ||
| if cls._instance is None: | ||
| cls._instance = super().__new__(cls) | ||
| cls._instance._reset_stats() | ||
| return cls._instance | ||
|
|
||
| def _reset_stats(self): | ||
| self.stats = { | ||
| "total_calls": 0, | ||
| "total_tokens": 0, | ||
| "prompt_tokens": 0, | ||
| "completion_tokens": 0, | ||
| "total_cost": 0.0, | ||
| "invoke_calls": 0, | ||
| "batch_calls": 0, | ||
| "batch_items": 0, | ||
| } | ||
|
|
||
| def _update_stats(self, callback, invoke_flag, **kwargs): | ||
| self.stats["total_calls"] += 1 | ||
| self.stats["total_tokens"] += callback.total_tokens | ||
| self.stats["prompt_tokens"] += callback.prompt_tokens | ||
| self.stats["completion_tokens"] += callback.completion_tokens | ||
| self.stats["total_cost"] += callback.total_cost | ||
|
|
||
| if invoke_flag: | ||
| self.stats["invoke_calls"] += 1 | ||
| else: | ||
| self.stats["batch_calls"] += 1 | ||
| self.stats["batch_items"] += kwargs.get("batch_size", 0) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. почему по дефолту batch_size = 0, если произошел сам вызов модели? |
||
|
|
||
| def wrap_model(self, model): | ||
| return TrackedLLMWrapper(model, self) | ||
|
|
||
| def get_stats(self): | ||
| return self.stats.copy() | ||
|
|
||
| def reset_stats(self): | ||
| self._reset_stats() | ||
|
|
||
|
|
||
| class TrackedLLMWrapper(BaseLanguageModel): | ||
| model: Any | ||
| tracker: Any | ||
|
|
||
| def __init__(self, model, tracker): | ||
| super().__init__(model=model, tracker=tracker) | ||
|
|
||
| @property | ||
| def _llm_type(self): | ||
| return "tracked_" + getattr(self.model, "_llm_type", "llm") | ||
|
|
||
| def generate_prompt(self, prompts, stop=None, **kwargs): | ||
| return self.model.generate_prompt(prompts, stop=stop, **kwargs) | ||
|
|
||
| async def agenerate_prompt(self, prompts, stop=None, **kwargs): | ||
| return await self.model.agenerate_prompt(prompts, stop=stop, **kwargs) | ||
|
|
||
| def invoke(self, input, **kwargs): | ||
| with get_openai_callback() as cb: | ||
| result = self.model.invoke(input, **kwargs) | ||
| self.tracker._update_stats(cb, True) | ||
| return result | ||
|
|
||
| def batch(self, inputs, **kwargs): | ||
| with get_openai_callback() as cb: | ||
| results = self.model.batch(inputs, **kwargs) | ||
| self.tracker._update_stats(cb, False, batch_size=len(inputs)) | ||
| return results | ||
|
|
||
| def with_structured_output(self, schema, **kwargs): | ||
| if hasattr(self.model, 'with_structured_output'): | ||
| return self.model.with_structured_output(schema, **kwargs) | ||
| raise NotImplementedError( | ||
| f"Model {type(self.model)} does not support structured output" | ||
| ) | ||
|
|
||
| def reset_stats(self): | ||
| self.tracker.reset_stats() | ||
|
|
||
| def get_stats(self): | ||
| return self.tracker.get_stats() | ||
|
|
||
| def __getattr__(self, name): | ||
| return getattr(self.model, name) | ||
|
|
||
|
|
||
| model_tracker = OpenAITracker() | ||
|
|
||
|
|
||
| def create_chat_model(model=None, **kwargs): | ||
| if isinstance(model, BaseLanguageModel): | ||
| base_model = model | ||
| elif model is not None: | ||
| kwargs["model"] = model | ||
| base_model = ChatOpenAI(**kwargs) | ||
| else: | ||
| base_model = ChatOpenAI(**kwargs) | ||
|
|
||
| return model_tracker.wrap_model(base_model) | ||
|
|
||
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
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.
все новые классы и методы нужны обернуть докстрингами по Google Style Code (посмотри как у нас в других скриптах)