-
-
Save ganeshan/97dd09799a31a8f57d4a0c1898dc4b8b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import ollama | |
| from pydantic import BaseModel, Field | |
| from typing import Literal, List | |
| # Define a more descriptive JSON structure using Pydantic. | |
| class UserInfo(BaseModel): | |
| name: str = Field(description="The full name of the user who wrote the text.") | |
| sentiment: Literal["positive", "neutral", "negative"] = Field( | |
| description="The overall sentiment of the text." | |
| ) | |
| reasoning: List[str] = Field( | |
| description="A step-by-step explanation of how the sentiment was determined." | |
| ) | |
| # The text we want to analyze. | |
| prompt = "I'm really happy with the new laptop I bought from TechCorp. My name is John Doe." | |
| # Ask the model for the information, passing the Pydantic model directly. | |
| response = ollama.chat( | |
| model='gemma3', | |
| messages=[ | |
| { | |
| 'role': 'system', | |
| 'content': 'You are an expert sentiment analysis AI. Your task is to accurately analyze the sentiment of a given text and extract key information based on the user-provided schema.', | |
| }, | |
| { | |
| 'role': 'user', | |
| 'content': f'Extract the user information and their sentiment from the following text: "{prompt}".', | |
| }, | |
| ], | |
| format=UserInfo, | |
| ) | |
| # The output will be a clean JSON object. | |
| print(response['message']['content']) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "name": "John Doe", | |
| "sentiment": "positive", | |
| "reasoning": [ | |
| "The user explicitly states they are 'really happy'.", | |
| "The phrase 'really happy' is a strong indicator of positive sentiment.", | |
| "No negative words or phrases were detected in the text." | |
| ] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment