Groq Python API Library

repository·main·Indexed 20 days ago

https://github.com/groq/groq-python

The official Python library for the Groq API (v1.6.0), providing synchronous and asynchronous access to the Groq REST API for Python 3.10+ applications. It supports chat completions, embeddings, audio services (speech, transcription, translation), model management, batch processing, and file uploads. The library includes built-in support for aiohttp as an async backend, automatic retries, and comprehensive error handling via groq.APIError.

Tokens
14.1K
Snippets
44
Records
63
Agent score
67%

What's inside groq-python

  1. Differentiate between `null` and missing fields in API responses

    main

    In API responses, a field that is explicitly null or missing entirely will both result in None in Python. To distinguish between them, check the .model_fields_set attribute on the response object. If the field name is not in .model_fields_set, the key was missing from the JSON; otherwise, it was explicitly set to null.

    if response.my_field is None:
      if 'my_field' not in response.model_fields_set:
        print('Got json like {}, without a "my_field" key present at all.'.format(response))
      else:
        print('Got json like {"my_field": null}.')
  2. Manage HTTP resources and client lifecycle

    main

    While the library closes connections upon garbage collection, it is best practice to manually manage the lifecycle. Use a context manager to ensure the client and its underlying connections are closed correctly when exiting the block.

    from groq import Groq
    
    with Groq() as client:
      # make requests here
      ...
    
    # HTTP client is now closed
  3. Enable logging for the Groq client

    main

    The library uses the standard Python logging module. You can enable logging by setting the GROQ_LOG environment variable to info or debug (for more verbose output).

    $ export GROQ_LOG=info
  4. Use aiohttp as the async HTTP backend

    main

    By default, the async client uses httpx. To use aiohttp for improved concurrency performance, install the aiohttp extra and pass DefaultAioHttpClient() to the http_client parameter.

    pip install groq[aiohttp]
    import os
    import asyncio
    from groq import DefaultAioHttpClient
    from groq import AsyncGroq
    
    async def main() -> None:
        async with AsyncGroq(
            api_key=os.environ.get("GROQ_API_KEY"),
            http_client=DefaultAioHttpClient(),
        ) as client:
            chat_completion = await client.chat.completions.create(
                messages=[
                    {
                        "role": "user",
                        "content": "Explain the importance of low latency LLMs",
                    }
                ],
                model="openai/gpt-oss-20b",
            )
            print(chat_completion.id)
    
    asyncio.run(main())
  5. Use Structured Outputs with ResponseFormat

    main

    You can force the model to output data in a specific format using the response_format parameter. There are three modes:

    1. JSON Schema (Recommended): Uses type: "json_schema" to ensure the model matches a provided JSON schema. This enables 'Structured Outputs'. You can set strict: true to enforce exact schema adherence.
    2. JSON Object: Uses type: "json_object" to ensure the output is valid JSON. This is an older method and requires instructions in the system or user message to work effectively.
    3. Text: The default type: "text" format.
    client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[{"role": "user", "content": "Extract the name and age from: John is 30 years old"}],
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "user_info",
                "schema": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"},
                        "age": {"type": "integer"}
                    },
                    "required": ["name", "age"]
                },
                "strict": true
            }
        }
    )
  6. Configure Tool Use with tools and tool_choice

    main

    The tools parameter allows you to provide a list of functions the model can call. Currently, only functions are supported as tools (up to 128 functions).

    Tool Choice Options

    Control how the model interacts with tools using tool_choice:

    • none: The model will not call any tool and will only generate a message.
    • auto: The model decides whether to call a tool or generate a message.
    • required: The model must call one or more tools.
    • Specific Tool: You can force a specific tool by passing {"type": "function", "function": {"name": "my_function"}}.
    client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[{"role": "user", "content": "What is the weather in London?"}],
        tools=[
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get the current weather",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "location": {"type": "string"}
                        }
                    }
                }
            }
        ],
        tool_choice="auto"
    )
  7. Understand the ChatCompletionChunk structure for streaming

    main

    When using streaming mode in Groq, the API returns a series of ChatCompletionChunk objects. Each chunk shares the same id, created timestamp, and model name.

    Key behaviors to note:

    • Choices: The choices list contains Choice objects. Each Choice contains a delta (the incremental content/tool calls) and a finish_reason.
    • Usage Data: By default, usage statistics are not included in the stream. To receive usage data, you must set stream_options: {"include_usage": true} in your request. When enabled, the usage field will be present in chunks, but will contain a null value until the final chunk, which contains the full token usage statistics.
    • Metadata: The x_groq field provides additional metadata, including a request id, seed, and usage_breakdown (for compound AI systems). This is typically sent in the first and final chunks.
    • Finish Reasons: The finish_reason in a Choice object indicates why generation stopped (e.g., stop, length, tool_calls, content_filter).
  8. Configure the HTTP client and proxies

    main

    You can customize the underlying httpx client by passing a DefaultHttpxClient to the Groq constructor. This allows for configuring proxies, custom transports, and base URLs. You can also apply these configurations to a specific client instance using .with_options().

    import httpx
    from groq import Groq, DefaultHttpxClient
    
    client = Groq(
        # Or use the `GROQ_BASE_URL` env var
        base_url="http://my.test.server.example.com:8083",
        http_client=DefaultHttpxClient(
            proxy="http://my.test.proxy.example.com",
            transport=httpx.HTTPTransport(local_address="0.0.0.0"),
        ),
    )
    
    # Per-request customization
    client.with_options(http_client=DefaultHttpxClient(...))
  9. Understand BatchRetrieveResponse status values

    main

    The status field in a BatchRetrieveResponse indicates the current lifecycle stage of a batch job. You can use this to determine if a batch is ready for processing or if you need to inspect error files.

    Valid status values:

    • validating: The batch is being checked for validity.
    • failed: The batch job encountered an error.
    • in_progress: The batch is currently being processed.
    • finalizing: The batch is in the final stages of processing.
    • completed: The batch has finished successfully.
    • expired: The batch has exceeded its processing window.
    • cancelling: A cancellation request is in progress.
    • cancelled: The batch was successfully cancelled.
  10. Use the Groq synchronous client

    main

    To use the synchronous client, import Groq and instantiate it. By default, it looks for the GROQ_API_KEY environment variable. You can also provide the api_key explicitly as a keyword argument.

    import os
    from groq import Groq
    
    client = Groq(
        api_key=os.environ.get("GROQ_API_KEY"),  # This is the default and can be omitted,
    )
    
    chat_completion = client.chat.completions.create(
        messages=[
            {
                "role": "user",
                "content": "Explain the importance of low latency LLMs",
            }
        ],
        model="openai/gpt-oss-20b",
    )
    print(chat_completion.choices[0].message.content)
  11. Upload files for transcription

    main

    When performing file uploads (e.g., for audio transcriptions), you can pass the file as bytes, a PathLike instance, or a tuple of (filename, contents, media type). If using a PathLike instance with the async client, the file is read asynchronously automatically.

    from pathlib import Path
    from groq import Groq
    
    client = Groq()
    
    client.audio.transcriptions.create(
        model="whisper-large-v3-turbo",
        file=Path("/path/to/file"),
    )