Skip to content

Commit

Permalink
feature to add default value prompt, and automatic prompt for literals
Browse files Browse the repository at this point in the history
  • Loading branch information
vizsatiz committed Dec 16, 2024
1 parent 92964d4 commit ed8efdf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
6 changes: 5 additions & 1 deletion examples/python/output_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@
'type': 'literal',
'description': 'The last name of the person, the value can be either of Vishnu or Satis',
'name': 'last_name',
'values': ['Vishnu', 'Satis'],
'values': [
{'value': 'Vishnu', 'description': 'If the first_name starts with K'},
{'value': 'Satis', 'description': 'If the first_name starts with M'},
],
'default_value_prompt': 'If none of the above value is suited, please use value other than the above in snake-case',
},
],
}
Expand Down
35 changes: 33 additions & 2 deletions flo_ai/parsers/flo_json_parser.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import json
import csv
from io import StringIO
from flo_ai.parsers.flo_parser import FloParser
from typing import List, Dict, Any, Optional, Literal
from pydantic import BaseModel, Field, create_model
Expand All @@ -18,6 +20,21 @@ def __init__(self, parse_contract: ParseContract):
self.contract = parse_contract
super().__init__()

def __dict_list_to_csv_string(self, data):
if not data or len(data) == 0:
return '```No data provided```'
headers = data[0].keys()
output = StringIO()

writer = csv.DictWriter(output, fieldnames=headers)
writer.writeheader()
writer.writerows(data)

csv_string = output.getvalue()
output.close()

return f'```\n{csv_string}```'

def __create_contract_from_json(self) -> BaseModel:
type_mapping = {
'str': str,
Expand All @@ -35,15 +52,29 @@ def __create_contract_from_json(self) -> BaseModel:
raise ValueError(
f"Field '{field['name']}' of type 'literal' must specify 'values'."
)
field_type_annotation = Literal[tuple(literal_values)]
literals = [literal_value['value'] for literal_value in literal_values]
field_type_annotation = Literal[tuple(literals)]
default_prompt = (
field['default_value_prompt']
if 'default_value_prompt' in field
else ''
)
field_description = f"""
{field['description']}
Following are the list of possibles values and its correponding description:
{self.__dict_list_to_csv_string(literal_values)}
{default_prompt}
"""
else:
field_type_annotation = type_mapping.get(field_type)
if field_type_annotation is None:
raise ValueError(f'Unsupported type: {field_type}')
field_description = field['description']

pydantic_fields[field['name']] = (
field_type_annotation,
Field(..., description=field['description']),
Field(..., description=field_description),
)

DynamicModel = create_model(self.contract.name, **pydantic_fields)
Expand Down

0 comments on commit ed8efdf

Please sign in to comment.