Ollama vs Ollama_Chat
587 lines
from itertools import chain
from itertools import chain
import requests, types, time # type: ignore
import requests
import json, uuid
import types
import time
import json
import uuid
import traceback
import traceback
from typing import Optional, List
from typing import Optional
import litellm
from litellm.types.utils import ProviderField
import httpx, aiohttp, asyncio # type: ignore
from .prompt_templates.factory import prompt_factory, custom_prompt
from litellm import verbose_logger
from litellm import verbose_logger
import litellm
import httpx
import aiohttp
class OllamaError(Exception):
class OllamaError(Exception):
def __init__(self, status_code, message):
def __init__(self, status_code, message):
self.status_code = status_code
self.status_code = status_code
self.message = message
self.message = message
self.request = httpx.Request(method="POST", url="http://localhost:11434")
self.request = httpx.Request(method="POST", url="http://localhost:11434")
self.response = httpx.Response(status_code=status_code, request=self.request)
self.response = httpx.Response(status_code=status_code, request=self.request)
super().__init__(
super().__init__(
self.message
self.message
) # Call the base class constructor with the parameters it needs
) # Call the base class constructor with the parameters it needs
class OllamaConfig:
class OllamaChatConfig:
"""
"""
Reference: https://github.com/ollama/ollama/blob/main/docs/api.md#parameters
Reference: https://github.com/ollama/ollama/blob/main/docs/api.md#parameters
The class `OllamaConfig` provides the configuration for the Ollama's API interface. Below are the parameters:
The class `OllamaConfig` provides the configuration for the Ollama's API interface. Below are the parameters:
- `mirostat` (int): Enable Mirostat sampling for controlling perplexity. Default is 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0. Example usage: mirostat 0
- `mirostat` (int): Enable Mirostat sampling for controlling perplexity. Default is 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0. Example usage: mirostat 0
- `mirostat_eta` (float): Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. Default: 0.1. Example usage: mirostat_eta 0.1
- `mirostat_eta` (float): Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. Default: 0.1. Example usage: mirostat_eta 0.1
- `mirostat_tau` (float): Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. Default: 5.0. Example usage: mirostat_tau 5.0
- `mirostat_tau` (float): Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. Default: 5.0. Example usage: mirostat_tau 5.0
- `num_ctx` (int): Sets the size of the context window used to generate the next token. Default: 2048. Example usage: num_ctx 4096
- `num_ctx` (int): Sets the size of the context window used to generate the next token. Default: 2048. Example usage: num_ctx 4096
- `num_gqa` (int): The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b. Example usage: num_gqa 1
- `num_gqa` (int): The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b. Example usage: num_gqa 1
- `num_gpu` (int): The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. Example usage: num_gpu 0
- `num_gpu` (int): The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. Example usage: num_gpu 0
- `num_thread` (int): Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Example usage: num_thread 8
- `num_thread` (int): Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Example usage: num_thread 8
- `repeat_last_n` (int): Sets how far back for the model to look back to prevent repetition. Default: 64, 0 = disabled, -1 = num_ctx. Example usage: repeat_last_n 64
- `repeat_last_n` (int): Sets how far back for the model to look back to prevent repetition. Default: 64, 0 = disabled, -1 = num_ctx. Example usage: repeat_last_n 64
- `repeat_penalty` (float): Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. Default: 1.1. Example usage: repeat_penalty 1.1
- `repeat_penalty` (float): Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. Default: 1.1. Example usage: repeat_penalty 1.1
- `temperature` (float): The temperature of the model. Increasing the temperature will make the model answer more creatively. Default: 0.8. Example usage: temperature 0.7
- `temperature` (float): The temperature of the model. Increasing the temperature will make the model answer more creatively. Default: 0.8. Example usage: temperature 0.7
- `seed` (int): Sets the random number seed to use for generation. Setting this to a specific number will make the model generate the same text for the same prompt. Example usage: seed 42
- `seed` (int): Sets the random number seed to use for generation. Setting this to a specific number will make the model generate the same text for the same prompt. Example usage: seed 42
- `stop` (string[]): Sets the stop sequences to use. Example usage: stop "AI assistant:"
- `stop` (string[]): Sets the stop sequences to use. Example usage: stop "AI assistant:"
- `tfs_z` (float): Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. Default: 1. Example usage: tfs_z 1
- `tfs_z` (float): Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. Default: 1. Example usage: tfs_z 1
- `num_predict` (int): Maximum number of tokens to predict when generating text. Default: 128, -1 = infinite generation, -2 = fill context. Example usage: num_predict 42
- `num_predict` (int): Maximum number of tokens to predict when generating text. Default: 128, -1 = infinite generation, -2 = fill context. Example usage: num_predict 42
- `top_k` (int): Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. Default: 40. Example usage: top_k 40
- `top_k` (int): Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. Default: 40. Example usage: top_k 40
- `top_p` (float): Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. Default: 0.9. Example usage: top_p 0.9
- `top_p` (float): Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. Default: 0.9. Example usage: top_p 0.9
- `system` (string): system prompt for model (overrides what is defined in the Modelfile)
- `system` (string): system prompt for model (overrides what is defined in the Modelfile)
- `template` (string): the full prompt or prompt template (overrides what is defined in the Modelfile)
- `template` (string): the full prompt or prompt template (overrides what is defined in the Modelfile)
"""
"""
mirostat: Optional[int] = None
mirostat: Optional[int] = None
mirostat_eta: Optional[float] = None
mirostat_eta: Optional[float] = None
mirostat_tau: Optional[float] = None
mirostat_tau: Optional[float] = None
num_ctx: Optional[int] = None
num_ctx: Optional[int] = None
num_gqa: Optional[int] = None
num_gqa: Optional[int] = None
num_thread: Optional[int] = None
num_thread: Optional[int] = None
repeat_last_n: Optional[int] = None
repeat_last_n: Optional[int] = None
repeat_penalty: Optional[float] = None
repeat_penalty: Optional[float] = None
temperature: Optional[float] = None
temperature: Optional[float] = None
seed: Optional[int] = None
seed: Optional[int] = None
stop: Optional[list] = (
stop: Optional[list] = (
None # stop is a list based on this - https://github.com/ollama/ollama/pull/442
None # stop is a list based on this - https://github.com/ollama/ollama/pull/442
)
)
tfs_z: Optional[float] = None
tfs_z: Optional[float] = None
num_predict: Optional[int] = None
num_predict: Optional[int] = None
top_k: Optional[int] = None
top_k: Optional[int] = None
top_p: Optional[float] = None
top_p: Optional[float] = None
system: Optional[str] = None
system: Optional[str] = None
template: Optional[str] = None
template: Optional[str] = None
def __init__(
def __init__(
self,
self,
mirostat: Optional[int] = None,
mirostat: Optional[int] = None,
mirostat_eta: Optional[float] = None,
mirostat_eta: Optional[float] = None,
mirostat_tau: Optional[float] = None,
mirostat_tau: Optional[float] = None,
num_ctx: Optional[int] = None,
num_ctx: Optional[int] = None,
num_gqa: Optional[int] = None,
num_gqa: Optional[int] = None,
num_thread: Optional[int] = None,
num_thread: Optional[int] = None,
repeat_last_n: Optional[int] = None,
repeat_last_n: Optional[int] = None,
repeat_penalty: Optional[float] = None,
repeat_penalty: Optional[float] = None,
temperature: Optional[float] = None,
temperature: Optional[float] = None,
seed: Optional[int] = None,
seed: Optional[int] = None,
stop: Optional[list] = None,
stop: Optional[list] = None,
tfs_z: Optional[float] = None,
tfs_z: Optional[float] = None,
num_predict: Optional[int] = None,
num_predict: Optional[int] = None,
top_k: Optional[int] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
top_p: Optional[float] = None,
system: Optional[str] = None,
system: Optional[str] = None,
template: Optional[str] = None,
template: Optional[str] = None,
) -> None:
) -> None:
locals_ = locals()
locals_ = locals()
for key, value in locals_.items():
for key, value in locals_.items():
if key != "self" and value is not None:
if key != "self" and value is not None:
setattr(self.__class__, key, value)
setattr(self.__class__, key, value)
@classmethod
@classmethod
def get_config(cls):
def get_config(cls):
return {
return {
k: v
k: v
for k, v in cls.__dict__.items()
for k, v in cls.__dict__.items()
if not k.startswith("__")
if not k.startswith("__")
and k != "function_name" # special param for function calling
and not isinstance(
and not isinstance(
v,
v,
(
(
types.FunctionType,
types.FunctionType,
types.BuiltinFunctionType,
types.BuiltinFunctionType,
classmethod,
classmethod,
staticmethod,
staticmethod,
),
),
)
)
and v is not None
and v is not None
}
}
def get_required_params(self) -> List[ProviderField]:
"""For a given provider, return it's required fields with a description"""
return [
ProviderField(
field_name="base_url",
field_type="string",
field_description="Your Ollama API Base",
field_value="http://10.10.11.249:11434",
)
]
def get_supported_openai_params(
def get_supported_openai_params(
self,
self,
):
):
return [
return [
"max_tokens",
"max_tokens",
"stream",
"stream",
"top_p",
"top_p",
"temperature",
"temperature",
"seed",
"seed",
"frequency_penalty",
"frequency_penalty",
"stop",
"stop",
"tools",
"tool_choice",
"functions",
"response_format",
"response_format",
]
]
def map_openai_params(self, non_default_params: dict, optional_params: dict):
# ollama wants plain base64 jpeg/png files as images. strip any leading dataURI
for param, value in non_default_params.items():
# and convert to jpeg if necessary.
if param == "max_tokens":
def _convert_image(image):
optional_params["num_predict"] = value
import base64, io
if param == "stream":
optional_params["stream"] = value
if param == "temperature":
optional_params["temperature"] = value
if param == "seed":
optional_params["seed"] = value
if param == "top_p":
optional_params["top_p"] = value
if param == "frequency_penalty":
optional_params["repeat_penalty"] = value
if param == "stop":
optional_params["stop"] = value
if param == "response_format" and value["type"] == "json_object":
optional_params["format"] = "json"
### FUNCTION CALLING LOGIC ###
if param == "tools":
# ollama actually supports json output
optional_params["format"] = "json"
litellm.add_function_to_prompt = (
True # so that main.py adds the function call to the prompt
)
optional_params["functions_unsupported_model"] = value
try:
if len(optional_params["functions_unsupported_model"]) == 1:
from PIL import Image
optional_params["function_name"] = optional_params[
except:
"functions_unsupported_model"
raise Exception(
][0]["function"]["name"]
"ollama image conversion failed please run `pip install Pillow`"
)
orig = image
if param == "functions":
if image.startswith("data:"):
# ollama actually supports json output
image = image.split(",")[-1]
optional_params["format"] = "json"
try:
litellm.add_function_to_prompt = (
image_data = Image.open(io.BytesIO(base64.b64decode(image)))
True # so that main.py adds the function call to the prompt
if image_data.format in ["JPEG", "PNG"]:
)
return image
optional_params["functions_unsupported_model"] = non_default_params.get(
except:
"functions"
return orig
)
jpeg_image = io.BytesIO()
non_default_params.pop("tool_choice", None) # causes ollama requests to hang
image_data.convert("RGB").save(jpeg_image, "JPEG")
non_default_params.pop("functions", None) # causes ollama requests to hang
jpeg_image.seek(0)
return optional_params
return base64.b64encode(jpeg_image.getvalue()).decode("utf-8")
# ollama implementation
# ollama implementation
def get_ollama_response(
def get_ollama_response(
api_base="http://localhost:11434",
api_base="http://localhost:11434",
api_key: Optional[str] = None,
model="llama2",
model="llama2",
prompt="Why is the sky blue?",
messages=None,
optional_params=None,
optional_params=None,
logging_obj=None,
logging_obj=None,
acompletion: bool = False,
acompletion: bool = False,
model_response=None,
model_response=None,
encoding=None,
encoding=None,
):
):
if api_base.endswith("/api/generate"):
if api_base.endswith("/api/chat"):
url = api_base
url = api_base
else:
else:
url = f"{api_base}/api/generate"
url = f"{api_base}/api/chat"
## Load Config
## Load Config
config = litellm.OllamaConfig.get_config()
config = litellm.OllamaChatConfig.get_config()
for k, v in config.items():
for k, v in config.items():
if (
if (
k not in optional_params
k not in optional_params
): # completion(top_k=3) > cohere_config(top_k=3) <- allows for dynamic variables to be passed in
): # completion(top_k=3) > cohere_config(top_k=3) <- allows for dynamic variables to be passed in
optional_params[k] = v
optional_params[k] = v
stream = optional_params.pop("stream", False)
stream = optional_params.pop("stream", False)
format = optional_params.pop("format", None)
format = optional_params.pop("format", None)
images = optional_params.pop("images", None)
function_name = optional_params.pop("function_name", None)
for m in messages:
if "role" in m and m["role"] == "tool":
m["role"] = "assistant"
data = {
data = {
"model": model,
"model": model,
"prompt": prompt,
"messages": messages,
"options": optional_params,
"options": optional_params,
"stream": stream,
"stream": stream,
}
}
if format is not None:
if format is not None:
data["format"] = format
data["format"] = format
if images is not None:
data["images"] = [_convert_image(image) for image in images]
## LOGGING
## LOGGING
logging_obj.pre_call(
logging_obj.pre_call(
input=None,
input=None,
api_key=None,
api_key=None,
additional_args={
additional_args={
"api_base": url,
"api_base": url,
"complete_input_dict": data,
"complete_input_dict": data,
"headers": {},
"headers": {},
"acompletion": acompletion,
"acompletion": acompletion,
},
},
)
)
if acompletion is True:
if acompletion is True:
if stream == True:
if stream == True:
response = ollama_async_streaming(
response = ollama_async_streaming(
url=url,
url=url,
api_key=api_key,
data=data,
data=data,
model_response=model_response,
model_response=model_response,
encoding=encoding,
encoding=encoding,
logging_obj=logging_obj,
logging_obj=logging_obj,
)
)
else:
else:
response = ollama_acompletion(
response = ollama_acompletion(
url=url,
url=url,
api_key=api_key,
data=data,
data=data,
model_response=model_response,
model_response=model_response,
encoding=encoding,
encoding=encoding,
logging_obj=logging_obj,
logging_obj=logging_obj,
function_name=function_name,
)
)
return response
return response
elif stream == True:
elif stream == True:
return ollama_completion_stream(url=url, data=data, logging_obj=logging_obj)
return ollama_completion_stream(
url=url, api_key=api_key, data=data, logging_obj=logging_obj
)
response = requests.post(
_request = {
url=f"{url}", json={**data, "stream": stream}, timeout=litellm.request_timeout
"url": f"{url}",
)
"json": data,
}
if api_key is not None:
_request["headers"] = "Bearer {}".format(api_key)
response = requests.post(**_request) # type: ignore
if response.status_code != 200:
if response.status_code != 200:
raise OllamaError(status_code=response.status_code, message=response.text)
raise OllamaError(status_code=response.status_code, message=response.text)
## LOGGING
## LOGGING
logging_obj.post_call(
logging_obj.post_call(
input=prompt,
input=messages,
api_key="",
api_key="",
original_response=response.text,
original_response=response.text,
additional_args={
additional_args={
"headers": None,
"headers": None,
"api_base": api_base,
"api_base": api_base,
},
},
)
)
response_json = response.json()
response_json = response.json()
## RESPONSE OBJECT
## RESPONSE OBJECT
model_response["choices"][0]["finish_reason"] = "stop"
model_response["choices"][0]["finish_reason"] = "stop"
if data.get("format", "") == "json":
if data.get("format", "") == "json":
function_call = json.loads(response_json["response"])
function_call = json.loads(response_json["message"]["content"])
message = litellm.Message(
message = litellm.Message(
content=None,
content=None,
tool_calls=[
tool_calls=[
{
{
"id": f"call_{str(uuid.uuid4())}",
"id": f"call_{str(uuid.uuid4())}",
"function": {
"function": {
"name": function_call["name"],
"name": function_call["name"],
"arguments": json.dumps(function_call["arguments"]),
"arguments": json.dumps(function_call["arguments"]),
},
},
"type": "function",
"type": "function",
}
}
],
],
)
)
model_response["choices"][0]["message"] = message
model_response["choices"][0]["message"] = message
model_response["choices"][0]["finish_reason"] = "tool_calls"
model_response["choices"][0]["finish_reason"] = "tool_calls"
else:
else:
model_response["choices"][0]["message"]["content"] = response_json["response"]
model_response["choices"][0]["message"]["content"] = response_json["message"][
"content"
]
model_response["created"] = int(time.time())
model_response["created"] = int(time.time())
model_response["model"] = "ollama/" + model
model_response["model"] = "ollama/" + model
prompt_tokens = response_json.get("prompt_eval_count", len(encoding.encode(prompt, disallowed_special=()))) # type: ignore
prompt_tokens = response_json.get("prompt_eval_count", litellm.token_counter(messages=messages)) # type: ignore
completion_tokens = response_json.get(
completion_tokens = response_json.get(
"eval_count", len(response_json.get("message", dict()).get("content", ""))
"eval_count", litellm.token_counter(text=response_json["message"]["content"])
)
)
model_response["usage"] = litellm.Usage(
model_response["usage"] = litellm.Usage(
prompt_tokens=prompt_tokens,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
)
)
return model_response
return model_response
def ollama_completion_stream(url, data, logging_obj):
def ollama_completion_stream(url, api_key, data, logging_obj):
with httpx.stream(
_request = {
url=url, json=data, method="POST", timeout=litellm.request_timeout
"url": f"{url}",
) as response:
"json": data,
"method": "POST",
"timeout": litellm.request_timeout,
}
if api_key is not None:
_request["headers"] = "Bearer {}".format(api_key)
with httpx.stream(**_request) as response:
try:
try:
if response.status_code != 200:
if response.status_code != 200:
raise OllamaError(
raise OllamaError(
status_code=response.status_code, message=response.text
status_code=response.status_code, message=response.iter_lines()
)
)
streamwrapper = litellm.CustomStreamWrapper(
streamwrapper = litellm.CustomStreamWrapper(
completion_stream=response.iter_lines(),
completion_stream=response.iter_lines(),
model=data["model"],
model=data["model"],
custom_llm_provider="ollama",
custom_llm_provider="ollama_chat",
logging_obj=logging_obj,
logging_obj=logging_obj,
)
)
# If format is JSON, this was a function call
# If format is JSON, this was a function call
# Gather all chunks and return the function call as one delta to simplify parsing
# Gather all chunks and return the function call as one delta to simplify parsing
if data.get("format", "") == "json":
if data.get("format", "") == "json":
first_chunk = next(streamwrapper)
first_chunk = next(streamwrapper)
response_content = "".join(
response_content = "".join(
chunk.choices[0].delta.content
chunk.choices[0].delta.content
for chunk in chain([first_chunk], streamwrapper)
for chunk in chain([first_chunk], streamwrapper)
if chunk.choices[0].delta.content
if chunk.choices[0].delta.content
)
)
function_call = json.loads(response_content)
function_call = json.loads(response_content)
delta = litellm.utils.Delta(
delta = litellm.utils.Delta(
content=None,
content=None,
tool_calls=[
tool_calls=[
{
{
"id": f"call_{str(uuid.uuid4())}",
"id": f"call_{str(uuid.uuid4())}",
"function": {
"function": {
"name": function_call["name"],
"name": function_call["name"],
"arguments": json.dumps(function_call["arguments"]),
"arguments": json.dumps(function_call["arguments"]),
},
},
"type": "function",
"type": "function",
}
}
],
],
)
)
model_response = first_chunk
model_response = first_chunk
model_response["choices"][0]["delta"] = delta
model_response["choices"][0]["delta"] = delta
model_response["choices"][0]["finish_reason"] = "tool_calls"
model_response["choices"][0]["finish_reason"] = "tool_calls"
yield model_response
yield model_response
else:
else:
for transformed_chunk in streamwrapper:
for transformed_chunk in streamwrapper:
yield transformed_chunk
yield transformed_chunk
except Exception as e:
except Exception as e:
raise e
raise e
async def ollama_async_streaming(url, data, model_response, encoding, logging_obj):
async def ollama_async_streaming(
url, api_key, data, model_response, encoding, logging_obj
):
try:
try:
client = httpx.AsyncClient()
client = httpx.AsyncClient()
async with client.stream(
_request = {
url=f"{url}", json=data, method="POST", timeout=litellm.request_timeout
"url": f"{url}",
) as response:
"json": data,
"method": "POST",
"timeout": litellm.request_timeout,
}
if api_key is not None:
_request["headers"] = "Bearer {}".format(api_key)
async with client.stream(**_request) as response:
if response.status_code != 200:
if response.status_code != 200:
raise OllamaError(
raise OllamaError(
status_code=response.status_code, message=await response.aread()
status_code=response.status_code, message=response.text
)
)
streamwrapper = litellm.CustomStreamWrapper(
streamwrapper = litellm.CustomStreamWrapper(
completion_stream=response.aiter_lines(),
completion_stream=response.aiter_lines(),
model=data["model"],
model=data["model"],
custom_llm_provider="ollama",
custom_llm_provider="ollama_chat",
logging_obj=logging_obj,
logging_obj=logging_obj,
)
)
# If format is JSON, this was a function call
# If format is JSON, this was a function call
# Gather all chunks and return the function call as one delta to simplify parsing
# Gather all chunks and return the function call as one delta to simplify parsing
if data.get("format", "") == "json":
if data.get("format", "") == "json":
first_chunk = await anext(streamwrapper)
first_chunk = await anext(streamwrapper)
first_chunk_content = first_chunk.choices[0].delta.content or ""
first_chunk_content = first_chunk.choices[0].delta.content or ""
response_content = first_chunk_content + "".join(
response_content = first_chunk_content + "".join(
[
[
chunk.choices[0].delta.content
chunk.choices[0].delta.content
async for chunk in streamwrapper
async for chunk in streamwrapper
if chunk.choices[0].delta.content
if chunk.choices[0].delta.content
]
]
)
)
function_call = json.loads(response_content)
function_call = json.loads(response_content)
delta = litellm.utils.Delta(
delta = litellm.utils.Delta(
content=None,
content=None,
tool_calls=[
tool_calls=[
{
{
"id": f"call_{str(uuid.uuid4())}",
"id": f"call_{str(uuid.uuid4())}",
"function": {
"function": {
"name": function_call["name"],
"name": function_call["name"],
"arguments": json.dumps(function_call["arguments"]),
"arguments": json.dumps(function_call["arguments"]),
},
},
"type": "function",
"type": "function",
}
}
],
],
)
)
model_response = first_chunk
model_response = first_chunk
model_response["choices"][0]["delta"] = delta
model_response["choices"][0]["delta"] = delta
model_response["choices"][0]["finish_reason"] = "tool_calls"
model_response["choices"][0]["finish_reason"] = "tool_calls"
yield model_response
yield model_response
else:
else:
async for transformed_chunk in streamwrapper:
async for transformed_chunk in streamwrapper:
yield transformed_chunk
yield transformed_chunk
except Exception as e:
except Exception as e:
verbose_logger.error(
verbose_logger.error("LiteLLM.gemini(): Exception occured - {}".format(str(e)))
"LiteLLM.ollama.py::ollama_async_streaming(): Exception occured - {}".format(
str(e)
)
)
verbose_logger.debug(traceback.format_exc())
verbose_logger.debug(traceback.format_exc())
raise e
async def ollama_acompletion(url, data, model_response, encoding, logging_obj):
async def ollama_acompletion(
url,
api_key: Optional[str],
data,
model_response,
encoding,
logging_obj,
function_name,
):
data["stream"] = False
data["stream"] = False
try:
try:
timeout = aiohttp.ClientTimeout(total=litellm.request_timeout) # 10 minutes
timeout = aiohttp.ClientTimeout(total=litellm.request_timeout) # 10 minutes
async with aiohttp.ClientSession(timeout=timeout) as session:
async with aiohttp.ClientSession(timeout=timeout) as session:
resp = await session.post(url, json=data)
_request = {
"url": f"{url}",
"json": data,
}
if api_key is not None:
_request["headers"] = "Bearer {}".format(api_key)
resp = await session.post(**_request)
if resp.status != 200:
if resp.status != 200:
text = await resp.text()
text = await resp.text()
raise OllamaError(status_code=resp.status, message=text)
raise OllamaError(status_code=resp.status, message=text)
response_json = await resp.json()
## LOGGING
## LOGGING
logging_obj.post_call(
logging_obj.post_call(
input=data["prompt"],
input=data,
api_key="",
api_key="",
original_response=resp.text,
original_response=response_json,
additional_args={
additional_args={
"headers": None,
"headers": None,
"api_base": url,
"api_base": url,
},
},
)
)
response_json = await resp.json()
## RESPONSE OBJECT
## RESPONSE OBJECT
model_response["choices"][0]["finish_reason"] = "stop"
model_response["choices"][0]["finish_reason"] = "stop"
if data.get("format", "") == "json":
if data.get("format", "") == "json":
function_call = json.loads(response_json["response"])
function_call = json.loads(response_json["message"]["content"])
message = litellm.Message(
message = litellm.Message(
content=None,
content=None,
tool_calls=[
tool_calls=[
{
{
"id": f"call_{str(uuid.uuid4())}",
"id": f"call_{str(uuid.uuid4())}",
"function": {
"function": {
"name": function_call["name"],
"name": function_call["name"],
"arguments": json.dumps(function_call["arguments"]),
"arguments": json.dumps(function_call["arguments"]),
},
},
"type": "function",
"type": "function",
}
}
],
],
)
)
model_response["choices"][0]["message"] = message
model_response["choices"][0]["message"] = message
model_response["choices"][0]["finish_reason"] = "tool_calls"
model_response["choices"][0]["finish_reason"] = "tool_calls"
else:
else:
model_response["choices"][0]["message"]["content"] = response_json[
model_response["choices"][0]["message"]["content"] = response_json[
"response"
"message"
]
]["content"]
model_response["created"] = int(time.time())
model_response["created"] = int(time.time())
model_response["model"] = "ollama/" + data["model"]
model_response["model"] = "ollama_chat/" + data["model"]
prompt_tokens = response_json.get("prompt_eval_count", len(encoding.encode(data["prompt"], disallowed_special=()))) # type: ignore
prompt_tokens = response_json.get("prompt_eval_count", litellm.token_counter(messages=data["messages"])) # type: ignore
completion_tokens = response_json.get(
completion_tokens = response_json.get(
"eval_count",
"eval_count",
len(response_json.get("message", dict()).get("content", "")),
litellm.token_counter(
text=response_json["message"]["content"], count_response_tokens=True
),
)
)
model_response["usage"] = litellm.Usage(
model_response["usage"] = litellm.Usage(
prompt_tokens=prompt_tokens,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
)
)
return model_response
return model_response
except Exception as e:
except Exception as e:
verbose_logger.error(
verbose_logger.error(
"LiteLLM.ollama.py::ollama_acompletion(): Exception occured - {}".format(
"LiteLLM.ollama_acompletion(): Exception occured - {}".format(str(e))
str(e)
)
)
)
verbose_logger.debug(traceback.format_exc())
verbose_logger.debug(traceback.format_exc())
raise e
raise e
async def ollama_aembeddings(
api_base: str,
model: str,
prompts: list,
optional_params=None,
logging_obj=None,
model_response=None,
encoding=None,
):
if api_base.endswith("/api/embeddings"):
url = api_base
else:
url = f"{api_base}/api/embeddings"
## Load Config
config = litellm.OllamaConfig.get_config()
for k, v in config.items():
if (
k not in optional_params
): # completion(top_k=3) > cohere_config(top_k=3) <- allows for dynamic variables to be passed in
optional_params[k] = v
total_input_tokens = 0
output_data = []
timeout = aiohttp.ClientTimeout(total=litellm.request_timeout) # 10 minutes
async with aiohttp.ClientSession(timeout=timeout) as session:
for idx, prompt in enumerate(prompts):
data = {
"model": model,
"prompt": prompt,
}
## LOGGING
logging_obj.pre_call(
input=None,
api_key=None,
additional_args={
"api_base": url,
"complete_input_dict": data,
"headers": {},
},
)
response = await session.post(url, json=data)
if response.status != 200:
text = await response.text()
raise OllamaError(status_code=response.status, message=text)
## LOGGING
logging_obj.post_call(
input=prompt,
api_key="",
original_response=response.text,
additional_args={
"headers": None,
"api_base": api_base,
},
)
response_json = await response.json()
embeddings: list[float] = response_json["embedding"]
output_data.append(
{"object": "embedding", "index": idx, "embedding": embeddings}
)
input_tokens = len(encoding.encode(prompt))
total_input_tokens += input_tokens
model_response["object"] = "list"
model_response["data"] = output_data
model_response["model"] = model
model_response["usage"] = {
"prompt_tokens": total_input_tokens,
"total_tokens": total_input_tokens,
}
return model_response
def ollama_embeddings(
api_base: str,
model: str,
prompts: list,
optional_params=None,
logging_obj=None,
model_response=None,
encoding=None,
):
return asyncio.run(
ollama_aembeddings(
api_base,
model,
prompts,
optional_params,
logging_obj,
model_response,
encoding,
)
)