meta-llama / llama-stack

Composable building blocks to build Llama Apps
MIT License
4.57k stars 576 forks source link

properly parsing model's async response #68

Closed teamblubee closed 2 months ago

teamblubee commented 2 months ago

Testing on llama 3.1 8B, local version

Don't mind this sloppy code, I'm trying to understand the response format since it seems the documentation has changed.

        buffer = ""
        # Process the response from the server
        async for log in client.chat_completion(request):
            # Print log to understand its structure
            # print(f"Log structure: {log}\n{type(log)}\n")
            # print(f"\nLog structure: {log}\n{type(log)}\n{log.event}\n{type(log.event)}\n")
            if isinstance(log, ChatCompletionResponseStreamChunk):
                # print(f"RESPONSE STREAM CHUNK")
                event = log.event
                buffer += event.delta
                if isinstance(log.event, ChatCompletionResponseEvent):
                    # print("\tRESPONSE EVENT")
                    if isinstance(event.event_type, ChatCompletionResponseEventType):
                        if event.event_type == ChatCompletionResponseEventType.start:
                            cprint(f"\n", "white", flush=True)
                        elif event.event_type == ChatCompletionResponseEventType.complete:
                            _stop_reason = event.stop_reason
                            cprint(f"\nCOMPLETED::Stop Reason::[{_stop_reason}]\n", "red", flush=True)
                            break
                        elif event.event_type == ChatCompletionResponseEventType.progress:
                            if isinstance(event.delta, str):
                                try:
                                    _ = json.loads(event.delta)
                                    if isinstance(_, str):
                                        cprint(_, "blue", end='', flush=True)
                                    elif isinstance(_, int):
                                        cprint(_, "green", end='', flush=True)
                                    else:
                                        print(f"""
                                        INSTANCE         ::[{isinstance(_,str)}]
                                        EVENT_DELTA      ::[{event.delta}]
                                        TYPE EVENT_DELTA ::[{type(event.delta)}]
                                        INSTANCE         ::[{isinstance(event.delta,str)}]
                                        _                ::[{_}]
                                        TYPE _           ::[{type(_)}]
                                        DATA             ::[{event.delta}]
                                        """)
                                        import time
                                        time.sleep(3)
                                except Exception as e:
                                    match = re.search(JSON_PARSE_PATTERN, log.event.delta)
                                    if match:
                                        bj = log.event.delta[:match.start()].strip()
                                        aj = log.event.delta[match.start():].strip()
                                        cprint(bj, "yellow", end='', flush=True)
                                        cprint(aj, "magenta", end='', flush=True)
                                    else:
                                        # print(log.event.delta)
                                        cprint(log.event.delta, "cyan", end='', flush=True)
                            # if ("errors" in log.event.delta and (log.event.logprobs == None or log.event.stop_reason == None)):
                                # break
                            # else:
                                # cprint(log.event.delta, "cyan", end='', flush=True)
                        else:
                            print(f"""
                            Log structure: {log}
                            {type(log)}
                            {log.event}
                            {type(log.event)}
                            ---------------------------------------------------------------------
                            print(f"\t\tEVENT TYPE             ::[{log.event.event_type}]")
                            print(f"\t\tEVENT [type] TYPE      ::[{type(log.event.event_type)}]")
                            print(f"\t\tEVENT TYPE DELTA       ::[{log.event.delta}]")
                            print(f"\t\tEVENT TYPE LOGPROBS    ::[{log.event.logprobs}]")
                            print(f"\t\tEVENT TYPE STOP_REASON ::[{log.event.stop_reason}]")
                            ---------------------------------------------------------------------
                            UNHANDLED ChatCompletionResponseEventType::[{log.event.event_type}]
                                """)
        print(buffer)
        buffer = ""

I keep getting json looking things like these in the response and cannot get them out via code.

{"event":{"event_type":"progress","delta":" error","logprobs":null,"stop_reason":null}}

What is that event and how can I properly parse it from the response?

tell me about chemistry, show some formulas in mathjax formula, provide sample code using python, place some markdown formatted tables, use numbers, dates, years, ages and some references from your training data.

response

**Introduction to Chemistry**
==========================

Chemistry is the scientific study of the composition, properties, and reactions of matter. It involves the study of atoms, molecules, and chemical reactions, and is a fundamental subject that underlies many areas of science and engineering.

**Atomic Structure**
-------------------

The atomic structure is the basic building block of matter. It consists of:

*   **Protons**: positively charged particles found in the nucleus of an atom
*   **Neutrons**: particles with no charge found in the nucleus of an atom
*   **Electrons**: negatively charged particles that orbit the nucleus of an atom

The atomic number (Z) is the number of protons in an atom's nucleus, and is unique to each element. The mass number (A) is the total number of protons and neutrons in an atom's nucleus.

**Chemical Reactions**
---------------------

Chemical reactions involve the transformation of one or more substances into new substances. They can be represented using chemical equations, which show the reactants and products of a reaction.

**Chemical Equations**
---------------------

Chemical equations can be represented using the following notation:

$$\text{Reactants} \rightarrow \text{Products}$$

For example, the equation for the combustion of methane is:

$$\text{CH}_4 + 2\text{O}_2 \rightarrow \text{CO}_2 + 2\text{H}_2\text{O}$$

**Chemical Bonding**
-------------------

Chemical bonding is the attraction between atoms that results in the formation of a chemical compound. There are several types of chemical bonds, including:

*   **Covalent bonds**: formed when two or more atoms share one or more pairs of electrons
*   **Ionic bonds**: formed when one or more electrons are transferred from one atom to another
*   **Hydrogen bonds**: formed when a hydrogen atom is attracted to an electronegative atom

**Sample Code using Python**
---------------------------

Here is a simple example of a Python program that calculates the molar mass of a chemical compound:

```python
def calculate_molar_mass(compound):
    """
    Calculate the molar mass of a chemical compound.

    Args:
        compound (str): The chemical formula of the compound.

    Returns:
        float: The molar mass of the compound.
    """
    # Define a dictionary of atomic masses
    atomic_masses = {
        'H': 1.008,
        'C': 12.01,
        'O': 16.00,
        'N': 14.01,
        'S': 32.07,
        'P': 30.97,
        'Cl': 35.45,
        'Br': 79.90,
        'I': 126.90
    }

    # Initialize the molar mass to 0
    molar_mass = 0

    # Iterate over the atoms in the compound
    for atom in compound:
        # Check if the atom is in the dictionary
        if atom in atomic_masses:
            # Add the atomic mass to the molar mass
            molar_mass += atomic_masses[atom]
        else:
            # Raise an{"event":{"event_type":"progress","delta":" error","logprobs":null,"stop_reason":null}}
 if the atom is not in the dictionary
            raise ValueError(f"Unknown atom: {atom}")

    # Return the molar mass
    return molar_mass

# Test the function
compound = "CH4"
print(f"The molar mass of {compound} is {calculate_molar_mass(compound)} g/mol")

Chemical Properties

Chemical properties are characteristics of a substance that can be observed or measured. Some common chemical properties include:

Property Description
Melting point The temperature at which a substance changes state from solid to liquid
Boiling point The temperature at which a substance changes state from liquid to gas
Density The mass of a substance per unit volume
Solubility The ability of a substance to dissolve in a solvent

Chemical Reactions and Equations

Chemical reactions and equations are used to describe the transformation of one or more substances into new substances. Some common types of chemical reactions include:

Reaction type Description
Synthesis reaction A reaction in which two or more substances combine to form a new substance
Decomposition reaction A reaction in which a single substance breaks down into two or more new substances
Replacement reaction A reaction in which one substance is replaced by another substance

References

Age of Chemistry

Chemistry has a long and rich history that dates back to ancient times. Some notable milestones in the development of chemistry include:

Years of Study

The study of chemistry typically takes several years to complete. Here is a rough outline of the typical progression of a chemistry student:

Note: The exact progression may vary depending on the individual and their goals.


a buffer I save from the response
```string
**Introduction to Chemistry**
==========================

Chemistry is the scientific study of the composition, properties, and reactions of matter. It involves the study of atoms, molecules, and chemical reactions, and is a fundamental subject that underlies many areas of science and engineering.

**Atomic Structure**
-------------------

The atomic structure is the basic building block of matter. It consists of:

*   **Protons**: positively charged particles found in the nucleus of an atom
*   **Neutrons**: particles with no charge found in the nucleus of an atom
*   **Electrons**: negatively charged particles that orbit the nucleus of an atom

The atomic number (Z) is the number of protons in an atom's nucleus, and is unique to each element. The mass number (A) is the total number of protons and neutrons in an atom's nucleus.

**Chemical Reactions**
---------------------

Chemical reactions involve the transformation of one or more substances into new substances. They can be represented using chemical equations, which show the reactants and products of a reaction.

**Chemical Equations**
---------------------

Chemical equations can be represented using the following notation:

$$\text{Reactants} \rightarrow \text{Products}$$

For example, the equation for the combustion of methane is:

$$\text{CH}_4 + 2\text{O}_2 \rightarrow \text{CO}_2 + 2\text{H}_2\text{O}$$

**Chemical Bonding**
-------------------

Chemical bonding is the attraction between atoms that results in the formation of a chemical compound. There are several types of chemical bonds, including:

*   **Covalent bonds**: formed when two or more atoms share one or more pairs of electrons
*   **Ionic bonds**: formed when one or more electrons are transferred from one atom to another
*   **Hydrogen bonds**: formed when a hydrogen atom is attracted to an electronegative atom

**Sample Code using Python**
---------------------------

Here is a simple example of a Python program that calculates the molar mass of a chemical compound:

```python
def calculate_molar_mass(compound):
    """
    Calculate the molar mass of a chemical compound.

    Args:
        compound (str): The chemical formula of the compound.

    Returns:
        float: The molar mass of the compound.
    """
    # Define a dictionary of atomic masses
    atomic_masses = {
        'H': 1.008,
        'C': 12.01,
        'O': 16.00,
        'N': 14.01,
        'S': 32.07,
        'P': 30.97,
        'Cl': 35.45,
        'Br': 79.90,
        'I': 126.90
    }

    # Initialize the molar mass to 0
    molar_mass = 0

    # Iterate over the atoms in the compound
    for atom in compound:
        # Check if the atom is in the dictionary
        if atom in atomic_masses:
            # Add the atomic mass to the molar mass
            molar_mass += atomic_masses[atom]
        else:
            # Raise an if the atom is not in the dictionary
            raise ValueError(f"Unknown atom: {atom}")

    # Return the molar mass
    return molar_mass

# Test the function
compound = "CH4"
print(f"The molar mass of {compound} is {calculate_molar_mass(compound)} g/mol")

Chemical Properties

Chemical properties are characteristics of a substance that can be observed or measured. Some common chemical properties include:

Property Description
Melting point The temperature at which a substance changes state from solid to liquid
Boiling point The temperature at which a substance changes state from liquid to gas
Density The mass of a substance per unit volume
Solubility The ability of a substance to dissolve in a solvent

Chemical Reactions and Equations

Chemical reactions and equations are used to describe the transformation of one or more substances into new substances. Some common types of chemical reactions include:

Reaction type Description
Synthesis reaction A reaction in which two or more substances combine to form a new substance
Decomposition reaction A reaction in which a single substance breaks down into two or more new substances
Replacement reaction A reaction in which one substance is replaced by another substance

References

Age of Chemistry

Chemistry has a long and rich history that dates back to ancient times. Some notable milestones in the development of chemistry include:

Years of Study

The study of chemistry typically takes several years to complete. Here is a rough outline of the typical progression of a chemistry student:

Note: The exact progression may vary depending on the individual and their goals.

teamblubee commented 2 months ago

I found the issue in the way the chat_completion function is defined, it's printing the error in the stream....

    async def chat_completion(self, request: ChatCompletionRequest) -> AsyncGenerator:
        async with httpx.AsyncClient() as client:
            async with client.stream(
                "POST",
                f"{self.base_url}/inference/chat_completion",
                json={
                    "request": encodable_dict(request),
                },
                headers={"Content-Type": "application/json"},
                timeout=20,
            ) as response:
                if response.status_code != 200:
                    content = await response.aread()
                    cprint(
                        f"Error: HTTP {response.status_code} {content.decode()}", "red"
                    )
                    return

                async for line in response.aiter_lines():
                    if line.startswith("data:"):
                        data = line[len("data: ") :]
                        try:
                            # Debugging: print out the structure of the data
                            # print(f"Raw response: {data}")

                            if request.stream:
                                if "error" in data:
                                    print(f"ERROR IN STREAM")
                                    cprint(data, "red") #<------------------------------- THIS LINE
                                    continue
                                # Yielding the streamed chunk response
                                yield ChatCompletionResponseStreamChunk(**json.loads(data))
                            else:
                                # Yielding the complete response at once
                                yield ChatCompletionResponse(**data)
                        except Exception as e:
                            print(data)
                            print(f"Error with parsing or validation: {e}")