Skip to content

Instantly share code, notes, and snippets.

@feliperyan
Created February 29, 2024 04:15
Show Gist options
  • Save feliperyan/26befd2870eb67eb0a553d567d550107 to your computer and use it in GitHub Desktop.
Save feliperyan/26befd2870eb67eb0a553d567d550107 to your computer and use it in GitHub Desktop.
JSON Output Gemini
import json
import logging
from typing import List, Dict, Any
from langchain_google_vertexai import VertexAI
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import JsonOutputParser
from langchain.output_parsers import OutputFixingParser
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.runnables.base import RunnableSerializable
# Basic configuration
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Get a logger instance
logger = logging.getLogger(__name__)
VERTEX_AI_MODEL_NAME = "gemini-pro"
class Hangable(BaseModel):
"""Analysis of product description"""
summary: str = Field(description="Succinct summary of the description")
width: str = Field(description="Width of the product")
height: str = Field(description="Height of the product")
isFrame: bool = Field(description="Boolean if the product is a frame")
creator: str = Field(description="Name of the artist or designer")
def process_review(product, chain):
try:
result = chain.invoke({"product": product})
return result
except Exception as e:
raise Exception(
f"Error extracting terms from sentence '{product}': {e}"
) from e
def main():
llm = VertexAI( model_name=VERTEX_AI_MODEL_NAME, temperature=0, top_p=1, max_output_tokens=8192 )
parser = JsonOutputParser(pydantic_object=Hangable)
retry_parser = OutputFixingParser.from_llm(parser=parser, llm=llm, max_retries=3)
prompt = PromptTemplate(
template="""You are a product review analyst at large furniture and home goods company. You role is to analyse product descriptions to summarise the descriptions, extract the product dimensions, determine if it's a photo frame and extract the artist or designer's name. Here is an example:
**Product Description**:
Decorate your walls with your favourite albums. The frame is designed to fit an LP cover.
Frame width: 32.5 cm, Frame height: 32.5 cm and Frame, depth: 2 cm
Designer
M Warnhammar/A Fredriksson
**Result in JSON**:
"summary": "Picture frame ideal for LP albums",
"width": "32.5",
"height": "32.5",
"isFrame": "True"
"classification": "True" \n
**Review**:\n
{product}\n
{format_instructions}\n""",
input_variables=["product"],
partial_variables={
"format_instructions": retry_parser.get_format_instructions()
},
)
chain = prompt | llm | retry_parser
product = """Motif created by Assaf Frank. The picture has extra depth and life,
because it's printed on high quality canvas. The picture stands out from the wall in an attractive way, because it continues around the edges of the canvas.
You can personalise your home with artwork that expresses your style. It's 140 cm wide and 56 cm tall"""
try:
results = process_review(product, chain)
return results
except Exception as e:
print(f"Error in main processing loop: {e}")
if __name__ == "__main__":
result = main()
print(json.dumps(result, indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment