|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import textwrap |
|
|
from typing import Optional, Type |
|
|
|
|
|
from pydantic import BaseModel |
|
|
|
|
|
from camel.messages import OpenAIMessage |
|
|
|
|
|
|
|
|
def try_modify_message_with_format( |
|
|
message: OpenAIMessage, |
|
|
response_format: Optional[Type[BaseModel]], |
|
|
) -> None: |
|
|
r"""Modifies the content of the message to include the instruction of using |
|
|
the response format. |
|
|
|
|
|
The message will not be modified in the following cases: |
|
|
- response_format is None |
|
|
- message content is not a string |
|
|
- message role is assistant |
|
|
|
|
|
Args: |
|
|
response_format (Optional[Type[BaseModel]]): The Pydantic model class. |
|
|
message (OpenAIMessage): The message to be modified. |
|
|
""" |
|
|
if response_format is None: |
|
|
return |
|
|
|
|
|
if not isinstance(message["content"], str): |
|
|
return |
|
|
|
|
|
if message["role"] == "assistant": |
|
|
return |
|
|
|
|
|
json_schema = response_format.model_json_schema() |
|
|
updated_prompt = textwrap.dedent( |
|
|
f"""\ |
|
|
{message["content"]} |
|
|
|
|
|
Please generate a JSON response adhering to the following JSON schema: |
|
|
{json_schema} |
|
|
Make sure the JSON response is valid and matches the EXACT structure defined in the schema. Your result should ONLY be a valid json object, WITHOUT ANY OTHER TEXT OR COMMENTS. |
|
|
""" |
|
|
) |
|
|
message["content"] = updated_prompt |
|
|
|