|
2 | 2 | from parsec.core import BaseLLMAdapter, GenerationResponse, ModelProviders |
3 | 3 | from typing import AsyncIterator |
4 | 4 | from parsec.logging import get_logger |
| 5 | +from pydantic import BaseModel |
5 | 6 | import time |
6 | 7 | import json |
7 | 8 |
|
@@ -41,8 +42,13 @@ async def generate(self, prompt: str, schema=None, temperature=0.7, |
41 | 42 | extra_args = {} |
42 | 43 | if schema and self.supports_native_structure_output(): |
43 | 44 | extra_args["response_format"] = {"type": "json_object"} |
| 45 | + # Convert Pydantic model to JSON schema if needed |
| 46 | + if isinstance(schema, type) and issubclass(schema, BaseModel): |
| 47 | + schema_dict = schema.model_json_schema() |
| 48 | + else: |
| 49 | + schema_dict = schema |
44 | 50 | # Add schema to prompt |
45 | | - messages[0]["content"] = f"{prompt}\n\nReturn valid JSON matching this schema: {json.dumps(schema)}" |
| 51 | + messages[0]["content"] = f"{prompt}\n\nReturn valid JSON matching this schema: {json.dumps(schema_dict)}" |
46 | 52 | try: |
47 | 53 | response = await client.chat.completions.create( |
48 | 54 | model=self.model, |
@@ -85,7 +91,12 @@ async def generate_stream( |
85 | 91 | extra_args = {} |
86 | 92 | if schema and self.supports_native_structure_output(): |
87 | 93 | extra_args["response_format"] = {"type": "json_object"} |
88 | | - messages[0]["content"] = f"{prompt}\n\nReturn valid JSON matching this schema: {json.dumps(schema)}" |
| 94 | + # Convert Pydantic model to JSON schema if needed |
| 95 | + if isinstance(schema, type) and issubclass(schema, BaseModel): |
| 96 | + schema_dict = schema.model_json_schema() |
| 97 | + else: |
| 98 | + schema_dict = schema |
| 99 | + messages[0]["content"] = f"{prompt}\n\nReturn valid JSON matching this schema: {json.dumps(schema_dict)}" |
89 | 100 |
|
90 | 101 | stream = await client.chat.completions.create( |
91 | 102 | model=self.model, |
|
0 commit comments