|
| 1 | +import json |
| 2 | +from copy import copy, deepcopy |
| 3 | +from dataclasses import dataclass, field |
| 4 | +from typing import List, Dict, Optional, Union |
| 5 | + |
| 6 | +from llama_cpp_agent.llm_output_settings import ( |
| 7 | + LlmStructuredOutputSettings, |
| 8 | + LlmStructuredOutputType, |
| 9 | +) |
| 10 | +from llama_cpp_agent.providers.provider_base import ( |
| 11 | + LlmProvider, |
| 12 | + LlmProviderId, |
| 13 | + LlmSamplingSettings, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class GroqSamplingSettings(LlmSamplingSettings): |
| 19 | + """ |
| 20 | + GroqSamplingSettings dataclass |
| 21 | + """ |
| 22 | + |
| 23 | + top_p: float = 1 |
| 24 | + temperature: float = 0.7 |
| 25 | + max_tokens: int = 16 |
| 26 | + stream: bool = False |
| 27 | + |
| 28 | + def get_provider_identifier(self) -> LlmProviderId: |
| 29 | + return LlmProviderId.groq |
| 30 | + |
| 31 | + def get_additional_stop_sequences(self) -> Union[List[str], None]: |
| 32 | + return None |
| 33 | + |
| 34 | + def add_additional_stop_sequences(self, sequences: List[str]): |
| 35 | + pass |
| 36 | + |
| 37 | + def is_streaming(self): |
| 38 | + return self.stream |
| 39 | + |
| 40 | + @staticmethod |
| 41 | + def load_from_dict(settings: dict) -> "GroqSamplingSettings": |
| 42 | + """ |
| 43 | + Load the settings from a dictionary. |
| 44 | +
|
| 45 | + Args: |
| 46 | + settings (dict): The dictionary containing the settings. |
| 47 | +
|
| 48 | + Returns: |
| 49 | + LlamaCppSamplingSettings: The loaded settings. |
| 50 | + """ |
| 51 | + return GroqSamplingSettings(**settings) |
| 52 | + |
| 53 | + def as_dict(self) -> dict: |
| 54 | + """ |
| 55 | + Convert the settings to a dictionary. |
| 56 | +
|
| 57 | + Returns: |
| 58 | + dict: The dictionary representation of the settings. |
| 59 | + """ |
| 60 | + return self.__dict__ |
| 61 | + |
| 62 | + |
| 63 | +class GroqProvider(LlmProvider): |
| 64 | + def __init__(self, base_url: str, model: str, huggingface_model: str, api_key: str = None): |
| 65 | + from openai import OpenAI |
| 66 | + from transformers import AutoTokenizer |
| 67 | + self.tokenizer = AutoTokenizer.from_pretrained(huggingface_model) |
| 68 | + self.client = OpenAI( |
| 69 | + base_url=base_url, |
| 70 | + api_key=api_key if api_key else "xxx-xxxxxxxx", |
| 71 | + ) |
| 72 | + self.model = model |
| 73 | + |
| 74 | + def is_using_json_schema_constraints(self): |
| 75 | + return True |
| 76 | + |
| 77 | + def get_provider_identifier(self) -> LlmProviderId: |
| 78 | + return LlmProviderId.groq |
| 79 | + |
| 80 | + def get_provider_default_settings(self) -> GroqSamplingSettings: |
| 81 | + return GroqSamplingSettings() |
| 82 | + |
| 83 | + def create_completion( |
| 84 | + self, |
| 85 | + prompt: str | list[dict], |
| 86 | + structured_output_settings: LlmStructuredOutputSettings, |
| 87 | + settings: GroqSamplingSettings, |
| 88 | + bos_token: str, |
| 89 | + ): |
| 90 | + tools = None |
| 91 | + if ( |
| 92 | + structured_output_settings.output_type |
| 93 | + == LlmStructuredOutputType.function_calling |
| 94 | + or structured_output_settings.output_type == LlmStructuredOutputType.parallel_function_calling |
| 95 | + ): |
| 96 | + tools = [tool.to_openai_tool() for tool in structured_output_settings.function_tools] |
| 97 | + top_p = settings.top_p |
| 98 | + stream = settings.stream |
| 99 | + temperature = settings.temperature |
| 100 | + max_tokens = settings.max_tokens |
| 101 | + |
| 102 | + settings_dict = deepcopy(settings.as_dict()) |
| 103 | + settings_dict.pop("top_p") |
| 104 | + settings_dict.pop("stream") |
| 105 | + settings_dict.pop("temperature") |
| 106 | + settings_dict.pop("max_tokens") |
| 107 | + |
| 108 | + if settings.stream: |
| 109 | + result = self.client.chat.completions.create( |
| 110 | + messages=prompt, |
| 111 | + model=self.model, |
| 112 | + extra_body=settings_dict, |
| 113 | + tools=tools, |
| 114 | + top_p=top_p, |
| 115 | + stream=stream, |
| 116 | + temperature=temperature, |
| 117 | + max_tokens=max_tokens, |
| 118 | + ) |
| 119 | + |
| 120 | + def generate_chunks(): |
| 121 | + for chunk in result: |
| 122 | + if chunk.choices[0].delta.tool_calls is not None: |
| 123 | + if tools is not None: |
| 124 | + args = chunk.choices[0].delta.tool_calls[0].function.arguments |
| 125 | + args_loaded = json.loads(args) |
| 126 | + function_name = chunk.choices[0].delta.tool_calls[0].function.name |
| 127 | + function_dict = {structured_output_settings.function_calling_name_field_name: function_name, structured_output_settings.function_calling_content: args_loaded} |
| 128 | + yield {"choices": [{"text": json.dumps(function_dict)}]} |
| 129 | + if chunk.choices[0].delta.content is not None: |
| 130 | + yield {"choices": [{"text": chunk.choices[0].delta.content}]} |
| 131 | + |
| 132 | + return generate_chunks() |
| 133 | + else: |
| 134 | + result = self.client.chat.completions.create( |
| 135 | + messages=prompt, |
| 136 | + model=self.model, |
| 137 | + extra_body=settings_dict, |
| 138 | + tools=tools, |
| 139 | + top_p=top_p, |
| 140 | + stream=stream, |
| 141 | + temperature=temperature, |
| 142 | + max_tokens=max_tokens, |
| 143 | + ) |
| 144 | + if tools is not None: |
| 145 | + args = result.choices[0].message.tool_calls[0].function.arguments |
| 146 | + args_loaded = json.loads(args) |
| 147 | + function_name = result.choices[0].message.tool_calls[0].function.name |
| 148 | + function_dict = {structured_output_settings.function_calling_name_field_name: function_name, structured_output_settings.function_calling_content: args_loaded} |
| 149 | + return {"choices": [{"text": json.dumps(function_dict)}]} |
| 150 | + return {"choices": [{"text": result.choices[0].message.content}]} |
| 151 | + |
| 152 | + def create_chat_completion( |
| 153 | + self, |
| 154 | + messages: List[Dict[str, str]], |
| 155 | + structured_output_settings: LlmStructuredOutputSettings, |
| 156 | + settings: GroqSamplingSettings |
| 157 | + ): |
| 158 | + grammar = None |
| 159 | + if ( |
| 160 | + structured_output_settings.output_type |
| 161 | + != LlmStructuredOutputType.no_structured_output |
| 162 | + ): |
| 163 | + grammar = structured_output_settings.get_json_schema() |
| 164 | + |
| 165 | + top_p = settings.top_p |
| 166 | + stream = settings.stream |
| 167 | + temperature = settings.temperature |
| 168 | + max_tokens = settings.max_tokens |
| 169 | + |
| 170 | + settings_dict = copy(settings.as_dict()) |
| 171 | + settings_dict.pop("top_p") |
| 172 | + settings_dict.pop("stream") |
| 173 | + settings_dict.pop("temperature") |
| 174 | + settings_dict.pop("max_tokens") |
| 175 | + if grammar is not None: |
| 176 | + settings_dict["guided_json"] = grammar |
| 177 | + |
| 178 | + if settings.stream: |
| 179 | + result = self.client.chat.completions.create( |
| 180 | + messages=messages, |
| 181 | + model=self.model, |
| 182 | + extra_body=settings_dict, |
| 183 | + top_p=top_p, |
| 184 | + stream=stream, |
| 185 | + temperature=temperature, |
| 186 | + max_tokens=max_tokens, |
| 187 | + ) |
| 188 | + |
| 189 | + def generate_chunks(): |
| 190 | + for chunk in result: |
| 191 | + if chunk.choices[0].delta.content is not None: |
| 192 | + yield {"choices": [{"text": chunk.choices[0].delta.content}]} |
| 193 | + |
| 194 | + return generate_chunks() |
| 195 | + else: |
| 196 | + result = self.client.chat.completions.create( |
| 197 | + messages=messages, |
| 198 | + model=self.model, |
| 199 | + extra_body=settings_dict, |
| 200 | + top_p=top_p, |
| 201 | + stream=stream, |
| 202 | + temperature=temperature, |
| 203 | + max_tokens=max_tokens, |
| 204 | + ) |
| 205 | + return {"choices": [{"text": result.choices[0].message.content}]} |
| 206 | + |
| 207 | + def tokenize(self, prompt: str) -> list[int]: |
| 208 | + result = self.tokenizer.encode(text=prompt) |
| 209 | + return result |
0 commit comments