Skip to content

A programming framework for agentic AI

Remove accidentally added files from 0.2 (#3661)

Jack Gerrits7f2599ad83b9
diff --git a/autogen/oai/cerebras.py b/autogen/oai/cerebras.py
deleted file mode 100644
index e87b048e1..000000000
--- a/autogen/oai/cerebras.py
+++ /dev/null
@@ -1,270 +0,0 @@
-"""Create an OpenAI-compatible client using Cerebras's API.
-
-Example:
- llm_config={
- "config_list": [{
- "api_type": "cerebras",
- "model": "llama3.1-8b",
- "api_key": os.environ.get("CEREBRAS_API_KEY")
- }]
- }
-
- agent = autogen.AssistantAgent("my_agent", llm_config=llm_config)
-
-Install Cerebras's python library using: pip install --upgrade cerebras_cloud_sdk
-
-Resources:
-- https://inference-docs.cerebras.ai/quickstart
-"""
-
-from __future__ import annotations
-
-import copy
-import os
-import time
-import warnings
-from typing import Any, Dict, List
-
-from cerebras.cloud.sdk import Cerebras, Stream
-from openai.types.chat import ChatCompletion, ChatCompletionMessageToolCall
-from openai.types.chat.chat_completion import ChatCompletionMessage, Choice
-from openai.types.completion_usage import CompletionUsage
-
-from autogen.oai.client_utils import should_hide_tools, validate_parameter
-
-CEREBRAS_PRICING_1K = {
- # Convert pricing per million to per thousand tokens.
- "llama3.1-8b": (0.10 / 1000, 0.10 / 1000),
- "llama3.1-70b": (0.60 / 1000, 0.60 / 1000),
-}
-
-
-class CerebrasClient:
- """Client for Cerebras's API."""
-
- def __init__(self, api_key=None, **kwargs):
- """Requires api_key or environment variable to be set
-
- Args:
- api_key (str): The API key for using Cerebras (or environment variable CEREBRAS_API_KEY needs to be set)
- """
- # Ensure we have the api_key upon instantiation
- self.api_key = api_key
- if not self.api_key:
- self.api_key = os.getenv("CEREBRAS_API_KEY")
-
- assert (
- self.api_key
- ), "Please include the api_key in your config list entry for Cerebras or set the CEREBRAS_API_KEY env variable."
-
- def message_retrieval(self, response: ChatCompletion) -> List:
- """
- Retrieve and return a list of strings or a list of Choice.Message from the response.
-
- NOTE: if a list of Choice.Message is returned, it currently needs to contain the fields of OpenAI's ChatCompletion Message object,
- since that is expected for function or tool calling in the rest of the codebase at the moment, unless a custom agent is being used.
- """
- return [choice.message for choice in response.choices]
-
- def cost(self, response: ChatCompletion) -> float:
- # Note: This field isn't explicitly in `ChatCompletion`, but is injected during chat creation.
- return response.cost
-
- @staticmethod
- def get_usage(response: ChatCompletion) -> Dict:
- """Return usage summary of the response using RESPONSE_USAGE_KEYS."""
- # ... # pragma: no cover
- return {
- "prompt_tokens": response.usage.prompt_tokens,
- "completion_tokens": response.usage.completion_tokens,
- "total_tokens": response.usage.total_tokens,
- "cost": response.cost,
- "model": response.model,
- }
-
- def parse_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
- """Loads the parameters for Cerebras API from the passed in parameters and returns a validated set. Checks types, ranges, and sets defaults"""
- cerebras_params = {}
-
- # Check that we have what we need to use Cerebras's API
- # We won't enforce the available models as they are likely to change
- cerebras_params["model"] = params.get("model", None)
- assert cerebras_params[
- "model"
- ], "Please specify the 'model' in your config list entry to nominate the Cerebras model to use."
-
- # Validate allowed Cerebras parameters
- # https://inference-docs.cerebras.ai/api-reference/chat-completions
- cerebras_params["max_tokens"] = validate_parameter(params, "max_tokens", int, True, None, (0, None), None)
- cerebras_params["seed"] = validate_parameter(params, "seed", int, True, None, None, None)
- cerebras_params["stream"] = validate_parameter(params, "stream", bool, True, False, None, None)
- cerebras_params["temperature"] = validate_parameter(
- params, "temperature", (int, float), True, 1, (0, 1.5), None
- )
- cerebras_params["top_p"] = validate_parameter(params, "top_p", (int, float), True, None, None, None)
-
- return cerebras_params
-
- def create(self, params: Dict) -> ChatCompletion:
-
- messages = params.get("messages", [])
-
- # Convert AutoGen messages to Cerebras messages
- cerebras_messages = oai_messages_to_cerebras_messages(messages)
-
- # Parse parameters to the Cerebras API's parameters
- cerebras_params = self.parse_params(params)
-
- # Add tools to the call if we have them and aren't hiding them
- if "tools" in params:
- hide_tools = validate_parameter(
- params, "hide_tools", str, False, "never", None, ["if_all_run", "if_any_run", "never"]
- )
- if not should_hide_tools(cerebras_messages, params["tools"], hide_tools):
- cerebras_params["tools"] = params["tools"]
-
- cerebras_params["messages"] = cerebras_messages
-
- # We use chat model by default, and set max_retries to 5 (in line with typical retries loop)
- client = Cerebras(api_key=self.api_key, max_retries=5)
-
- # Token counts will be returned
- prompt_tokens = 0
- completion_tokens = 0
- total_tokens = 0
-
- # Streaming tool call recommendations
- streaming_tool_calls = []
-
- ans = None
- try:
- response = client.chat.completions.create(**cerebras_params)
- except Exception as e:
- raise RuntimeError(f"Cerebras exception occurred: {e}")
- else:
-
- if cerebras_params["stream"]:
- # Read in the chunks as they stream, taking in tool_calls which may be across
- # multiple chunks if more than one suggested
- ans = ""
- for chunk in response:
- # Grab first choice, which _should_ always be generated.
- ans = ans + (chunk.choices[0].delta.content or "")
-
- if chunk.choices[0].delta.tool_calls:
- # We have a tool call recommendation
- for tool_call in chunk.choices[0].delta.tool_calls:
- streaming_tool_calls.append(
- ChatCompletionMessageToolCall(
- id=tool_call.id,
- function={
- "name": tool_call.function.name,
- "arguments": tool_call.function.arguments,
- },
- type="function",
- )
- )
-
- if chunk.choices[0].finish_reason:
- prompt_tokens = chunk.x_cerebras.usage.prompt_tokens
- completion_tokens = chunk.x_cerebras.usage.completion_tokens
- total_tokens = chunk.x_cerebras.usage.total_tokens
- else:
- # Non-streaming finished
- ans: str = response.choices[0].message.content
-
- prompt_tokens = response.usage.prompt_tokens
- completion_tokens = response.usage.completion_tokens
- total_tokens = response.usage.total_tokens
-
- if response is not None:
- if isinstance(response, Stream):
- # Streaming response
- if chunk.choices[0].finish_reason == "tool_calls":
- cerebras_finish = "tool_calls"
- tool_calls = streaming_tool_calls
- else:
- cerebras_finish = "stop"
- tool_calls = None
-
- response_content = ans
- response_id = chunk.id
- else:
- # Non-streaming response
- # If we have tool calls as the response, populate completed tool calls for our return OAI response
- if response.choices[0].finish_reason == "tool_calls":
- cerebras_finish = "tool_calls"
- tool_calls = []
- for tool_call in response.choices[0].message.tool_calls:
- tool_calls.append(
- ChatCompletionMessageToolCall(
- id=tool_call.id,
- function={"name": tool_call.function.name, "arguments": tool_call.function.arguments},
- type="function",
- )
- )
- else:
- cerebras_finish = "stop"
- tool_calls = None
-
- response_content = response.choices[0].message.content
- response_id = response.id
- else:
- raise RuntimeError("Failed to get response from Cerebras after retrying 5 times.")
-
- # 3. convert output
- message = ChatCompletionMessage(
- role="assistant",
- content=response_content,
- function_call=None,
- tool_calls=tool_calls,
- )
- choices = [Choice(finish_reason=cerebras_finish, index=0, message=message)]
-
- response_oai = ChatCompletion(
- id=response_id,
- model=cerebras_params["model"],
- created=int(time.time()),
- object="chat.completion",
- choices=choices,
- usage=CompletionUsage(
- prompt_tokens=prompt_tokens,
- completion_tokens=completion_tokens,
- total_tokens=total_tokens,
- ),
- # Note: This seems to be a field that isn't in the schema of `ChatCompletion`, so Pydantic
- # just adds it dynamically.
- cost=calculate_cerebras_cost(prompt_tokens, completion_tokens, cerebras_params["model"]),
- )
-
- return response_oai
-
-
-def oai_messages_to_cerebras_messages(messages: list[Dict[str, Any]]) -> list[dict[str, Any]]:
- """Convert messages from OAI format to Cerebras's format.
- We correct for any specific role orders and types.
- """
-
- cerebras_messages = copy.deepcopy(messages)
-
- # Remove the name field
- for message in cerebras_messages:
- if "name" in message:
- message.pop("name", None)
-
- return cerebras_messages
-
-
-def calculate_cerebras_cost(input_tokens: int, output_tokens: int, model: str) -> float:
- """Calculate the cost of the completion using the Cerebras pricing."""
- total = 0.0
-
- if model in CEREBRAS_PRICING_1K:
- input_cost_per_k, output_cost_per_k = CEREBRAS_PRICING_1K[model]
- input_cost = (input_tokens / 1000) * input_cost_per_k
- output_cost = (output_tokens / 1000) * output_cost_per_k
- total = input_cost + output_cost
- else:
- warnings.warn(f"Cost calculation not available for model {model}", UserWarning)
-
- return total
diff --git a/autogen/oai/ollama.py b/autogen/oai/ollama.py
deleted file mode 100644
index 636d152ae..000000000
--- a/autogen/oai/ollama.py
+++ /dev/null
@@ -1,579 +0,0 @@
-"""Create an OpenAI-compatible client using Ollama's API.
-
-Example:
- llm_config={
- "config_list": [{
- "api_type": "ollama",
- "model": "mistral:7b-instruct-v0.3-q6_K"
- }
- ]}
-
- agent = autogen.AssistantAgent("my_agent", llm_config=llm_config)
-
-Install Ollama's python library using: pip install --upgrade ollama
-
-Resources:
-- https://github.com/ollama/ollama-python
-"""
-
-from __future__ import annotations
-
-import copy
-import json
-import random
-import re
-import time
-import warnings
-from typing import Any, Dict, List, Tuple
-
-import ollama
-from fix_busted_json import repair_json
-from ollama import Client
-from openai.types.chat import ChatCompletion, ChatCompletionMessageToolCall
-from openai.types.chat.chat_completion import ChatCompletionMessage, Choice
-from openai.types.completion_usage import CompletionUsage
-
-from autogen.oai.client_utils import should_hide_tools, validate_parameter
-
-
-class OllamaClient:
- """Client for Ollama's API."""
-
- # Defaults for manual tool calling
- # Instruction is added to the first system message and provides directions to follow a two step
- # process
- # 1. (before tools have been called) Return JSON with the functions to call
- # 2. (directly after tools have been called) Return Text describing the results of the function calls in text format
-
- # Override using "manual_tool_call_instruction" config parameter
- TOOL_CALL_MANUAL_INSTRUCTION = (
- "You are to follow a strict two step process that will occur over "
- "a number of interactions, so pay attention to what step you are in based on the full "
- "conversation. We will be taking turns so only do one step at a time so don't perform step "
- "2 until step 1 is complete and I've told you the result. The first step is to choose one "
- "or more functions based on the request given and return only JSON with the functions and "
- "arguments to use. The second step is to analyse the given output of the function and summarise "
- "it returning only TEXT and not Python or JSON. "
- "For argument values, be sure numbers aren't strings, they should not have double quotes around them. "
- "In terms of your response format, for step 1 return only JSON and NO OTHER text, "
- "for step 2 return only text and NO JSON/Python/Markdown. "
- 'The format for running a function is [{"name": "function_name1", "arguments":{"argument_name": "argument_value"}},{"name": "function_name2", "arguments":{"argument_name": "argument_value"}}] '
- 'Make sure the keys "name" and "arguments" are as described. '
- "If you don't get the format correct, try again. "
- "The following functions are available to you:[FUNCTIONS_LIST]"
- )
-
- # Appended to the last user message if no tools have been called
- # Override using "manual_tool_call_step1" config parameter
- TOOL_CALL_MANUAL_STEP1 = " (proceed with step 1)"
-
- # Appended to the user message after tools have been executed. Will create a 'user' message if one doesn't exist.
- # Override using "manual_tool_call_step2" config parameter
- TOOL_CALL_MANUAL_STEP2 = " (proceed with step 2)"
-
- def __init__(self, **kwargs):
- """Note that no api_key or environment variable is required for Ollama.
-
- Args:
- None
- """
-
- def message_retrieval(self, response) -> List:
- """
- Retrieve and return a list of strings or a list of Choice.Message from the response.
-
- NOTE: if a list of Choice.Message is returned, it currently needs to contain the fields of OpenAI's ChatCompletion Message object,
- since that is expected for function or tool calling in the rest of the codebase at the moment, unless a custom agent is being used.
- """
- return [choice.message for choice in response.choices]
-
- def cost(self, response) -> float:
- return response.cost
-
- @staticmethod
- def get_usage(response) -> Dict:
- """Return usage summary of the response using RESPONSE_USAGE_KEYS."""
- # ... # pragma: no cover
- return {
- "prompt_tokens": response.usage.prompt_tokens,
- "completion_tokens": response.usage.completion_tokens,
- "total_tokens": response.usage.total_tokens,
- "cost": response.cost,
- "model": response.model,
- }
-
- def parse_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
- """Loads the parameters for Ollama API from the passed in parameters and returns a validated set. Checks types, ranges, and sets defaults"""
- ollama_params = {}
-
- # Check that we have what we need to use Ollama's API
- # https://github.com/ollama/ollama/blob/main/docs/api.md#generate-a-completion
-
- # The main parameters are model, prompt, stream, and options
- # Options is a dictionary of parameters for the model
- # There are other, advanced, parameters such as format, system (to override system message), template, raw, etc. - not used
-
- # We won't enforce the available models
- ollama_params["model"] = params.get("model", None)
- assert ollama_params[
- "model"
- ], "Please specify the 'model' in your config list entry to nominate the Ollama model to use."
-
- ollama_params["stream"] = validate_parameter(params, "stream", bool, True, False, None, None)
-
- # Build up the options dictionary
- # https://github.com/ollama/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values
- options_dict = {}
-
- if "num_predict" in params:
- # Maximum number of tokens to predict, note: -1 is infinite, -2 is fill context, 128 is default
- options_dict["num_predict"] = validate_parameter(params, "num_predict", int, False, 128, None, None)
-
- if "repeat_penalty" in params:
- options_dict["repeat_penalty"] = validate_parameter(
- params, "repeat_penalty", (int, float), False, 1.1, None, None
- )
-
- if "seed" in params:
- options_dict["seed"] = validate_parameter(params, "seed", int, False, 42, None, None)
-
- if "temperature" in params:
- options_dict["temperature"] = validate_parameter(
- params, "temperature", (int, float), False, 0.8, None, None
- )
-
- if "top_k" in params:
- options_dict["top_k"] = validate_parameter(params, "top_k", int, False, 40, None, None)
-
- if "top_p" in params:
- options_dict["top_p"] = validate_parameter(params, "top_p", (int, float), False, 0.9, None, None)
-
- if self._native_tool_calls and self._tools_in_conversation and not self._should_hide_tools:
- ollama_params["tools"] = params["tools"]
-
- # Ollama doesn't support streaming with tools natively
- if ollama_params["stream"] and self._native_tool_calls:
- warnings.warn(
- "Streaming is not supported when using tools and 'Native' tool calling, streaming will be disabled.",
- UserWarning,
- )
-
- ollama_params["stream"] = False
-
- if not self._native_tool_calls and self._tools_in_conversation:
- # For manual tool calling we have injected the available tools into the prompt
- # and we don't want to force JSON mode
- ollama_params["format"] = "" # Don't force JSON for manual tool calling mode
-
- if len(options_dict) != 0:
- ollama_params["options"] = options_dict
-
- return ollama_params
-
- def create(self, params: Dict) -> ChatCompletion:
-
- messages = params.get("messages", [])
-
- # Are tools involved in this conversation?
- self._tools_in_conversation = "tools" in params
-
- # We provide second-level filtering out of tools to avoid LLMs re-calling tools continuously
- if self._tools_in_conversation:
- hide_tools = validate_parameter(
- params, "hide_tools", str, False, "never", None, ["if_all_run", "if_any_run", "never"]
- )
- self._should_hide_tools = should_hide_tools(messages, params["tools"], hide_tools)
- else:
- self._should_hide_tools = False
-
- # Are we using native Ollama tool calling, otherwise we're doing manual tool calling
- # We allow the user to decide if they want to use Ollama's tool calling
- # or for tool calling to be handled manually through text messages
- # Default is True = Ollama's tool calling
- self._native_tool_calls = validate_parameter(params, "native_tool_calls", bool, False, True, None, None)
-
- if not self._native_tool_calls:
- # Load defaults
- self._manual_tool_call_instruction = validate_parameter(
- params, "manual_tool_call_instruction", str, False, self.TOOL_CALL_MANUAL_INSTRUCTION, None, None
- )
- self._manual_tool_call_step1 = validate_parameter(
- params, "manual_tool_call_step1", str, False, self.TOOL_CALL_MANUAL_STEP1, None, None
- )
- self._manual_tool_call_step2 = validate_parameter(
- params, "manual_tool_call_step2", str, False, self.TOOL_CALL_MANUAL_STEP2, None, None
- )
-
- # Convert AutoGen messages to Ollama messages
- ollama_messages = self.oai_messages_to_ollama_messages(
- messages,
- (
- params["tools"]
- if (not self._native_tool_calls and self._tools_in_conversation) and not self._should_hide_tools
- else None
- ),
- )
-
- # Parse parameters to the Ollama API's parameters
- ollama_params = self.parse_params(params)
-
- ollama_params["messages"] = ollama_messages
-
- # Token counts will be returned
- prompt_tokens = 0
- completion_tokens = 0
- total_tokens = 0
-
- ans = None
- try:
- if "client_host" in params:
- client = Client(host=params["client_host"])
- response = client.chat(**ollama_params)
- else:
- response = ollama.chat(**ollama_params)
- except Exception as e:
- raise RuntimeError(f"Ollama exception occurred: {e}")
- else:
-
- if ollama_params["stream"]:
- # Read in the chunks as they stream, taking in tool_calls which may be across
- # multiple chunks if more than one suggested
- ans = ""
- for chunk in response:
- ans = ans + (chunk["message"]["content"] or "")
-
- if "done_reason" in chunk:
- prompt_tokens = chunk["prompt_eval_count"] if "prompt_eval_count" in chunk else 0
- completion_tokens = chunk["eval_count"] if "eval_count" in chunk else 0
- total_tokens = prompt_tokens + completion_tokens
- else:
- # Non-streaming finished
- ans: str = response["message"]["content"]
-
- prompt_tokens = response["prompt_eval_count"] if "prompt_eval_count" in response else 0
- completion_tokens = response["eval_count"] if "eval_count" in response else 0
- total_tokens = prompt_tokens + completion_tokens
-
- if response is not None:
-
- # Defaults
- ollama_finish = "stop"
- tool_calls = None
-
- # Id and streaming text into response
- if ollama_params["stream"]:
- response_content = ans
- response_id = chunk["created_at"]
- else:
- response_content = response["message"]["content"]
- response_id = response["created_at"]
-
- # Process tools in the response
- if self._tools_in_conversation:
-
- if self._native_tool_calls:
-
- if not ollama_params["stream"]:
- response_content = response["message"]["content"]
-
- # Native tool calling
- if "tool_calls" in response["message"]:
- ollama_finish = "tool_calls"
- tool_calls = []
- random_id = random.randint(0, 10000)
- for tool_call in response["message"]["tool_calls"]:
- tool_calls.append(
- ChatCompletionMessageToolCall(
- id="ollama_func_{}".format(random_id),
- function={
- "name": tool_call["function"]["name"],
- "arguments": json.dumps(tool_call["function"]["arguments"]),
- },
- type="function",
- )
- )
-
- random_id += 1
-
- elif not self._native_tool_calls:
-
- # Try to convert the response to a tool call object
- response_toolcalls = response_to_tool_call(ans)
-
- # If we can, then we've got tool call(s)
- if response_toolcalls is not None:
- ollama_finish = "tool_calls"
- tool_calls = []
- random_id = random.randint(0, 10000)
-
- for json_function in response_toolcalls:
- tool_calls.append(
- ChatCompletionMessageToolCall(
- id="ollama_manual_func_{}".format(random_id),
- function={
- "name": json_function["name"],
- "arguments": (
- json.dumps(json_function["arguments"])
- if "arguments" in json_function
- else "{}"
- ),
- },
- type="function",
- )
- )
-
- random_id += 1
-
- # Blank the message content
- response_content = ""
-
- else:
- raise RuntimeError("Failed to get response from Ollama.")
-
- # Convert response to AutoGen response
- message = ChatCompletionMessage(
- role="assistant",
- content=response_content,
- function_call=None,
- tool_calls=tool_calls,
- )
- choices = [Choice(finish_reason=ollama_finish, index=0, message=message)]
-
- response_oai = ChatCompletion(
- id=response_id,
- model=ollama_params["model"],
- created=int(time.time()),
- object="chat.completion",
- choices=choices,
- usage=CompletionUsage(
- prompt_tokens=prompt_tokens,
- completion_tokens=completion_tokens,
- total_tokens=total_tokens,
- ),
- cost=0, # Local models, FREE!
- )
-
- return response_oai
-
- def oai_messages_to_ollama_messages(self, messages: list[Dict[str, Any]], tools: list) -> list[dict[str, Any]]:
- """Convert messages from OAI format to Ollama's format.
- We correct for any specific role orders and types, and convert tools to messages (as Ollama can't use tool messages)
- """
-
- ollama_messages = copy.deepcopy(messages)
-
- # Remove the name field
- for message in ollama_messages:
- if "name" in message:
- message.pop("name", None)
-
- # Having a 'system' message on the end does not work well with Ollama, so we change it to 'user'
- # 'system' messages on the end are typical of the summarisation message: summary_method="reflection_with_llm"
- if len(ollama_messages) > 1 and ollama_messages[-1]["role"] == "system":
- ollama_messages[-1]["role"] = "user"
-
- # Process messages for tool calling manually
- if tools is not None and not self._native_tool_calls:
- # 1. We need to append instructions to the starting system message on function calling
- # 2. If we have not yet called tools we append "step 1 instruction" to the latest user message
- # 3. If we have already called tools we append "step 2 instruction" to the latest user message
-
- have_tool_calls = False
- have_tool_results = False
- last_tool_result_index = -1
-
- for i, message in enumerate(ollama_messages):
- if "tool_calls" in message:
- have_tool_calls = True
- if "tool_call_id" in message:
- have_tool_results = True
- last_tool_result_index = i
-
- tool_result_is_last_msg = have_tool_results and last_tool_result_index == len(ollama_messages) - 1
-
- if ollama_messages[0]["role"] == "system":
- manual_instruction = self._manual_tool_call_instruction
-
- # Build a string of the functions available
- functions_string = ""
- for function in tools:
- functions_string += f"""\n{function}\n"""
-
- # Replace single quotes with double questions - Not sure why this helps the LLM perform
- # better, but it seems to. Monitor and remove if not necessary.
- functions_string = functions_string.replace("'", '"')
-
- manual_instruction = manual_instruction.replace("[FUNCTIONS_LIST]", functions_string)
-
- # Update the system message with the instructions and functions
- ollama_messages[0]["content"] = ollama_messages[0]["content"] + manual_instruction.rstrip()
-
- # If we are still in the function calling or evaluating process, append the steps instruction
- if not have_tool_calls or tool_result_is_last_msg:
- if ollama_messages[0]["role"] == "system":
- # NOTE: we require a system message to exist for the manual steps texts
- # Append the manual step instructions
- content_to_append = (
- self._manual_tool_call_step1 if not have_tool_results else self._manual_tool_call_step2
- )
-
- if content_to_append != "":
- # Append the relevant tool call instruction to the latest user message
- if ollama_messages[-1]["role"] == "user":
- ollama_messages[-1]["content"] = ollama_messages[-1]["content"] + content_to_append
- else:
- ollama_messages.append({"role": "user", "content": content_to_append})
-
- # Convert tool call and tool result messages to normal text messages for Ollama
- for i, message in enumerate(ollama_messages):
- if "tool_calls" in message:
- # Recommended tool calls
- content = "Run the following function(s):"
- for tool_call in message["tool_calls"]:
- content = content + "\n" + str(tool_call)
- ollama_messages[i] = {"role": "assistant", "content": content}
- if "tool_call_id" in message:
- # Executed tool results
- message["result"] = message["content"]
- del message["content"]
- del message["role"]
- content = "The following function was run: " + str(message)
- ollama_messages[i] = {"role": "user", "content": content}
-
- # As we are changing messages, let's merge if they have two user messages on the end and the last one is tool call step instructions
- if (
- len(ollama_messages) >= 2
- and not self._native_tool_calls
- and ollama_messages[-2]["role"] == "user"
- and ollama_messages[-1]["role"] == "user"
- and (
- ollama_messages[-1]["content"] == self._manual_tool_call_step1
- or ollama_messages[-1]["content"] == self._manual_tool_call_step2
- )
- ):
- ollama_messages[-2]["content"] = ollama_messages[-2]["content"] + ollama_messages[-1]["content"]
- del ollama_messages[-1]
-
- # Ensure the last message is a user / system message, if not, add a user message
- if ollama_messages[-1]["role"] != "user" and ollama_messages[-1]["role"] != "system":
- ollama_messages.append({"role": "user", "content": "Please continue."})
-
- return ollama_messages
-
-
-def response_to_tool_call(response_string: str) -> Any:
- """Attempts to convert the response to an object, aimed to align with function format [{},{}]"""
-
- # We try and detect the list[dict] format:
- # Pattern 1 is [{},{}]
- # Pattern 2 is {} (without the [], so could be a single function call)
- patterns = [r"\[[\s\S]*?\]", r"\{[\s\S]*\}"]
-
- for i, pattern in enumerate(patterns):
- # Search for the pattern in the input string
- matches = re.findall(pattern, response_string.strip())
-
- for match in matches:
-
- # It has matched, extract it and load it
- json_str = match.strip()
- data_object = None
-
- try:
- # Attempt to convert it as is
- data_object = json.loads(json_str)
- except Exception:
- try:
- # If that fails, attempt to repair it
-
- if i == 0:
- # Enclose to a JSON object for repairing, which is restored upon fix
- fixed_json = repair_json("{'temp':" + json_str + "}")
- data_object = json.loads(fixed_json)
- data_object = data_object["temp"]
- else:
- fixed_json = repair_json(json_str)
- data_object = json.loads(fixed_json)
- except json.JSONDecodeError as e:
- if e.msg == "Invalid \\escape":
- # Handle Mistral/Mixtral trying to escape underlines with \\
- try:
- json_str = json_str.replace("\\_", "_")
- if i == 0:
- fixed_json = repair_json("{'temp':" + json_str + "}")
- data_object = json.loads(fixed_json)
- data_object = data_object["temp"]
- else:
- fixed_json = repair_json("{'temp':" + json_str + "}")
- data_object = json.loads(fixed_json)
- except Exception:
- pass
- except Exception:
- pass
-
- if data_object is not None:
- data_object = _object_to_tool_call(data_object)
-
- if data_object is not None:
- return data_object
-
- # There's no tool call in the response
- return None
-
-
-def _object_to_tool_call(data_object: Any) -> List[Dict]:
- """Attempts to convert an object to a valid tool call object List[Dict] and returns it, if it can, otherwise None"""
-
- # If it's a dictionary and not a list then wrap in a list
- if isinstance(data_object, dict):
- data_object = [data_object]
-
- # Validate that the data is a list of dictionaries
- if isinstance(data_object, list) and all(isinstance(item, dict) for item in data_object):
- # Perfect format, a list of dictionaries
-
- # Check that each dictionary has at least 'name', optionally 'arguments' and no other keys
- is_invalid = False
- for item in data_object:
- if not is_valid_tool_call_item(item):
- is_invalid = True
- break
-
- # All passed, name and (optionally) arguments exist for all entries.
- if not is_invalid:
- return data_object
- elif isinstance(data_object, list):
- # If it's a list but the items are not dictionaries, check if they are strings that can be converted to dictionaries
- data_copy = data_object.copy()
- is_invalid = False
- for i, item in enumerate(data_copy):
- try:
- new_item = eval(item)
- if isinstance(new_item, dict):
- if is_valid_tool_call_item(new_item):
- data_object[i] = new_item
- else:
- is_invalid = True
- break
- else:
- is_invalid = True
- break
- except Exception:
- is_invalid = True
- break
-
- if not is_invalid:
- return data_object
-
- return None
-
-
-def is_valid_tool_call_item(call_item: dict) -> bool:
- """Check that a dictionary item has at least 'name', optionally 'arguments' and no other keys to match a tool call JSON"""
- if "name" not in call_item or not isinstance(call_item["name"], str):
- return False
-
- if set(call_item.keys()) - {"name", "arguments"}:
- return False
-
- return True
diff --git a/notebook/agentchat_function_call_with_composio.ipynb b/notebook/agentchat_function_call_with_composio.ipynb
deleted file mode 100644
index 1eea9e908..000000000
--- a/notebook/agentchat_function_call_with_composio.ipynb
+++ /dev/null
@@ -1,421 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "aRDQQophCLQs"
- },
- "source": [
- "# AI email agent using Composio"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "bZVu2lrqCLQu"
- },
- "source": [
- "This notebook demonstrates how to create an AI Email agent using Composio’s Gmail tool with autogen to create an agent that will automatically respond to emails based on provided instructions.\n",
- "\n",
- "[Composio](https://composio.dev/) allows an AI agent or LLM to easily connect to apps like Gmail, Slack, Trello etc. The key features of Composio are:"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "UI78uqxyCLQu"
- },
- "source": [
- "- Repository of Tools: Composio allows LLMs and agents to integrate with 100+ apps (Github, Salesforce, File Manager, Code Execution & More) to perform actions & subscribe to triggers(events).\n",
- "\n",
- "- Frameworks & LLM Agnostic: Composio provides out of box support for 10+ popular agentic frameworks and works with all the LLM providers using function calling.\n",
- "\n",
- "- Managed Auth: Composio helps manage authentication for all users/agents from a single dashboard."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Visit [Composio Docs](https://docs.composio.dev/introduction/intro/overview) to learn more."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "16kFQX0kCLQv"
- },
- "source": [
- "The notebook demonstrates how to create a Gmail integration with Composio, set up a trigger for new emails, initialize agents with tools and finally we'll see the agent in action."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "ixe3kpQrCLQv"
- },
- "source": [
- "````{=mdx}\n",
- ":::info Requirements\n",
- "Some extra dependencies are needed for this notebook, which can be installed via pip:\n",
- "\n",
- "```bash\n",
- "pip install autogen-agentchat~=0.2 composio-autogen\n",
- "```\n",
- "\n",
- "For more information, please refer to the [installation guide](/docs/installation/).\n",
- ":::\n",
- "````"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "XK6_H749CLQv"
- },
- "source": [
- "## Composio Setup\n",
- "\n",
- "To get started with using Composio's Gmail tool, we need to create an integration between Composio and Gmail. This can be done using a simple command -"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "-1XLfYJRCLQv"
- },
- "outputs": [],
- "source": [
- "!composio add gmail"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "T-YxALkYCLQw"
- },
- "source": [
- "To set up a trigger(basically a listener) for new emails -"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "YUzcCGaCCLQw"
- },
- "outputs": [],
- "source": [
- "!composio triggers enable gmail_new_gmail_message"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "yTM8eqE2CLQw"
- },
- "source": [
- "This enables the `gmail_new_gmail_message` trigger, which is fired when a new email is received in the connected account."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "GqlJ06y8CLQw"
- },
- "outputs": [],
- "source": [
- "import os\n",
- "\n",
- "from composio_autogen import Action, ComposioToolSet\n",
- "\n",
- "from autogen.agentchat import AssistantAgent, UserProxyAgent\n",
- "\n",
- "os.environ[\"OPENAI_API_KEY\"] = \"YOUR_API_KEY\""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "BHuqMynBCLQw"
- },
- "source": [
- "## Initialize agents"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "VzEYr6uuCLQw"
- },
- "outputs": [],
- "source": [
- "llm_config = {\"config_list\": [{\"model\": \"gpt-4o\", \"api_key\": os.environ.get(\"OPENAI_API_KEY\")}]}\n",
- "\n",
- "# Prompt for email assistant\n",
- "email_assistant_prompt = \"\"\"\n",
- " You are an AI email assistant specialized in drafting replies to emails.\n",
- " You create appropriate and professional replies to emails based on the content of the email.\n",
- " After executing the GMAIL_REPLY_TO_THREAD action and sending the email to the user, respond with TERMINATE.\n",
- "\"\"\"\n",
- "\n",
- "# Initialize AssistantAgent\n",
- "chatbot = AssistantAgent(\n",
- " \"chatbot\",\n",
- " system_message=email_assistant_prompt,\n",
- " llm_config=llm_config,\n",
- ")\n",
- "\n",
- "# Initialize UserProxyAgent\n",
- "user_proxy = UserProxyAgent(\n",
- " \"user_proxy\",\n",
- " is_termination_msg=lambda x: x.get(\"content\", \"\") and \"TERMINATE\" in x.get(\"content\", \"\"),\n",
- " human_input_mode=\"NEVER\",\n",
- " code_execution_config=False,\n",
- " llm_config=llm_config,\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "6SB0HFZ7CLQw"
- },
- "source": [
- "## Initialize Composio's Toolset\n",
- "\n",
- "Now, we initialize Composio's toolset and get the tools and actions we need for the agent. Then, we register the tools with the `UserProxyAgent`.\n",
- "\n",
- "The agent can then call the tools using function calling."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "_nosEvgxCLQx"
- },
- "outputs": [],
- "source": [
- "# Initialize Composio Toolset\n",
- "composio_toolset = ComposioToolSet()\n",
- "\n",
- "# Get the required tools and register them with the agents\n",
- "email_tools = composio_toolset.register_tools(\n",
- " caller=user_proxy,\n",
- " executor=chatbot,\n",
- " actions=[\n",
- " Action.GMAIL_REPLY_TO_THREAD,\n",
- " ],\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "kFkkMIIeCLQx"
- },
- "source": [
- "Here, we get the `GMAIL_REPLY_TO_THREAD` action, which is just a function that can be used to reply to an email. We'll be using this action to reply to emails automatically when they arrive."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "ZsgE3qm9CLQx"
- },
- "source": [
- "## Create trigger listener"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "fU6TmawGCLQx"
- },
- "source": [
- "Now, we create a listener for the trigger that we created above. This listener will listen for new emails and when a new email arrives, it'll provide data associated with the email like the sender email, email content etc. This data will be used by the attached callback function to invoke the agent and to send a reply to the email."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The `@listener.callback` decorator registers the function it decorates as a callback for a specific event trigger, in this case, when a new Gmail message is received (`GMAIL_NEW_GMAIL_MESSAGE`). It listens for the specified trigger and invokes the decorated function (`callback_new_message`) when the event occurs.\n",
- "\n",
- "After extracting the relevant data from the trigger payload, we start a conversation between `user_proxy` and `chatbot` to send a reply to the received email."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 1000
- },
- "id": "aDTm1tQECLQx",
- "outputId": "8aa5ab9a-9526-4287-e8f1-7b8ac9cfb0b3"
- },
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "INFO:composio.utils.shared:Creating trigger subscription\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Subscribed to triggers!\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "INFO:composio.utils.shared:Received trigger event with trigger ID: ea36d63f-5cc9-4581-9a19-b647e7468697 and trigger name: GMAIL_NEW_GMAIL_MESSAGE\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "user_proxy (to chatbot):\n",
- "\n",
- "\n",
- " Analyze the email content and create an appropriate reply. \n",
- " a. The email was received from John Doe <[email protected]> \n",
- " b. The content of the email is: hey, how are you?\n",
- " \n",
- " c. The thread id is: 1922811a78db4....\n",
- " \n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "chatbot (to user_proxy):\n",
- "\n",
- "GMAIL_REPLY_TO_THREAD thread_id: 1922811a78db4... message: \n",
- "Hi John,\n",
- "\n",
- "I'm doing well, thank you! How about you?\n",
- "\n",
- "Best,\n",
- "[Your Name]\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "user_proxy (to chatbot):\n",
- "\n",
- "***** Suggested tool call (call_qGQzJ6XgyO8LKSSFnwkQhSCz): GMAIL_REPLY_TO_THREAD_8c4b19f45c *****\n",
- "Arguments: \n",
- "{\"thread_id\":\"1922811a78db4...\",\"message_body\":\"Hi John,\\n\\nI'm doing well, thank you! How about you?\\n\\nBest,\\n[Your Name]\",\"recipient_email\":\"[email protected]\"}\n",
- "*************************************************************************************************\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\n",
- ">>>>>>>> EXECUTING FUNCTION GMAIL_REPLY_TO_THREAD_8c4b19f45c...\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "INFO:composio.utils.shared:Executing `GMAIL_REPLY_TO_THREAD` with params={'thread_id': '1922811a78db4...', 'message_body': \"Hi John,\\n\\nI'm doing well, thank you! How about you?\\n\\nBest,\\n[Your Name]\", 'recipient_email': '[email protected]'} and metadata={} connected_account_i...\n",
- "INFO:composio.utils.shared:Got response={'successfull': True, 'data': {'response_data': {'id': '1922811c1b3ed...', 'threadId': '1922811a78db4...', 'labelIds': ['SENT']}}, 'error': None} from action=<composio.client.enums._action.Action object at 0x7d50554c4310> with params={'thread_...\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "chatbot (to user_proxy):\n",
- "\n",
- "chatbot (to user_proxy):\n",
- "\n",
- "***** Response from calling tool (call_qGQzJ6XgyO8LKSSFnwkQhSCz) *****\n",
- "{\"successfull\": true, \"data\": {\"response_data\": {\"id\": \"1922811c1b3ed...\", \"threadId\": \"1922811a78db4...\", \"labelIds\": [\"SENT\"]}}, \"error\": null}\n",
- "**********************************************************************\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "user_proxy (to chatbot):\n",
- "\n",
- "I've replied to the email with the following message:\n",
- "\n",
- "Hi John,\n",
- "\n",
- "I'm doing well, thank you! How about you?\n",
- "\n",
- "Best,\n",
- "[Your Name]\n",
- "\n",
- "Is there anything else you need?\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "chatbot (to user_proxy):\n",
- "\n",
- "TERMINATE\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\n"
- ]
- }
- ],
- "source": [
- "# Create a trigger listener\n",
- "listener = composio_toolset.create_trigger_listener()\n",
- "\n",
- "\n",
- "@listener.callback(filters={\"trigger_name\": \"GMAIL_NEW_GMAIL_MESSAGE\"})\n",
- "def callback_new_message(event) -> None:\n",
- " # Get the payload and extract relevant information\n",
- " payload = event.payload # Email payload\n",
- " thread_id = payload.get(\"threadId\")\n",
- " message = payload.get(\"messageText\")\n",
- " sender_mail = payload.get(\"sender\")\n",
- " if sender_mail is None:\n",
- " print(\"No sender email found\")\n",
- " return\n",
- "\n",
- " analyze_email_task = f\"\"\"\n",
- " Analyze the email content and create an appropriate reply.\n",
- " a. The email was received from {sender_mail}\n",
- " b. The content of the email is: {message}\n",
- " c. The thread id is: {thread_id}.\n",
- " \"\"\"\n",
- " # Initiate the conversation\n",
- " res = user_proxy.initiate_chat(chatbot, message=analyze_email_task)\n",
- " print(res.summary)\n",
- "\n",
- "\n",
- "print(\"Subscribed to triggers!\")\n",
- "# Start listening\n",
- "listener.listen()"
- ]
- }
- ],
- "metadata": {
- "colab": {
- "provenance": []
- },
- "front_matter": {
- "description": "Use Composio to create AI agents that seamlessly connect with external tools, Apps, and APIs to perform actions and receive triggers. With built-in support for AutoGen, Composio enables the creation of highly capable and adaptable AI agents that can autonomously execute complex tasks and deliver personalized experiences.",
- "tags": [
- "agents",
- "tool use"
- ]
- },
- "kernelspec": {
- "display_name": "Python 3",
- "name": "python3"
- },
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 0
-}
diff --git a/test/oai/test_cerebras.py b/test/oai/test_cerebras.py
deleted file mode 100644
index 7f84ae3f9..000000000
--- a/test/oai/test_cerebras.py
+++ /dev/null
@@ -1,248 +0,0 @@
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-try:
- from autogen.oai.cerebras import CerebrasClient, calculate_cerebras_cost
-
- skip = False
-except ImportError:
- CerebrasClient = object
- InternalServerError = object
- skip = True
-
-
-# Fixtures for mock data
-def mock_response():
- class MockResponse:
- def __init__(self, text, choices, usage, cost, model):
- self.text = text
- self.choices = choices
- self.usage = usage
- self.cost = cost
- self.model = model
-
- return MockResponse
-
-
-def cerebras_client():
- return CerebrasClient(api_key="fake_api_key")
-
-
-skip_reason = "Cerebras dependency is not installed"
-
-
-# Test initialization and configuration
[email protected](skip, reason=skip_reason)
-def test_initialization():
-
- # Missing any api_key
- with pytest.raises(AssertionError) as assertinfo:
- CerebrasClient() # Should raise an AssertionError due to missing api_key
-
- assert (
- "Please include the api_key in your config list entry for Cerebras or set the CEREBRAS_API_KEY env variable."
- in str(assertinfo.value)
- )
-
- # Creation works
- CerebrasClient(api_key="fake_api_key") # Should create okay now.
-
-
-# Test standard initialization
[email protected](skip, reason=skip_reason)
-def test_valid_initialization(cerebras_client):
- assert cerebras_client.api_key == "fake_api_key", "Config api_key should be correctly set"
-
-
-# Test parameters
[email protected](skip, reason=skip_reason)
-def test_parsing_params(cerebras_client):
- # All parameters
- params = {
- "model": "llama3.1-8b",
- "max_tokens": 1000,
- "seed": 42,
- "stream": False,
- "temperature": 1,
- "top_p": 0.8,
- }
- expected_params = {
- "model": "llama3.1-8b",
- "max_tokens": 1000,
- "seed": 42,
- "stream": False,
- "temperature": 1,
- "top_p": 0.8,
- }
- result = cerebras_client.parse_params(params)
- assert result == expected_params
-
- # Only model, others set as defaults
- params = {
- "model": "llama3.1-8b",
- }
- expected_params = {
- "model": "llama3.1-8b",
- "max_tokens": None,
- "seed": None,
- "stream": False,
- "temperature": 1,
- "top_p": None,
- }
- result = cerebras_client.parse_params(params)
- assert result == expected_params
-
- # Incorrect types, defaults should be set, will show warnings but not trigger assertions
- params = {
- "model": "llama3.1-8b",
- "max_tokens": "1000",
- "seed": "42",
- "stream": "False",
- "temperature": "1",
- "top_p": "0.8",
- }
- result = cerebras_client.parse_params(params)
- assert result == expected_params
-
- # Values outside bounds, should warn and set to defaults
- params = {
- "model": "llama3.1-8b",
- "temperature": 33123,
- }
- result = cerebras_client.parse_params(params)
- assert result == expected_params
-
- # No model
- params = {
- "temperature": 1,
- }
-
- with pytest.raises(AssertionError) as assertinfo:
- result = cerebras_client.parse_params(params)
-
- assert "Please specify the 'model' in your config list entry to nominate the Cerebras model to use." in str(
- assertinfo.value
- )
-
-
-# Test cost calculation
[email protected](skip, reason=skip_reason)
-def test_cost_calculation(mock_response):
- response = mock_response(
- text="Example response",
- choices=[{"message": "Test message 1"}],
- usage={"prompt_tokens": 500, "completion_tokens": 300, "total_tokens": 800},
- cost=None,
- model="llama3.1-70b",
- )
- calculated_cost = calculate_cerebras_cost(
- response.usage["prompt_tokens"], response.usage["completion_tokens"], response.model
- )
-
- # Convert cost per milliion to cost per token.
- expected_cost = (
- response.usage["prompt_tokens"] * 0.6 / 1000000 + response.usage["completion_tokens"] * 0.6 / 1000000
- )
-
- assert calculated_cost == expected_cost, f"Cost for this should be ${expected_cost} but got ${calculated_cost}"
-
-
-# Test text generation
[email protected](skip, reason=skip_reason)
-@patch("autogen.oai.cerebras.CerebrasClient.create")
-def test_create_response(mock_chat, cerebras_client):
- # Mock CerebrasClient.chat response
- mock_cerebras_response = MagicMock()
- mock_cerebras_response.choices = [
- MagicMock(finish_reason="stop", message=MagicMock(content="Example Cerebras response", tool_calls=None))
- ]
- mock_cerebras_response.id = "mock_cerebras_response_id"
- mock_cerebras_response.model = "llama3.1-70b"
- mock_cerebras_response.usage = MagicMock(prompt_tokens=10, completion_tokens=20) # Example token usage
-
- mock_chat.return_value = mock_cerebras_response
-
- # Test parameters
- params = {
- "messages": [{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "World"}],
- "model": "llama3.1-70b",
- }
-
- # Call the create method
- response = cerebras_client.create(params)
-
- # Assertions to check if response is structured as expected
- assert (
- response.choices[0].message.content == "Example Cerebras response"
- ), "Response content should match expected output"
- assert response.id == "mock_cerebras_response_id", "Response ID should match the mocked response ID"
- assert response.model == "llama3.1-70b", "Response model should match the mocked response model"
- assert response.usage.prompt_tokens == 10, "Response prompt tokens should match the mocked response usage"
- assert response.usage.completion_tokens == 20, "Response completion tokens should match the mocked response usage"
-
-
-# Test functions/tools
[email protected](skip, reason=skip_reason)
-@patch("autogen.oai.cerebras.CerebrasClient.create")
-def test_create_response_with_tool_call(mock_chat, cerebras_client):
- # Mock `cerebras_response = client.chat(**cerebras_params)`
- mock_function = MagicMock(name="currency_calculator")
- mock_function.name = "currency_calculator"
- mock_function.arguments = '{"base_currency": "EUR", "quote_currency": "USD", "base_amount": 123.45}'
-
- mock_function_2 = MagicMock(name="get_weather")
- mock_function_2.name = "get_weather"
- mock_function_2.arguments = '{"location": "Chicago"}'
-
- mock_chat.return_value = MagicMock(
- choices=[
- MagicMock(
- finish_reason="tool_calls",
- message=MagicMock(
- content="Sample text about the functions",
- tool_calls=[
- MagicMock(id="gdRdrvnHh", function=mock_function),
- MagicMock(id="abRdrvnHh", function=mock_function_2),
- ],
- ),
- )
- ],
- id="mock_cerebras_response_id",
- model="llama3.1-70b",
- usage=MagicMock(prompt_tokens=10, completion_tokens=20),
- )
-
- # Construct parameters
- converted_functions = [
- {
- "type": "function",
- "function": {
- "description": "Currency exchange calculator.",
- "name": "currency_calculator",
- "parameters": {
- "type": "object",
- "properties": {
- "base_amount": {"type": "number", "description": "Amount of currency in base_currency"},
- },
- "required": ["base_amount"],
- },
- },
- }
- ]
- cerebras_messages = [
- {"role": "user", "content": "How much is 123.45 EUR in USD?"},
- {"role": "assistant", "content": "World"},
- ]
-
- # Call the create method
- response = cerebras_client.create(
- {"messages": cerebras_messages, "tools": converted_functions, "model": "llama3.1-70b"}
- )
-
- # Assertions to check if the functions and content are included in the response
- assert response.choices[0].message.content == "Sample text about the functions"
- assert response.choices[0].message.tool_calls[0].function.name == "currency_calculator"
- assert response.choices[0].message.tool_calls[1].function.name == "get_weather"
diff --git a/test/oai/test_ollama.py b/test/oai/test_ollama.py
deleted file mode 100644
index 5491a04d7..000000000
--- a/test/oai/test_ollama.py
+++ /dev/null
@@ -1,302 +0,0 @@
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-try:
- from autogen.oai.ollama import OllamaClient, response_to_tool_call
-
- skip = False
-except ImportError:
- OllamaClient = object
- InternalServerError = object
- skip = True
-
-
-# Fixtures for mock data
-def mock_response():
- class MockResponse:
- def __init__(self, text, choices, usage, cost, model):
- self.text = text
- self.choices = choices
- self.usage = usage
- self.cost = cost
- self.model = model
-
- return MockResponse
-
-
-def ollama_client():
-
- # Set Ollama client with some default values
- client = OllamaClient()
-
- client._native_tool_calls = True
- client._tools_in_conversation = False
-
- return client
-
-
-skip_reason = "Ollama dependency is not installed"
-
-
-# Test initialization and configuration
[email protected](skip, reason=skip_reason)
-def test_initialization():
-
- # Creation works without an api_key
- OllamaClient()
-
-
-# Test parameters
[email protected](skip, reason=skip_reason)
-def test_parsing_params(ollama_client):
- # All parameters (with default values)
- params = {
- "model": "llama3.1:8b",
- "temperature": 0.8,
- "num_predict": 128,
- "repeat_penalty": 1.1,
- "seed": 42,
- "top_k": 40,
- "top_p": 0.9,
- "stream": False,
- }
- expected_params = {
- "model": "llama3.1:8b",
- "options": {
- "repeat_penalty": 1.1,
- "seed": 42,
- "temperature": 0.8,
- "num_predict": 128,
- "top_k": 40,
- "top_p": 0.9,
- },
- "stream": False,
- }
- result = ollama_client.parse_params(params)
- assert result == expected_params
-
- # Incorrect types, defaults should be set, will show warnings but not trigger assertions
- params = {
- "model": "llama3.1:8b",
- "temperature": "0.5",
- "num_predict": "128",
- "repeat_penalty": "1.1",
- "seed": "42",
- "top_k": "40",
- "top_p": "0.9",
- "stream": "True",
- }
- result = ollama_client.parse_params(params)
- assert result == expected_params
-
- # Only model, others set as defaults if they are mandatory
- params = {
- "model": "llama3.1:8b",
- }
- expected_params = {"model": "llama3.1:8b", "stream": False}
- result = ollama_client.parse_params(params)
- assert result == expected_params
-
- # No model
- params = {
- "temperature": 0.8,
- }
-
- with pytest.raises(AssertionError) as assertinfo:
- result = ollama_client.parse_params(params)
-
- assert "Please specify the 'model' in your config list entry to nominate the Ollama model to use." in str(
- assertinfo.value
- )
-
-
-# Test text generation
[email protected](skip, reason=skip_reason)
-@patch("autogen.oai.ollama.OllamaClient.create")
-def test_create_response(mock_chat, ollama_client):
- # Mock OllamaClient.chat response
- mock_ollama_response = MagicMock()
- mock_ollama_response.choices = [
- MagicMock(finish_reason="stop", message=MagicMock(content="Example Ollama response", tool_calls=None))
- ]
- mock_ollama_response.id = "mock_ollama_response_id"
- mock_ollama_response.model = "llama3.1:8b"
- mock_ollama_response.usage = MagicMock(prompt_tokens=10, completion_tokens=20) # Example token usage
-
- mock_chat.return_value = mock_ollama_response
-
- # Test parameters
- params = {
- "messages": [{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "World"}],
- "model": "llama3.1:8b",
- }
-
- # Call the create method
- response = ollama_client.create(params)
-
- # Assertions to check if response is structured as expected
- assert (
- response.choices[0].message.content == "Example Ollama response"
- ), "Response content should match expected output"
- assert response.id == "mock_ollama_response_id", "Response ID should match the mocked response ID"
- assert response.model == "llama3.1:8b", "Response model should match the mocked response model"
- assert response.usage.prompt_tokens == 10, "Response prompt tokens should match the mocked response usage"
- assert response.usage.completion_tokens == 20, "Response completion tokens should match the mocked response usage"
-
-
-# Test functions/tools
[email protected](skip, reason=skip_reason)
-@patch("autogen.oai.ollama.OllamaClient.create")
-def test_create_response_with_tool_call(mock_chat, ollama_client):
- # Mock OllamaClient.chat response
- mock_function = MagicMock(name="currency_calculator")
- mock_function.name = "currency_calculator"
- mock_function.arguments = '{"base_currency": "EUR", "quote_currency": "USD", "base_amount": 123.45}'
-
- mock_function_2 = MagicMock(name="get_weather")
- mock_function_2.name = "get_weather"
- mock_function_2.arguments = '{"location": "New York"}'
-
- mock_chat.return_value = MagicMock(
- choices=[
- MagicMock(
- finish_reason="tool_calls",
- message=MagicMock(
- content="Sample text about the functions",
- tool_calls=[
- MagicMock(id="gdRdrvnHh", function=mock_function),
- MagicMock(id="abRdrvnHh", function=mock_function_2),
- ],
- ),
- )
- ],
- id="mock_ollama_response_id",
- model="llama3.1:8b",
- usage=MagicMock(prompt_tokens=10, completion_tokens=20),
- )
-
- # Construct parameters
- converted_functions = [
- {
- "type": "function",
- "function": {
- "description": "Currency exchange calculator.",
- "name": "currency_calculator",
- "parameters": {
- "type": "object",
- "properties": {
- "base_amount": {"type": "number", "description": "Amount of currency in base_currency"},
- },
- "required": ["base_amount"],
- },
- },
- }
- ]
- ollama_messages = [
- {"role": "user", "content": "How much is 123.45 EUR in USD?"},
- {"role": "assistant", "content": "World"},
- ]
-
- # Call the create method
- response = ollama_client.create({"messages": ollama_messages, "tools": converted_functions, "model": "llama3.1:8b"})
-
- # Assertions to check if the functions and content are included in the response
- assert response.choices[0].message.content == "Sample text about the functions"
- assert response.choices[0].message.tool_calls[0].function.name == "currency_calculator"
- assert response.choices[0].message.tool_calls[1].function.name == "get_weather"
-
-
-# Test function parsing with manual tool calling
[email protected](skip, reason=skip_reason)
-def test_manual_tool_calling_parsing(ollama_client):
- # Test the parsing of a tool call within the response content (fully correct)
- response_content = """[{"name": "weather_forecast", "arguments":{"location": "New York"}},{"name": "currency_calculator", "arguments":{"base_amount": 123.45, "quote_currency": "EUR", "base_currency": "USD"}}]"""
-
- response_tool_calls = response_to_tool_call(response_content)
-
- expected_tool_calls = [
- {"name": "weather_forecast", "arguments": {"location": "New York"}},
- {
- "name": "currency_calculator",
- "arguments": {"base_amount": 123.45, "quote_currency": "EUR", "base_currency": "USD"},
- },
- ]
-
- assert (
- response_tool_calls == expected_tool_calls
- ), "Manual Tool Calling Parsing of response did not yield correct tool_calls (full string match)"
-
- # Test the parsing with a substring containing the response content (should still pass)
- response_content = """I will call two functions, weather_forecast and currency_calculator:\n[{"name": "weather_forecast", "arguments":{"location": "New York"}},{"name": "currency_calculator", "arguments":{"base_amount": 123.45, "quote_currency": "EUR", "base_currency": "USD"}}]"""
-
- response_tool_calls = response_to_tool_call(response_content)
-
- assert (
- response_tool_calls == expected_tool_calls
- ), "Manual Tool Calling Parsing of response did not yield correct tool_calls (partial string match)"
-
- # Test the parsing with an invalid function call
- response_content = """[{"function": "weather_forecast", "args":{"location": "New York"}},{"function": "currency_calculator", "args":{"base_amount": 123.45, "quote_currency": "EUR", "base_currency": "USD"}}]"""
-
- response_tool_calls = response_to_tool_call(response_content)
-
- assert (
- response_tool_calls is None
- ), "Manual Tool Calling Parsing of response did not yield correct tool_calls (invalid function call)"
-
- # Test the parsing with plain text
- response_content = """Call the weather_forecast function and pass in 'New York' as the 'location' argument."""
-
- response_tool_calls = response_to_tool_call(response_content)
-
- assert (
- response_tool_calls is None
- ), "Manual Tool Calling Parsing of response did not yield correct tool_calls (no function in text)"
-
-
-# Test message conversion from OpenAI to Ollama format
[email protected](skip, reason=skip_reason)
-def test_oai_messages_to_ollama_messages(ollama_client):
- # Test that the "name" key is removed
- test_messages = [
- {"role": "system", "content": "You are a helpful AI bot."},
- {"role": "user", "name": "anne", "content": "Why is the sky blue?"},
- ]
- messages = ollama_client.oai_messages_to_ollama_messages(test_messages, None)
-
- expected_messages = [
- {"role": "system", "content": "You are a helpful AI bot."},
- {"role": "user", "content": "Why is the sky blue?"},
- ]
-
- assert messages == expected_messages, "'name' was not removed from messages"
-
- # Test that there isn't a final system message and it's changed to user
- test_messages.append({"role": "system", "content": "Summarise the conversation."})
-
- messages = ollama_client.oai_messages_to_ollama_messages(test_messages, None)
-
- expected_messages = [
- {"role": "system", "content": "You are a helpful AI bot."},
- {"role": "user", "content": "Why is the sky blue?"},
- {"role": "user", "content": "Summarise the conversation."},
- ]
-
- assert messages == expected_messages, "Final 'system' message was not changed to 'user'"
-
- # Test that the last message is a user or system message and if not, add a continue message
- test_messages[2] = {"role": "assistant", "content": "The sky is blue because that's a great colour."}
-
- messages = ollama_client.oai_messages_to_ollama_messages(test_messages, None)
-
- expected_messages = [
- {"role": "system", "content": "You are a helpful AI bot."},
- {"role": "user", "content": "Why is the sky blue?"},
- {"role": "assistant", "content": "The sky is blue because that's a great colour."},
- {"role": "user", "content": "Please continue."},
- ]
-
- assert messages == expected_messages, "'Please continue' message was not appended."
diff --git a/website/blog/2024-10-02-new-autogen-architecture-preview/img/robots.jpeg b/website/blog/2024-10-02-new-autogen-architecture-preview/img/robots.jpeg
deleted file mode 100644
index 5ec1aba78..000000000
--- a/website/blog/2024-10-02-new-autogen-architecture-preview/img/robots.jpeg
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:daf14746d10ed67ab9de1f50c241827342e523fdb5bd08af8dc5a0fee5a8d37e
-size 52503
diff --git a/website/blog/2024-10-02-new-autogen-architecture-preview/index.mdx b/website/blog/2024-10-02-new-autogen-architecture-preview/index.mdx
deleted file mode 100644
index 3b13ac514..000000000
--- a/website/blog/2024-10-02-new-autogen-architecture-preview/index.mdx
+++ /dev/null
@@ -1,103 +0,0 @@
----
-title: New AutoGen Architecture Preview
-authors:
- - autogen-team
-tags: [AutoGen]
----
-
-# New AutoGen Architecture Preview
-
-<center>
-
-![What are they doing?](img/robots.jpeg)
-
-</center>
-
-One year ago, we launched AutoGen, a programming framework designed to build
-agentic AI systems. The release of AutoGen sparked massive interest within the
-developer community. As an early release, it provided us with a unique
-opportunity to engage deeply with users, gather invaluable feedback, and learn
-from a diverse range of use cases and contributions. By listening and engaging
-with the community, we gained insights into what people were building or
-attempting to build, how they were approaching the creation of agentic systems,
-and where they were struggling. This experience was both humbling and
-enlightening, revealing significant opportunities for improvement in our initial
-design, especially for power users developing production-level applications with
-AutoGen.
-
-Through engagements with the community, we learned many lessons:
-
-- Developers value modular and reusable agents. For example, our built-in agents
- that could be directly plugged in or easily customized for specific use cases
- were particularly popular. At the same time, there was a desire for more
- customizability, such as integrating custom agents built using other
- programming languages or frameworks.
-- Chat-based agent-to-agent communication was an intuitive collaboration
- pattern, making it easy for developers to get started and involve humans in
- the loop. As developers began to employ agents in a wider range of scenarios,
- they sought more flexibility in collaboration patterns. For instance,
- developers wanted to build predictable, ordered workflows with agents, and to
- integrate them with new user interfaces that are not chat-based.
-- Although it was easy for developers to get started with AutoGen, debugging and
- scaling agent teams applications proved more challenging.
-- There were many opportunities for improving code quality.
-
-These learnings, along with many others from other agentic efforts across
-Microsoft, prompted us to take a step back and lay the groundwork for a new
-direction. A few months ago, we started dedicating time to distilling these
-learnings into a roadmap for the future of AutoGen. This led to the development
-of AutoGen 0.4, a complete redesign of the framework from the foundation up.
-AutoGen 0.4 embraces the actor model of computing to support distributed, highly
-scalable, event-driven agentic systems. This approach offers many advantages,
-such as:
-
-- **Composability**. Systems designed in this way are more composable, allowing
- developers to bring their own agents implemented in different frameworks or
- programming languages and to build more powerful systems using complex agentic
- patterns.
-- **Flexibility**. It allows for the creation of both deterministic, ordered
- workflows and event-driven or decentralized workflows, enabling customers to
- bring their own orchestration or integrate with other systems more easily. It
- also opens more opportunities for human-in-the-loop scenarios, both active and
- reactive.
-- **Debugging and Observability**. Event-driven communication moves message delivery
- away from agents to a centralized component, making it easier to observe and
- debug their activities regardless of agent implementation.
-- **Scalability**. An event-based architecture enables distributed and
- cloud-deployed agents, which is essential for building scalable AI services
- and applications.
-
-Today, we are delighted to share our progress and invite everyone to collaborate
-with us and provide feedback to evolve AutoGen and help shape the future of
-multi-agent systems.
-
-As the first step, we are opening a [pull request](#) into the main branch with the
-current state of development of 0.4. After approximately a week, we plan to
-merge this into main and continue development. There's still a lot left to do
-before 0.4 is ready for release though, so keep in mind this is a work in
-progress.
-
-Starting in AutoGen 0.4, the project will have three main libraries:
-
-- **Core** - the building blocks for an event-driven agentic system.
-- **AgentChat** - a task-driven, high-level API built with core, including group
- chat, code execution, pre-built agents, and more. This is the most similar API
- to AutoGen 0.2 and will be the easiest API to migrate to.
-- **Extensions** - implementations of core interfaces and third-party integrations
- (e.g., Azure code executor and OpenAI model client).
-
-AutoGen 0.2 is still available, developed and maintained out of the [0.2 branch](https://github.com/microsoft/autogen/tree/0.2).
-For everyone looking for a stable version, we recommend continuing to use 0.2
-for the time being. It can be installed using:
-
-```sh
-pip install autogen-agentchat~=0.2
-```
-
-This new package name was used to align with the new packages that will come with 0.4:
-`autogen-core`, `autogen-agentchat`, and `autogen-ext`.
-
-Lastly, we will be using [GitHub
-Discussion](https://github.com/microsoft/autogen/discussions) as the official
-community forum for the new version and, going forward, all discussions related
-to the AutoGen project. We look forward to meeting you there.
diff --git a/website/docs/topics/non-openai-models/cloud-cerebras.ipynb b/website/docs/topics/non-openai-models/cloud-cerebras.ipynb
deleted file mode 100644
index 71cb9da44..000000000
--- a/website/docs/topics/non-openai-models/cloud-cerebras.ipynb
+++ /dev/null
@@ -1,505 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Cerebras\n",
- "\n",
- "[Cerebras](https://cerebras.ai) has developed the world's largest and fastest AI processor, the Wafer-Scale Engine-3 (WSE-3). Notably, the CS-3 system can run large language models like Llama-3.1-8B and Llama-3.1-70B at extremely fast speeds, making it an ideal platform for demanding AI workloads.\n",
- "\n",
- "While it's technically possible to adapt AutoGen to work with Cerebras' API by updating the `base_url`, this approach may not fully account for minor differences in parameter support. Using this library will also allow for tracking of the API costs based on actual token usage.\n",
- "\n",
- "For more information about Cerebras Cloud, visit [cloud.cerebras.ai](https://cloud.cerebras.ai). Their API reference is available at [inference-docs.cerebras.ai](https://inference-docs.cerebras.ai)."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Requirements\n",
- "To use Cerebras with AutoGen, install the `autogen-agentchat[cerebras]` package."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "!pip install autogen-agentchat[\"cerebras\"]~=0.2"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Getting Started\n",
- "\n",
- "Cerebras provides a number of models to use. See the list of [models here](https://inference-docs.cerebras.ai/introduction).\n",
- "\n",
- "See the sample `OAI_CONFIG_LIST` below showing how the Cerebras client class is used by specifying the `api_type` as `cerebras`.\n",
- "```python\n",
- "[\n",
- " {\n",
- " \"model\": \"llama3.1-8b\",\n",
- " \"api_key\": \"your Cerebras API Key goes here\",\n",
- " \"api_type\": \"cerebras\"\n",
- " },\n",
- " {\n",
- " \"model\": \"llama3.1-70b\",\n",
- " \"api_key\": \"your Cerebras API Key goes here\",\n",
- " \"api_type\": \"cerebras\"\n",
- " }\n",
- "]\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Credentials\n",
- "\n",
- "Get an API Key from [cloud.cerebras.ai](https://cloud.cerebras.ai/) and add it to your environment variables:\n",
- "\n",
- "```\n",
- "export CEREBRAS_API_KEY=\"your-api-key-here\"\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## API parameters\n",
- "\n",
- "The following parameters can be added to your config for the Cerebras API. See [this link](https://inference-docs.cerebras.ai/api-reference/chat-completions) for further information on them and their default values.\n",
- "\n",
- "- max_tokens (null, integer >= 0)\n",
- "- seed (number)\n",
- "- stream (True or False)\n",
- "- temperature (number 0..1.5)\n",
- "- top_p (number)\n",
- "\n",
- "Example:\n",
- "```python\n",
- "[\n",
- " {\n",
- " \"model\": \"llama3.1-70b\",\n",
- " \"api_key\": \"your Cerebras API Key goes here\",\n",
- " \"api_type\": \"cerebras\"\n",
- " \"max_tokens\": 10000,\n",
- " \"seed\": 1234,\n",
- " \"stream\" True,\n",
- " \"temperature\": 0.5,\n",
- " \"top_p\": 0.2, # Note: It is recommended to set temperature or top_p but not both.\n",
- " }\n",
- "]\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Two-Agent Coding Example\n",
- "\n",
- "In this example, we run a two-agent chat with an AssistantAgent (primarily a coding agent) to generate code to count the number of prime numbers between 1 and 10,000 and then it will be executed.\n",
- "\n",
- "We'll use Meta's LLama-3.1-70B model which is suitable for coding."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 32,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "\n",
- "from autogen.oai.cerebras import CerebrasClient, calculate_cerebras_cost\n",
- "\n",
- "config_list = [{\"model\": \"llama3.1-70b\", \"api_key\": os.environ.get(\"CEREBRAS_API_KEY\"), \"api_type\": \"cerebras\"}]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Importantly, we have tweaked the system message so that the model doesn't return the termination keyword, which we've changed to FINISH, with the code block."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 33,
- "metadata": {},
- "outputs": [],
- "source": [
- "from pathlib import Path\n",
- "\n",
- "from autogen import AssistantAgent, UserProxyAgent\n",
- "from autogen.coding import LocalCommandLineCodeExecutor\n",
- "\n",
- "# Setting up the code executor\n",
- "workdir = Path(\"coding\")\n",
- "workdir.mkdir(exist_ok=True)\n",
- "code_executor = LocalCommandLineCodeExecutor(work_dir=workdir)\n",
- "\n",
- "# Setting up the agents\n",
- "\n",
- "# The UserProxyAgent will execute the code that the AssistantAgent provides\n",
- "user_proxy_agent = UserProxyAgent(\n",
- " name=\"User\",\n",
- " code_execution_config={\"executor\": code_executor},\n",
- " is_termination_msg=lambda msg: \"FINISH\" in msg.get(\"content\"),\n",
- ")\n",
- "\n",
- "system_message = \"\"\"You are a helpful AI assistant who writes code and the user executes it.\n",
- "Solve tasks using your coding and language skills.\n",
- "In the following cases, suggest python code (in a python coding block) for the user to execute.\n",
- "Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill.\n",
- "When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user.\n",
- "Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.\n",
- "If the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try.\n",
- "When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible.\n",
- "IMPORTANT: Wait for the user to execute your code and then you can reply with the word \"FINISH\". DO NOT OUTPUT \"FINISH\" after your code block.\"\"\"\n",
- "\n",
- "# The AssistantAgent, using Llama-3.1-70B on Cerebras Inference, will take the coding request and return code\n",
- "assistant_agent = AssistantAgent(\n",
- " name=\"Cerebras Assistant\",\n",
- " system_message=system_message,\n",
- " llm_config={\"config_list\": config_list},\n",
- ")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 35,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u001b[33mUser\u001b[0m (to Cerebras Assistant):\n",
- "\n",
- "Provide code to count the number of prime numbers from 1 to 10000.\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33mCerebras Assistant\u001b[0m (to User):\n",
- "\n",
- "To count the number of prime numbers from 1 to 10000, we will utilize a simple algorithm that checks each number in the range to see if it is prime. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n",
- "\n",
- "Here's how we can do it using a Python script:\n",
- "\n",
- "```python\n",
- "def count_primes(n):\n",
- " primes = 0\n",
- " for possiblePrime in range(2, n + 1):\n",
- " # Assume number is prime until shown it is not. \n",
- " isPrime = True\n",
- " for num in range(2, int(possiblePrime ** 0.5) + 1):\n",
- " if possiblePrime % num == 0:\n",
- " isPrime = False\n",
- " break\n",
- " if isPrime:\n",
- " primes += 1\n",
- " return primes\n",
- "\n",
- "# Counting prime numbers from 1 to 10000\n",
- "count = count_primes(10000)\n",
- "print(count)\n",
- "```\n",
- "\n",
- "Please execute this code. I will respond with \"FINISH\" after you provide the result.\n",
- "\n",
- "--------------------------------------------------------------------------------\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Replying as User. Provide feedback to Cerebras Assistant. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: \n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u001b[31m\n",
- ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n"
- ]
- }
- ],
- "source": [
- "# Start the chat, with the UserProxyAgent asking the AssistantAgent the message\n",
- "chat_result = user_proxy_agent.initiate_chat(\n",
- " assistant_agent,\n",
- " message=\"Provide code to count the number of prime numbers from 1 to 10000.\",\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Tool Call Example\n",
- "\n",
- "In this example, instead of writing code, we will show how Meta's Llama-3.1-70B model can perform parallel tool calling, where it recommends calling more than one tool at a time.\n",
- "\n",
- "We'll use a simple travel agent assistant program where we have a couple of tools for weather and currency conversion.\n",
- "\n",
- "We start by importing libraries and setting up our configuration to use Llama-3.1-70B and the `cerebras` client class."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 36,
- "metadata": {},
- "outputs": [],
- "source": [
- "import json\n",
- "import os\n",
- "from typing import Literal\n",
- "\n",
- "from typing_extensions import Annotated\n",
- "\n",
- "import autogen\n",
- "\n",
- "config_list = [\n",
- " {\n",
- " \"model\": \"llama3.1-70b\",\n",
- " \"api_key\": os.environ.get(\"CEREBRAS_API_KEY\"),\n",
- " \"api_type\": \"cerebras\",\n",
- " }\n",
- "]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Create our two agents."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 43,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Create the agent for tool calling\n",
- "chatbot = autogen.AssistantAgent(\n",
- " name=\"chatbot\",\n",
- " system_message=\"\"\"\n",
- " For currency exchange and weather forecasting tasks,\n",
- " only use the functions you have been provided with.\n",
- " When you summarize, make sure you've considered ALL previous instructions.\n",
- " Output 'HAVE FUN!' when an answer has been provided.\n",
- " \"\"\",\n",
- " llm_config={\"config_list\": config_list},\n",
- ")\n",
- "\n",
- "# Note that we have changed the termination string to be \"HAVE FUN!\"\n",
- "user_proxy = autogen.UserProxyAgent(\n",
- " name=\"user_proxy\",\n",
- " is_termination_msg=lambda x: x.get(\"content\", \"\") and \"HAVE FUN!\" in x.get(\"content\", \"\"),\n",
- " human_input_mode=\"NEVER\",\n",
- " max_consecutive_auto_reply=1,\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Create the two functions, annotating them so that those descriptions can be passed through to the LLM.\n",
- "\n",
- "We associate them with the agents using `register_for_execution` for the user_proxy so it can execute the function and `register_for_llm` for the chatbot (powered by the LLM) so it can pass the function definitions to the LLM."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 44,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Currency Exchange function\n",
- "\n",
- "CurrencySymbol = Literal[\"USD\", \"EUR\"]\n",
- "\n",
- "# Define our function that we expect to call\n",
- "\n",
- "\n",
- "def exchange_rate(base_currency: CurrencySymbol, quote_currency: CurrencySymbol) -> float:\n",
- " if base_currency == quote_currency:\n",
- " return 1.0\n",
- " elif base_currency == \"USD\" and quote_currency == \"EUR\":\n",
- " return 1 / 1.1\n",
- " elif base_currency == \"EUR\" and quote_currency == \"USD\":\n",
- " return 1.1\n",
- " else:\n",
- " raise ValueError(f\"Unknown currencies {base_currency}, {quote_currency}\")\n",
- "\n",
- "\n",
- "# Register the function with the agent\n",
- "\n",
- "\n",
- "@user_proxy.register_for_execution()\n",
- "@chatbot.register_for_llm(description=\"Currency exchange calculator.\")\n",
- "def currency_calculator(\n",
- " base_amount: Annotated[float, \"Amount of currency in base_currency\"],\n",
- " base_currency: Annotated[CurrencySymbol, \"Base currency\"] = \"USD\",\n",
- " quote_currency: Annotated[CurrencySymbol, \"Quote currency\"] = \"EUR\",\n",
- ") -> str:\n",
- " quote_amount = exchange_rate(base_currency, quote_currency) * base_amount\n",
- " return f\"{format(quote_amount, '.2f')} {quote_currency}\"\n",
- "\n",
- "\n",
- "# Weather function\n",
- "\n",
- "\n",
- "# Example function to make available to model\n",
- "def get_current_weather(location, unit=\"fahrenheit\"):\n",
- " \"\"\"Get the weather for some location\"\"\"\n",
- " if \"chicago\" in location.lower():\n",
- " return json.dumps({\"location\": \"Chicago\", \"temperature\": \"13\", \"unit\": unit})\n",
- " elif \"san francisco\" in location.lower():\n",
- " return json.dumps({\"location\": \"San Francisco\", \"temperature\": \"55\", \"unit\": unit})\n",
- " elif \"new york\" in location.lower():\n",
- " return json.dumps({\"location\": \"New York\", \"temperature\": \"11\", \"unit\": unit})\n",
- " else:\n",
- " return json.dumps({\"location\": location, \"temperature\": \"unknown\"})\n",
- "\n",
- "\n",
- "# Register the function with the agent\n",
- "\n",
- "\n",
- "@user_proxy.register_for_execution()\n",
- "@chatbot.register_for_llm(description=\"Weather forecast for US cities.\")\n",
- "def weather_forecast(\n",
- " location: Annotated[str, \"City name\"],\n",
- ") -> str:\n",
- " weather_details = get_current_weather(location=location)\n",
- " weather = json.loads(weather_details)\n",
- " return f\"{weather['location']} will be {weather['temperature']} degrees {weather['unit']}\""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We pass through our customer's message and run the chat.\n",
- "\n",
- "Finally, we ask the LLM to summarise the chat and print that out."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 45,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
- "\n",
- "What's the weather in New York and can you tell me how much is 123.45 EUR in USD so I can spend it on my holiday? Throw a few holiday tips in as well.\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
- "\n",
- "\u001b[32m***** Suggested tool call (210f6ac6d): weather_forecast *****\u001b[0m\n",
- "Arguments: \n",
- "{\"location\": \"New York\"}\n",
- "\u001b[32m*************************************************************\u001b[0m\n",
- "\u001b[32m***** Suggested tool call (3c00ac7d5): currency_calculator *****\u001b[0m\n",
- "Arguments: \n",
- "{\"base_amount\": 123.45, \"base_currency\": \"EUR\", \"quote_currency\": \"USD\"}\n",
- "\u001b[32m****************************************************************\u001b[0m\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[35m\n",
- ">>>>>>>> EXECUTING FUNCTION weather_forecast...\u001b[0m\n",
- "\u001b[35m\n",
- ">>>>>>>> EXECUTING FUNCTION currency_calculator...\u001b[0m\n",
- "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
- "\n",
- "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
- "\n",
- "\u001b[32m***** Response from calling tool (210f6ac6d) *****\u001b[0m\n",
- "New York will be 11 degrees fahrenheit\n",
- "\u001b[32m**************************************************\u001b[0m\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
- "\n",
- "\u001b[32m***** Response from calling tool (3c00ac7d5) *****\u001b[0m\n",
- "135.80 USD\n",
- "\u001b[32m**************************************************\u001b[0m\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
- "\n",
- "New York will be 11 degrees fahrenheit.\n",
- "123.45 EUR is equivalent to 135.80 USD.\n",
- " \n",
- "For a great holiday, explore the Statue of Liberty, take a walk through Central Park, or visit one of the many world-class museums. Also, you'll find great food ranging from bagels to fine dining experiences. HAVE FUN!\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "LLM SUMMARY: New York will be 11 degrees fahrenheit. 123.45 EUR is equivalent to 135.80 USD. Explore the Statue of Liberty, walk through Central Park, or visit one of the many world-class museums for a great holiday in New York.\n",
- "\n",
- "Duration: 73.97937774658203ms\n"
- ]
- }
- ],
- "source": [
- "import time\n",
- "\n",
- "start_time = time.time()\n",
- "\n",
- "# start the conversation\n",
- "res = user_proxy.initiate_chat(\n",
- " chatbot,\n",
- " message=\"What's the weather in New York and can you tell me how much is 123.45 EUR in USD so I can spend it on my holiday? Throw a few holiday tips in as well.\",\n",
- " summary_method=\"reflection_with_llm\",\n",
- ")\n",
- "\n",
- "end_time = time.time()\n",
- "\n",
- "print(f\"LLM SUMMARY: {res.summary['content']}\\n\\nDuration: {(end_time - start_time) * 1000}ms\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can see that the Cerebras Wafer-Scale Engine-3 (WSE-3) completed the query in 74ms -- faster than the blink of an eye!"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3 (ipykernel)",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.8.13"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 4
-}
diff --git a/website/docs/topics/non-openai-models/local-ollama.ipynb b/website/docs/topics/non-openai-models/local-ollama.ipynb
deleted file mode 100644
index 95803e50e..000000000
--- a/website/docs/topics/non-openai-models/local-ollama.ipynb
+++ /dev/null
@@ -1,631 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Ollama\n",
- "\n",
- "[Ollama](https://ollama.com/) is a local inference engine that enables you to run open-weight LLMs in your environment. It has native support for a large number of models such as Google's Gemma, Meta's Llama 2/3/3.1, Microsoft's Phi 3, Mistral.AI's Mistral/Mixtral, and Cohere's Command R models.\n",
- "\n",
- "Note: Previously, to use Ollama with AutoGen you required LiteLLM. Now it can be used directly and supports tool calling."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Features\n",
- "\n",
- "When using this Ollama client class, messages are tailored to accommodate the specific requirements of Ollama's API and this includes message role sequences, support for function/tool calling, and token usage.\n",
- "\n",
- "## Installing Ollama\n",
- "\n",
- "For Mac and Windows, [download Ollama](https://ollama.com/download).\n",
- "\n",
- "For Linux:\n",
- "\n",
- "```bash\n",
- "curl -fsSL https://ollama.com/install.sh | sh\n",
- "```\n",
- "\n",
- "## Downloading models for Ollama\n",
- "\n",
- "Ollama has a library of models to choose from, see them [here](https://ollama.com/library).\n",
- "\n",
- "Before you can use a model, you need to download it (using the name of the model from the library):\n",
- "\n",
- "```bash\n",
- "ollama pull llama3.1\n",
- "```\n",
- "\n",
- "To view the models you have downloaded and can use:\n",
- "\n",
- "```bash\n",
- "ollama list\n",
- "```\n",
- "\n",
- "## Getting started with AutoGen and Ollama\n",
- "\n",
- "When installing AutoGen, you need to install the `pyautogen` package with the Ollama library.\n",
- "\n",
- "``` bash\n",
- "pip install pyautogen[ollama]\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "See the sample `OAI_CONFIG_LIST` below showing how the Ollama client class is used by specifying the `api_type` as `ollama`.\n",
- "\n",
- "```python\n",
- "[\n",
- " {\n",
- " \"model\": \"llama3.1\",\n",
- " \"api_type\": \"ollama\"\n",
- " },\n",
- " {\n",
- " \"model\": \"llama3.1:8b-instruct-q6_K\",\n",
- " \"api_type\": \"ollama\"\n",
- " },\n",
- " {\n",
- " \"model\": \"mistral-nemo\",\n",
- " \"api_type\": \"ollama\"\n",
- " }\n",
- "]\n",
- "```\n",
- "\n",
- "If you need to specify the URL for your Ollama install, use the `client_host` key in your config as per the below example:\n",
- "\n",
- "```python\n",
- "[\n",
- " {\n",
- " \"model\": \"llama3.1\",\n",
- " \"api_type\": \"ollama\",\n",
- " \"client_host\": \"http://192.168.0.1:11434\"\n",
- " }\n",
- "]\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## API parameters\n",
- "\n",
- "The following Ollama parameters can be added to your config. See [this link](https://github.com/ollama/ollama/blob/main/docs/api.md#parameters) for further information on them.\n",
- "\n",
- "- num_predict (integer): -1 is infinite, -2 is fill context, 128 is default\n",
- "- repeat_penalty (float)\n",
- "- seed (integer)\n",
- "- stream (boolean)\n",
- "- temperature (float)\n",
- "- top_k (int)\n",
- "- top_p (float)\n",
- "\n",
- "Example:\n",
- "```python\n",
- "[\n",
- " {\n",
- " \"model\": \"llama3.1:instruct\",\n",
- " \"api_type\": \"ollama\",\n",
- " \"num_predict\": -1,\n",
- " \"repeat_penalty\": 1.1,\n",
- " \"seed\": 42,\n",
- " \"stream\": False,\n",
- " \"temperature\": 1,\n",
- " \"top_k\": 50,\n",
- " \"top_p\": 0.8\n",
- " }\n",
- "]\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Two-Agent Coding Example\n",
- "\n",
- "In this example, we run a two-agent chat with an AssistantAgent (primarily a coding agent) to generate code to count the number of prime numbers between 1 and 10,000 and then it will be executed.\n",
- "\n",
- "We'll use Meta's Llama 3.1 model which is suitable for coding.\n",
- "\n",
- "In this example we will specify the URL for the Ollama installation using `client_host`."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "config_list = [\n",
- " {\n",
- " # Let's choose the Meta's Llama 3.1 model (model names must match Ollama exactly)\n",
- " \"model\": \"llama3.1:8b\",\n",
- " # We specify the API Type as 'ollama' so it uses the Ollama client class\n",
- " \"api_type\": \"ollama\",\n",
- " \"stream\": False,\n",
- " \"client_host\": \"http://192.168.0.1:11434\",\n",
- " }\n",
- "]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Importantly, we have tweaked the system message so that the model doesn't return the termination keyword, which we've changed to FINISH, with the code block."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "/usr/local/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
- " from .autonotebook import tqdm as notebook_tqdm\n"
- ]
- }
- ],
- "source": [
- "from pathlib import Path\n",
- "\n",
- "from autogen import AssistantAgent, UserProxyAgent\n",
- "from autogen.coding import LocalCommandLineCodeExecutor\n",
- "\n",
- "# Setting up the code executor\n",
- "workdir = Path(\"coding\")\n",
- "workdir.mkdir(exist_ok=True)\n",
- "code_executor = LocalCommandLineCodeExecutor(work_dir=workdir)\n",
- "\n",
- "# Setting up the agents\n",
- "\n",
- "# The UserProxyAgent will execute the code that the AssistantAgent provides\n",
- "user_proxy_agent = UserProxyAgent(\n",
- " name=\"User\",\n",
- " code_execution_config={\"executor\": code_executor},\n",
- " is_termination_msg=lambda msg: \"FINISH\" in msg.get(\"content\"),\n",
- ")\n",
- "\n",
- "system_message = \"\"\"You are a helpful AI assistant who writes code and the user\n",
- "executes it. Solve tasks using your python coding skills.\n",
- "In the following cases, suggest python code (in a python coding block) for the\n",
- "user to execute. When using code, you must indicate the script type in the code block.\n",
- "You only need to create one working sample.\n",
- "Do not suggest incomplete code which requires users to modify it.\n",
- "Don't use a code block if it's not intended to be executed by the user. Don't\n",
- "include multiple code blocks in one response. Do not ask users to copy and\n",
- "paste the result. Instead, use 'print' function for the output when relevant.\n",
- "Check the execution result returned by the user.\n",
- "\n",
- "If the result indicates there is an error, fix the error.\n",
- "\n",
- "IMPORTANT: If it has executed successfully, ONLY output 'FINISH'.\"\"\"\n",
- "\n",
- "# The AssistantAgent, using the Ollama config, will take the coding request and return code\n",
- "assistant_agent = AssistantAgent(\n",
- " name=\"Ollama Assistant\",\n",
- " system_message=system_message,\n",
- " llm_config={\"config_list\": config_list},\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can now start the chat."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u001b[33mUser\u001b[0m (to Ollama Assistant):\n",
- "\n",
- "Provide code to count the number of prime numbers from 1 to 10000.\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33mOllama Assistant\u001b[0m (to User):\n",
- "\n",
- "```python\n",
- "def is_prime(n):\n",
- " if n <= 1:\n",
- " return False\n",
- " for i in range(2, int(n**0.5) + 1):\n",
- " if n % i == 0:\n",
- " return False\n",
- " return True\n",
- "\n",
- "count = sum(is_prime(i) for i in range(1, 10001))\n",
- "print(count)\n",
- "```\n",
- "\n",
- "Please execute this code. I will wait for the result.\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[31m\n",
- ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
- "\u001b[31m\n",
- ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
- "\u001b[31m\n",
- ">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n",
- "\u001b[33mUser\u001b[0m (to Ollama Assistant):\n",
- "\n",
- "exitcode: 0 (execution succeeded)\n",
- "Code output: 1229\n",
- "\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33mOllama Assistant\u001b[0m (to User):\n",
- "\n",
- "FINISH\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[31m\n",
- ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n"
- ]
- }
- ],
- "source": [
- "# Start the chat, with the UserProxyAgent asking the AssistantAgent the message\n",
- "chat_result = user_proxy_agent.initiate_chat(\n",
- " assistant_agent,\n",
- " message=\"Provide code to count the number of prime numbers from 1 to 10000.\",\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Tool Calling - Native vs Manual\n",
- "\n",
- "Ollama supports native tool calling (Ollama v0.3.1 library onward). If you install AutoGen with `pip install pyautogen[ollama]` you will be able to use native tool calling.\n",
- "\n",
- "The parameter `native_tool_calls` in your configuration allows you to specify if you want to use Ollama's native tool calling (default) or manual tool calling.\n",
- "\n",
- "```python\n",
- "[\n",
- " {\n",
- " \"model\": \"llama3.1\",\n",
- " \"api_type\": \"ollama\",\n",
- " \"client_host\": \"http://192.168.0.1:11434\",\n",
- " \"native_tool_calls\": True # Use Ollama's native tool calling, False for manual\n",
- " }\n",
- "]\n",
- "```\n",
- "\n",
- "Native tool calling only works with certain models and an exception will be thrown if you try to use it with an unsupported model.\n",
- "\n",
- "Manual tool calling allows you to use tool calling with any Ollama model. It incorporates guided tool calling messages into the prompt that guide the LLM through the process of selecting a tool and then evaluating the result of the tool. As to be expected, the ability to follow instructions and return formatted JSON is highly dependent on the model.\n",
- "\n",
- "You can tailor the manual tool calling messages by adding these parameters to your configuration:\n",
- "\n",
- "- `manual_tool_call_instruction`\n",
- "- `manual_tool_call_step1`\n",
- "- `manual_tool_call_step2`\n",
- "\n",
- "To use manual tool calling set `native_tool_calls` to `False`."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Reducing repetitive tool calls\n",
- "\n",
- "By incorporating tools into a conversation, LLMs can often continually recommend them to be called, even after they've been called and a result returned. This can lead to a never ending cycle of tool calls.\n",
- "\n",
- "To remove the chance of an LLM recommending a tool call, an additional parameter called `hide_tools` can be used to specify when tools are hidden from the LLM. The string values for the parameter are:\n",
- "\n",
- "- 'never': tools are never hidden\n",
- "- 'if_all_run': tools are hidden if all tools have been called\n",
- "- 'if_any_run': tools are hidden if any tool has been called\n",
- "\n",
- "This can be used with native or manual tool calling, an example of a configuration is shown below.\n",
- "\n",
- "```python\n",
- "[\n",
- " {\n",
- " \"model\": \"llama3.1\",\n",
- " \"api_type\": \"ollama\",\n",
- " \"client_host\": \"http://192.168.0.1:11434\",\n",
- " \"native_tool_calls\": True,\n",
- " \"hide_tools\": \"if_any_run\" # Hide tools once any tool has been called\n",
- " }\n",
- "]\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Tool Call Example\n",
- "\n",
- "In this example, instead of writing code, we will have an agent assist with some trip planning using multiple tool calling.\n",
- "\n",
- "Again, we'll use Meta's versatile Llama 3.1.\n",
- "\n",
- "Native Ollama tool calling will be used and we'll utilise the `hide_tools` parameter to hide the tools once all have been called."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [],
- "source": [
- "import json\n",
- "from typing import Literal\n",
- "\n",
- "from typing_extensions import Annotated\n",
- "\n",
- "import autogen\n",
- "\n",
- "config_list = [\n",
- " {\n",
- " # Let's choose the Meta's Llama 3.1 model (model names must match Ollama exactly)\n",
- " \"model\": \"llama3.1:8b\",\n",
- " \"api_type\": \"ollama\",\n",
- " \"stream\": False,\n",
- " \"client_host\": \"http://192.168.0.1:11434\",\n",
- " \"hide_tools\": \"if_any_run\",\n",
- " }\n",
- "]"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We'll create our agents. Importantly, we're using native Ollama tool calling and to help guide it we add the JSON to the system_message so that the number fields aren't wrapped in quotes (becoming strings)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Create the agent for tool calling\n",
- "chatbot = autogen.AssistantAgent(\n",
- " name=\"chatbot\",\n",
- " system_message=\"\"\"For currency exchange and weather forecasting tasks,\n",
- " only use the functions you have been provided with.\n",
- " Example of the return JSON is:\n",
- " {\n",
- " \"parameter_1_name\": 100.00,\n",
- " \"parameter_2_name\": \"ABC\",\n",
- " \"parameter_3_name\": \"DEF\",\n",
- " }.\n",
- " Another example of the return JSON is:\n",
- " {\n",
- " \"parameter_1_name\": \"GHI\",\n",
- " \"parameter_2_name\": \"ABC\",\n",
- " \"parameter_3_name\": \"DEF\",\n",
- " \"parameter_4_name\": 123.00,\n",
- " }.\n",
- " Output 'HAVE FUN!' when an answer has been provided.\"\"\",\n",
- " llm_config={\"config_list\": config_list},\n",
- ")\n",
- "\n",
- "# Note that we have changed the termination string to be \"HAVE FUN!\"\n",
- "user_proxy = autogen.UserProxyAgent(\n",
- " name=\"user_proxy\",\n",
- " is_termination_msg=lambda x: x.get(\"content\", \"\") and \"HAVE FUN!\" in x.get(\"content\", \"\"),\n",
- " human_input_mode=\"NEVER\",\n",
- " max_consecutive_auto_reply=1,\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Create and register our functions (tools). See the [tutorial chapter on tool use](/docs/tutorial/tool-use) \n",
- "for more information."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Currency Exchange function\n",
- "\n",
- "CurrencySymbol = Literal[\"USD\", \"EUR\"]\n",
- "\n",
- "# Define our function that we expect to call\n",
- "\n",
- "\n",
- "def exchange_rate(base_currency: CurrencySymbol, quote_currency: CurrencySymbol) -> float:\n",
- " if base_currency == quote_currency:\n",
- " return 1.0\n",
- " elif base_currency == \"USD\" and quote_currency == \"EUR\":\n",
- " return 1 / 1.1\n",
- " elif base_currency == \"EUR\" and quote_currency == \"USD\":\n",
- " return 1.1\n",
- " else:\n",
- " raise ValueError(f\"Unknown currencies {base_currency}, {quote_currency}\")\n",
- "\n",
- "\n",
- "# Register the function with the agent\n",
- "\n",
- "\n",
- "@user_proxy.register_for_execution()\n",
- "@chatbot.register_for_llm(description=\"Currency exchange calculator.\")\n",
- "def currency_calculator(\n",
- " base_amount: Annotated[\n",
- " float,\n",
- " \"Amount of currency in base_currency. Type is float, not string, return value should be a number only, e.g. 987.65.\",\n",
- " ],\n",
- " base_currency: Annotated[CurrencySymbol, \"Base currency\"] = \"USD\",\n",
- " quote_currency: Annotated[CurrencySymbol, \"Quote currency\"] = \"EUR\",\n",
- ") -> str:\n",
- " quote_amount = exchange_rate(base_currency, quote_currency) * base_amount\n",
- " return f\"{format(quote_amount, '.2f')} {quote_currency}\"\n",
- "\n",
- "\n",
- "# Weather function\n",
- "\n",
- "\n",
- "# Example function to make available to model\n",
- "def get_current_weather(location, unit=\"fahrenheit\"):\n",
- " \"\"\"Get the weather for some location\"\"\"\n",
- " if \"chicago\" in location.lower():\n",
- " return json.dumps({\"location\": \"Chicago\", \"temperature\": \"13\", \"unit\": unit})\n",
- " elif \"san francisco\" in location.lower():\n",
- " return json.dumps({\"location\": \"San Francisco\", \"temperature\": \"55\", \"unit\": unit})\n",
- " elif \"new york\" in location.lower():\n",
- " return json.dumps({\"location\": \"New York\", \"temperature\": \"11\", \"unit\": unit})\n",
- " else:\n",
- " return json.dumps({\"location\": location, \"temperature\": \"unknown\"})\n",
- "\n",
- "\n",
- "# Register the function with the agent\n",
- "\n",
- "\n",
- "@user_proxy.register_for_execution()\n",
- "@chatbot.register_for_llm(description=\"Weather forecast for US cities.\")\n",
- "def weather_forecast(\n",
- " location: Annotated[str, \"City name\"],\n",
- ") -> str:\n",
- " weather_details = get_current_weather(location=location)\n",
- " weather = json.loads(weather_details)\n",
- " return f\"{weather['location']} will be {weather['temperature']} degrees {weather['unit']}\""
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "And run it!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
- "\n",
- "What's the weather in New York and can you tell me how much is 123.45 EUR in USD so I can spend it on my holiday? Throw a few holiday tips in as well.\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
- "\n",
- "\n",
- "\u001b[32m***** Suggested tool call (ollama_func_4506): weather_forecast *****\u001b[0m\n",
- "Arguments: \n",
- "{\"location\": \"New York\"}\n",
- "\u001b[32m********************************************************************\u001b[0m\n",
- "\u001b[32m***** Suggested tool call (ollama_func_4507): currency_calculator *****\u001b[0m\n",
- "Arguments: \n",
- "{\"base_amount\": 123.45, \"base_currency\": \"EUR\", \"quote_currency\": \"USD\"}\n",
- "\u001b[32m***********************************************************************\u001b[0m\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[35m\n",
- ">>>>>>>> EXECUTING FUNCTION weather_forecast...\u001b[0m\n",
- "\u001b[35m\n",
- ">>>>>>>> EXECUTING FUNCTION currency_calculator...\u001b[0m\n",
- "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
- "\n",
- "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
- "\n",
- "\u001b[32m***** Response from calling tool (ollama_func_4506) *****\u001b[0m\n",
- "New York will be 11 degrees fahrenheit\n",
- "\u001b[32m*********************************************************\u001b[0m\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
- "\n",
- "\u001b[32m***** Response from calling tool (ollama_func_4507) *****\u001b[0m\n",
- "135.80 USD\n",
- "\u001b[32m*********************************************************\u001b[0m\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
- "\n",
- "Based on the results, it seems that:\n",
- "\n",
- "* The weather forecast for New York is expected to be around 11 degrees Fahrenheit.\n",
- "* The exchange rate for EUR to USD is currently 1 EUR = 1.3580 USD, so 123.45 EUR is equivalent to approximately 135.80 USD.\n",
- "\n",
- "As a bonus, here are some holiday tips in New York:\n",
- "\n",
- "* Be sure to try a classic New York-style hot dog from a street cart or a diner.\n",
- "* Explore the iconic Central Park and take a stroll through the High Line for some great views of the city.\n",
- "* Catch a Broadway show or a concert at one of the many world-class venues in the city.\n",
- "\n",
- "And... HAVE FUN!\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "LLM SUMMARY: The weather forecast for New York is expected to be around 11 degrees Fahrenheit.\n",
- "123.45 EUR is equivalent to approximately 135.80 USD.\n",
- "Try a classic New York-style hot dog, explore Central Park and the High Line, and catch a Broadway show or concert during your visit.\n"
- ]
- }
- ],
- "source": [
- "# start the conversation\n",
- "res = user_proxy.initiate_chat(\n",
- " chatbot,\n",
- " message=\"What's the weather in New York and can you tell me how much is 123.45 EUR in USD so I can spend it on my holiday? Throw a few holiday tips in as well.\",\n",
- " summary_method=\"reflection_with_llm\",\n",
- ")\n",
- "\n",
- "print(f\"LLM SUMMARY: {res.summary['content']}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Great, we can see that Llama 3.1 has helped choose the right functions, their parameters, and then summarised them for us."
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.9"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}