跳到主要内容

Groq

Open In Colab Open on GitHub

Groq 是一个基于云的平台,以高推理速度提供多种流行的开放权重模型。模型包括 Meta 的 Llama 3、Mistral AI 的 Mixtral 和 Google 的 Gemma。

尽管Groq的API与OpenAI的API非常一致,而OpenAI的API是AutoGen原生使用的API,但该库提供了设置特定参数以及跟踪API成本的能力。

您需要一个Groq账户并创建一个API密钥。详情请参见他们的网站

Groq 提供了多种模型供使用,如下所示。请参阅模型列表 (需要登录)

请参阅下面的示例 OAI_CONFIG_LIST,展示如何通过将 api_type 指定为 groq 来使用 Groq 客户端类。

[
{
"model": "gpt-35-turbo",
"api_key": "your OpenAI Key goes here",
},
{
"model": "gpt-4-vision-preview",
"api_key": "your OpenAI Key goes here",
},
{
"model": "dalle",
"api_key": "your OpenAI Key goes here",
},
{
"model": "llama3-8b-8192",
"api_key": "your Groq API Key goes here",
"api_type": "groq"
},
{
"model": "llama3-70b-8192",
"api_key": "your Groq API Key goes here",
"api_type": "groq"
},
{
"model": "Mixtral 8x7b",
"api_key": "your Groq API Key goes here",
"api_type": "groq"
},
{
"model": "gemma-7b-it",
"api_key": "your Groq API Key goes here",
"api_type": "groq"
}
]

作为配置中api_key键和值的替代方案,你可以将环境变量GROQ_API_KEY设置为你的Groq密钥。

Linux/Mac:

export GROQ_API_KEY="your_groq_api_key_here"

Windows:

set GROQ_API_KEY=your_groq_api_key_here

API参数

您可以在Groq API的配置中添加以下参数。更多信息请参见此链接

  • frequency_penalty (数字 0..1)
  • max_tokens (整数 >= 0)
  • presence_penalty (数字 -2..2)
  • seed (整数)
  • 温度(数字0..2)
  • top_p(数字)

示例:

[
{
"model": "llama3-8b-8192",
"api_key": "your Groq API Key goes here",
"api_type": "groq",
"frequency_penalty": 0.5,
"max_tokens": 2048,
"presence_penalty": 0.2,
"seed": 42,
"temperature": 0.5,
"top_p": 0.2
}
]

双代理编码示例

在这个示例中,我们运行了一个双代理聊天,其中包含一个AssistantAgent(主要是一个编码代理)来生成代码,用于计算1到10,000之间的质数数量,然后执行该代码。

我们将使用Meta的Llama 3模型,该模型适合编码。

import os

config_list = [
{
# Let's choose the Llama 3 model
"model": "llama3-8b-8192",
# Put your Groq API key here or put it into the GROQ_API_KEY environment variable.
"api_key": os.environ.get("GROQ_API_KEY"),
# We specify the API Type as 'groq' so it uses the Groq client class
"api_type": "groq",
}
]

重要的是,我们已经调整了系统消息,以便模型不会返回终止关键字,我们已将其更改为 FINISH,与代码块一起。

from pathlib import Path

from autogen import AssistantAgent, UserProxyAgent
from autogen.coding import LocalCommandLineCodeExecutor

# Setting up the code executor
workdir = Path("coding")
workdir.mkdir(exist_ok=True)
code_executor = LocalCommandLineCodeExecutor(work_dir=workdir)

# Setting up the agents

# The UserProxyAgent will execute the code that the AssistantAgent provides
user_proxy_agent = UserProxyAgent(
name="User",
code_execution_config={"executor": code_executor},
is_termination_msg=lambda msg: "FINISH" in msg.get("content"),
)

system_message = """You are a helpful AI assistant who writes code and the user executes it.
Solve tasks using your coding and language skills.
In the following cases, suggest python code (in a python coding block) for the user to execute.
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.
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.
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.
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.
When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible.
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."""

# The AssistantAgent, using Groq's model, will take the coding request and return code
assistant_agent = AssistantAgent(
name="Groq Assistant",
system_message=system_message,
llm_config={"config_list": config_list},
)
/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
from .autonotebook import tqdm as notebook_tqdm
# Start the chat, with the UserProxyAgent asking the AssistantAgent the message
chat_result = user_proxy_agent.initiate_chat(
assistant_agent,
message="Provide code to count the number of prime numbers from 1 to 10000.",
)
User (to Groq Assistant):

Provide code to count the number of prime numbers from 1 to 10000.

--------------------------------------------------------------------------------
Groq Assistant (to User):

Here's the plan to count the number of prime numbers from 1 to 10000:

First, we need to write a helper function to check if a number is prime. A prime number is a number that is divisible only by 1 and itself.

Then, we can use a loop to iterate through all numbers from 1 to 10000, check if each number is prime using our helper function, and count the number of prime numbers found.

Here's the Python code to implement this plan:
```python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

count = 0
for i in range(2, 10001):
if is_prime(i):
count += 1

print(count)
```
Please execute this code, and I'll wait for the result.

--------------------------------------------------------------------------------

>>>>>>>> NO HUMAN INPUT RECEIVED.

>>>>>>>> USING AUTO REPLY...

>>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...
User (to Groq Assistant):

exitcode: 0 (execution succeeded)
Code output: 1229


--------------------------------------------------------------------------------
Groq Assistant (to User):

FINISH

--------------------------------------------------------------------------------

>>>>>>>> NO HUMAN INPUT RECEIVED.

工具调用示例

在这个例子中,我们将展示如何使用Meta的Llama 3模型进行并行工具调用,而不是编写代码。在此过程中,它建议同时调用多个工具,使用Groq的云推理。

我们将使用一个简单的旅行助手程序,其中包含了天气和货币转换的几个工具。

我们首先导入库并设置配置,以使用 Meta 的 Llama 3 模型和 groq 客户端类。

import json
import os
from typing import Literal

from typing_extensions import Annotated

import autogen

config_list = [
{"api_type": "groq", "model": "llama3-8b-8192", "api_key": os.getenv("GROQ_API_KEY"), "cache_seed": None}
]

创建我们的两个代理。

# Create the agent for tool calling
chatbot = autogen.AssistantAgent(
name="chatbot",
system_message="""For currency exchange and weather forecasting tasks,
only use the functions you have been provided with.
Output 'HAVE FUN!' when an answer has been provided.""",
llm_config={"config_list": config_list},
)

# Note that we have changed the termination string to be "HAVE FUN!"
user_proxy = autogen.UserProxyAgent(
name="user_proxy",
is_termination_msg=lambda x: x.get("content", "") and "HAVE FUN!" in x.get("content", ""),
human_input_mode="NEVER",
max_consecutive_auto_reply=1,
)

创建这两个函数,并对它们进行注释,以便这些描述可以传递给LLM。

我们通过使用register_for_execution函数将用户代理与之关联,以便它可以执行该函数,并使用register_for_llm函数将聊天机器人(由LLM驱动)与之关联,以便它可以将函数定义传递给LLM。

# Currency Exchange function

CurrencySymbol = Literal["USD", "EUR"]

# Define our function that we expect to call


def exchange_rate(base_currency: CurrencySymbol, quote_currency: CurrencySymbol) -> float:
if base_currency == quote_currency:
return 1.0
elif base_currency == "USD" and quote_currency == "EUR":
return 1 / 1.1
elif base_currency == "EUR" and quote_currency == "USD":
return 1.1
else:
raise ValueError(f"Unknown currencies {base_currency}, {quote_currency}")


# Register the function with the agent


@user_proxy.register_for_execution()
@chatbot.register_for_llm(description="Currency exchange calculator.")
def currency_calculator(
base_amount: Annotated[float, "Amount of currency in base_currency"],
base_currency: Annotated[CurrencySymbol, "Base currency"] = "USD",
quote_currency: Annotated[CurrencySymbol, "Quote currency"] = "EUR",
) -> str:
quote_amount = exchange_rate(base_currency, quote_currency) * base_amount
return f"{format(quote_amount, '.2f')} {quote_currency}"


# Weather function


# Example function to make available to model
def get_current_weather(location, unit="fahrenheit"):
"""Get the weather for some location"""
if "chicago" in location.lower():
return json.dumps({"location": "Chicago", "temperature": "13", "unit": unit})
elif "san francisco" in location.lower():
return json.dumps({"location": "San Francisco", "temperature": "55", "unit": unit})
elif "new york" in location.lower():
return json.dumps({"location": "New York", "temperature": "11", "unit": unit})
else:
return json.dumps({"location": location, "temperature": "unknown"})


# Register the function with the agent


@user_proxy.register_for_execution()
@chatbot.register_for_llm(description="Weather forecast for US cities.")
def weather_forecast(
location: Annotated[str, "City name"],
) -> str:
weather_details = get_current_weather(location=location)
weather = json.loads(weather_details)
return f"{weather['location']} will be {weather['temperature']} degrees {weather['unit']}"

我们传递客户的消息并运行聊天。

最后,我们要求LLM(大语言模型)总结聊天内容并打印出来。

# start the conversation
res = user_proxy.initiate_chat(
chatbot,
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.",
summary_method="reflection_with_llm",
)

print(f"LLM SUMMARY: {res.summary['content']}")
user_proxy (to chatbot):

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.

--------------------------------------------------------------------------------
chatbot (to user_proxy):

***** Suggested tool call (call_hg7g): weather_forecast *****
Arguments:
{"location":"New York"}
*************************************************************
***** Suggested tool call (call_hrsf): currency_calculator *****
Arguments:
{"base_amount":123.45,"base_currency":"EUR","quote_currency":"USD"}
****************************************************************

--------------------------------------------------------------------------------

>>>>>>>> EXECUTING FUNCTION weather_forecast...

>>>>>>>> EXECUTING FUNCTION currency_calculator...
user_proxy (to chatbot):

user_proxy (to chatbot):

***** Response from calling tool (call_hg7g) *****
New York will be 11 degrees fahrenheit
**************************************************

--------------------------------------------------------------------------------
user_proxy (to chatbot):

***** Response from calling tool (call_hrsf) *****
135.80 USD
**************************************************

--------------------------------------------------------------------------------
chatbot (to user_proxy):

***** Suggested tool call (call_ahwk): weather_forecast *****
Arguments:
{"location":"New York"}
*************************************************************

--------------------------------------------------------------------------------
LLM SUMMARY: Based on the conversation, it's predicted that New York will be 11 degrees Fahrenheit. You also found out that 123.45 EUR is equal to 135.80 USD. Here are a few holiday tips:

* Pack warm clothing for your visit to New York, as the temperature is expected to be quite chilly.
* Consider exchanging your money at a local currency exchange or an ATM since the exchange rate might not be as favorable in tourist areas.
* Make sure to check the estimated expenses for your holiday and adjust your budget accordingly.

I hope you have a great trip!

利用其快速推理能力,Groq在整个聊天过程中所需时间不到2秒!

此外,Llama 3 能够调用工具并传递正确的参数。user_proxy 然后执行它们,并将结果传递回 Llama 3 以总结整个对话。