Skip to content

Instantly share code, notes, and snippets.

@RohanAwhad
Last active October 12, 2024 23:54
Show Gist options
  • Save RohanAwhad/e0c96704f174c88c2352e054be52c519 to your computer and use it in GitHub Desktop.
Save RohanAwhad/e0c96704f174c88c2352e054be52c519 to your computer and use it in GitHub Desktop.
import dataclasses
import openai
import os
import re
import yaml
from pydantic import BaseModel, ValidationError
from typing import Optional
@dataclasses.dataclass
class Message:
role: str
content: str
def llm_call(model: str, messages: list[Message]):
client = openai.OpenAI(api_key=os.environ["TOGETHER_API_KEY"], base_url="https://api.together.xyz/v1")
res = client.chat.completions.create(model=model, messages=[dataclasses.asdict(x) for x in messages], temperature=0.8, max_tokens=4096)
return res.choices[0].message.content
def generate_response_prompt(model: type(BaseModel)) -> str:
TAB = " "
ret = "Respond in YAML format, following the below Pydantic model:\n```python\n"
ret += f"from pydantic import BaseModel, Field\n\nclass {model.__name__}(BaseModel):\n"
yaml_example = ""
for attr, prop in model.model_json_schema()["properties"].items():
yaml_example += f"\n{attr}: ..."
if 'type' in prop and prop["type"] == "array":
ret += f"{TAB}{attr}: list[{prop['items']['type']}] = Field(desc='{prop['desc']}', max_length={prop['maxItems']})\n"
elif 'anyOf' in prop:
ret += f"{TAB}{attr}: {' | '.join([x['type'] for x in prop['anyOf']])} = Field(desc='{prop['desc']}'"
else:
ret += f"{TAB}{attr}: {prop['type']} = Field(desc='{prop['desc']}')\n"
ret += f"```\n\nYAML should be enclosed in triple backticks like\n```yaml{yaml_example}\n```\n"
return ret
def parse_llm_response(model: type[BaseModel], llm_res: str):
ptrn = re.compile(r"```yaml(.*?)```", re.DOTALL)
match = re.search(ptrn, llm_res)
if match:
try:
res_dict = yaml.safe_load(match.group(1))
if isinstance(res_dict, dict): ret = model.model_validate(res_dict)
elif isinstance(res_dict, list): ret = [model.model_validate(x) for x in res_dict]
else: raise Exception(f"Shouldn't have reached here. Expected type of dict or list, but got {type(res_dict)}")
return ret
except ValidationError as e:
print("Pydantic Validation Error:", e)
print(llm_res)
except yaml.YAMLError as e:
print("YAML parsing error:", e)
print(llm_res)
except Exception as e:
print("Error:", e)
print(llm_res)
else:
print("Couldn't find yaml tags\nResponse:")
print(llm_res)
return None
def run(model: str, messages: list[Message], max_retries: int, response_model: Optional[type(BaseModel)] = None):
messages[0].content += f"\n---\n\n{generate_response_prompt(response_model)}---\n"
while max_retries:
res = llm_call(model, messages)
ret = parse_llm_response(response_model, res)
if ret is None: max_retries -= 1
else: return ret
@RohanAwhad
Copy link
Author

Usage Example:

from pydantic import BaseModel, Field
from structured_llm_output import Message, run

if __name__ == '__main__':
  # Example 2:
  inp = """
Richard M
Richard M
Lansing, MI126 contributions

0

Good food, good beer, good atmosphere. I ate the Easter bunny on Easter.
Mar 2024 • Family
I liked the peach ale a lot. I had a four way sampler of four others which were good including the Kilt Lifter, Kuhl Beans, oatmeal stout, and Kuhl Beans. I had the Bunny enchiladas on the special which was good. Others enjoyed their food, which was burgers, and fish and chips.
Written June 1, 2024
This review is the subjective opinion of a Tripadvisor member and not of Tripadvisor LLC. Tripadvisor performs checks on reviews as part of our industry-leading trust & safety standards. Read our transparency report to learn more.
Julia C
Julia C
Tucson, AZ37 contributions

0

Watch out at the airport!!
Oct 2023 • Couples
We went to their restaurant at Sky Harbor Airport between flights. My husband and I split a sandwich. It was fine and the service was very good. But.........the menu didn't list wine, but they have a full bar, so I asked the waitress. She said they did and brought me a Cabernet. When the bill came, the charge was $25!!!!!! Since it wasn't on the menu, I didn't know before ordering it. The waitress said she had given up mentioning it. Talk about highway robbery. Not going there again!
Written October 25, 2023
This review is the subjective opinion of a Tripadvisor member and not of Tripadvisor LLC. Tripadvisor performs checks on reviews as part of our industry-leading trust & safety standards. Read our transparency report to learn more.
Deb D
Deb D
Eden Prairie, MN51 contributions

0

Nice beers, good food
Mar 2023
The beer flight was great, the food was very good for all 5 of us and the only miss at the place was the lack of parking. We were meeting people and they had to park a block or so away and we were right out front. Enjoyed our time there!
Written March 7, 2023
This review is the subjective opinion of a Tripadvisor member and not of Tripadvisor LLC. Tripadvisor performs checks on reviews as part of our industry-leading trust & safety standards. Read our transparency report to learn more.
Jacob W
Jacob W
Royse City, TX86 contributions

0

Great beer, good food, slow service, and no parking
Jan 2023
The beer was great. We were there with a large group of soccer players and parents. We made a reservation with them, but I don't think they were ready for a large group. We were there for almost and hour before they took our order. Then almost another full hour before we got our food.

Thankfully the beer and the company was great. The food was pretty good too once it got there.

No complaints about the facility itself beside the lack of parking. We had to park on the street about a quarter mile down the road.

Read more
Written January 23, 2023
This review is the subjective opinion of a Tripadvisor member and not of Tripadvisor LLC. Tripadvisor performs checks on reviews as part of our industry-leading trust & safety standards. Read our transparency report to learn more.
Matt P
Matt P
Petoskey, MI228 contributions

0

Nice Dinner
Dec 2022 • Family
We had a very nice dinner. My youngest daughter wanted chicken strips for dinner, so we looked for a brewery & found this one. The menu looked good & had good reviews. Our 30 minute wait was more like 5 minutes (but we also got there after 7, behind the initial dinner rush & lots of people were leaving as we got there, so that probably helped, I’m sure it certainly has longer waits). Nice looking inside with a large outdoor seating area (with heaters keeping the temperature very comfortable for those sitting outside in the 55 degree temperature). They had quite an extensive beer list. We tried a few & they were very good. We really enjoyed our appetizers (pretzel with cheese & the edamame). My wife got a sale that was enormous! She couldn’t finish it, as much as she wanted to it was so good. My youngest daughter got the chicken fingers & they were excellent. Fried perfectly with lots of tender meat. The reason for only 4/5 stars though was my French Dip Sandwich. It just didn’t have much flavor to it. I didn’t “dislike” it, the meat was tender & wasn’t tough, it was just a bland taste. I wish I had gone with one of my other choices (nachos or the Buffalo Caesar Salad). I’m glad we went & if we’re back in the area again, I’d go again, but I’d pick something different for my main course.

Read more
Written December 30, 2022
This review is the subjective opinion of a Tripadvisor member and not of Tripadvisor LLC. Tripadvisor performs checks on reviews as part of our industry-leading trust & safety standards. Read our transparency report to learn more.
lost72
lost72
Illinois30 contributions

0

Highly recommend for great beer AND food
Dec 2022 • Family
Great beer, amazing food, wonderful service! Had the peach ale and the Leroy brown, actually 2 of each. The poke bowl, chicken strips, brewer’s dip, enchiladas, poutine, and chicken rolls. All delicious! We wish we had time to come back because this was a favorite in Phoenix! Thanks for the great beer, food, and service!
Written December 27, 2022
This review is the subjective opinion of a Tripadvisor member and not of Tripadvisor LLC. Tripadvisor performs checks on reviews as part of our industry-leading trust & safety standards. Read our transparency report to learn more.
cari k
cari k
1 contribution

0

Excellent
Nov 2022 • Family
What a great vibe! Amazing food and fun drinks! Had a great experience- Hailey was wonderful and enjoyed talking to the manager, Carter! Excellent service will definitely be back!!!
Written November 5, 2022
This review is the subjective opinion of a Tripadvisor member and not of Tripadvisor LLC. Tripadvisor performs checks on reviews as part of our industry-leading trust & safety standards. Read our transparency report to learn more.
jamie
jamie
Henderson, NV6 contributions

0

Excellent
Jul 2022 • Couples
Highly recommend! Food was excellent and my husband enjoyed the flights of beer. He loved the seasonal beer he had so much that we took a growler of it home. We sat at the bar and the service was great.




Written July 6, 2022
This review is the subjective opinion of a Tripadvisor member and not of Tripadvisor LLC. Tripadvisor performs checks on reviews as part of our industry-leading trust & safety standards. Read our transparency report to learn more.
marzbar32
marzbar32
Ferndale, WA12 contributions

0

Delicious beer and even better food
Jul 2022 • Friends
We came here with a group of 8 people, including kids. They seated us very quickly even though the place was busy, and the service was great. We all ordered something different and we all raved about the food. The carne adovada had so much flavor and the Brussel sprouts were to die for. From pizza to burgers to enchiladas you can’t go wrong here! Plus the beer was great too. Just wish we weren’t from out of town so we could come here more often!

---

The above are reviews for FourPeak brewery. Parse them.
"""

  class Review(BaseModel):
      review_date: str = Field(desc='date of review in "Month Date, Year" format')
      content: str = Field(desc="actual content of the review")
      sentiment: str = Field(
          desc="what's the sentiment of the review. positive, negative or neutral"
      )
      speciality_dishes: list[str] = Field(
          desc="dishes which the guests loved, if any, else []", max_length=3
      )

  result = run(
      "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
      messages=[Message("user", inp)],
      max_retries=3,
      response_model=Review,
  )
  print(result)

Output:

[Review(review_date='March 2024', content='Good food, good beer, good atmosphere. I ate the Easter bunny on Easter. I liked the peach ale a lot. I had a four way sampler of four others which were good including the Kilt Lifter, Kuhl Beans, oatmeal stout, and Kuhl Beans. I had the Bunny enchiladas on the special which was good. Others enjoyed their food, which was burgers, and fish and chips.', sentiment='positive', speciality_dishes=['peach ale', 'Bunny enchiladas', 'Kilt Lifter']), Review(review_date='October 2023', content="Watch out at the airport!! We went to their restaurant at Sky Harbor Airport between flights. My husband and I split a sandwich. It was fine and the service was very good. But.........the menu didn't list wine, but they have a full bar, so I asked the waitress. She said they did and brought me a Cabernet. When the bill came, the charge was $25!!!!!! Since it wasn't on the menu, I didn't know before ordering it. The waitress said she had given up mentioning it. Talk about highway robbery. Not going there again!", sentiment='negative', speciality_dishes=[]), Review(review_date='March 2023', content='Nice beers, good food. The beer flight was great, the food was very good for all 5 of us and the only miss at the place was the lack of parking. We were meeting people and they had to park a block or so away and we were right out front. Enjoyed our time there!', sentiment='positive', speciality_dishes=['beer flight']), Review(review_date='January 2023', content="Great beer, good food, slow service, and no parking. The beer was great. We were there with a large group of soccer players and parents. We made a reservation with them, but I don't think they were ready for a large group. We were there for almost and hour before they took our order. Then almost another full hour before we got our food.", sentiment='neutral', speciality_dishes=[]), Review(review_date='December 2022', content='Nice Dinner. We had a very nice dinner. My youngest daughter wanted chicken strips for dinner, so we looked for a brewery & found this one. The menu looked good & had good reviews. Our 30 minute wait was more like 5 minutes (but we also got there after 7, behind the initial dinner rush & lots of people were leaving as we got there, so that probably helped, I’m sure it certainly has longer waits). Nice looking inside with a large outdoor seating area (with heaters keeping the temperature very comfortable for those sitting outside in the 55 degree temperature). They had quite an extensive beer list. We tried a few & they were very good. We really enjoyed our appetizers (pretzel with cheese & the edamame). My wife got a sale that was enormous! She couldn’t finish it, as much as she wanted to it was so good. My youngest daughter got the chicken fingers & they were excellent. Fried perfectly with lots of tender meat. The reason for only 4/5 stars though was my French Dip Sandwich. It just didn’t have much flavor to it. I didn’t “dislike” it, the meat was tender & wasn’t tough, it was just a bland taste. I wish I had gone with one of my other choices (nachos or the Buffalo Caesar Salad). I’m glad we went & if we’re back in the area again, I’d go again, but I’d pick something different for my main course.', sentiment='neutral', speciality_dishes=['pretzel with cheese', 'edamame', 'chicken fingers']), Review(review_date='December 2022', content='Highly recommend for great beer AND food. Great beer, amazing food, wonderful service! Had the peach ale and the Leroy brown, actually 2 of each. The poke bowl, chicken strips, brewer’s dip, enchiladas, poutine, and chicken rolls. All delicious! We wish we had time to come back because this was a favorite in Phoenix! Thanks for the great beer, food, and service!', sentiment='positive', speciality_dishes=['peach ale', 'Leroy brown', 'poke bowl']), Review(review_date='November 2022', content='Excellent. What a great vibe! Amazing food and fun drinks! Had a great experience- Hailey was wonderful and enjoyed talking to the manager, Carter! Excellent service will definitely be back!!!', sentiment='positive', speciality_dishes=[]), Review(review_date='July 2022', content='Excellent. Highly recommend! Food was excellent and my husband enjoyed the flights of beer. He loved the seasonal beer he had so much that we took a growler of it home. We sat at the bar and the service was great.', sentiment='positive', speciality_dishes=['flights of beer']), Review(review_date='July 2022', content='Delicious beer and even better food. We came here with a group of 8 people, including kids. They seated us very quickly even though the place was busy, and the service was great. We all ordered something different and we all raved about the food. The carne adovada had so much flavor and the Brussel sprouts were to die for. From pizza to burgers to enchiladas you can’t go wrong here! Plus the beer was great too. Just wish we weren’t from out of town so we could come here more often!', sentiment='positive', speciality_dishes=['carne adovada', 'Brussel sprouts'])]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment