Defining Reusable Directives: The example defines a set of reusable directives for balanced analysis:
balancedAnalysisDirectives := []string{"Consider technological, economic, social, and ethical implications","Provide at least one potential positive and one potential negative outcome for each perspective","Ensure the analysis is balanced and objective",}
Creating a Custom Prompt Template: A custom prompt template is created for balanced analysis:
balancedAnalysisTemplate := gollm.NewPromptTemplate("BalancedAnalysis","Analyze a topic from multiple perspectives",`Analyze the following topic from multiple perspectives: {{.Topic}}Please structure your response as a JSON object with the following format:{ "perspectives": [ { "name": "Perspective Name", "implications": [ "Positive implication", "Negative implication" ] } ], "summary": "A brief, balanced summary of the analysis"}`, gollm.WithPromptOptions( gollm.WithDirectives(balancedAnalysisDirectives...), gollm.WithMaxLength(500), ),)
This template includes the JSON structure for the expected output.
Analyzing Multiple Topics: The example defines a list of topics and analyzes each one:
topics := []string{"The impact of artificial intelligence on job markets","The role of social media in modern democracy","The transition to renewable energy sources",}for _, topic :=range topics {// Execute the prompt template prompt, err := balancedAnalysisTemplate.Execute(map[string]interface{}{"Topic": topic, })// Generate the analysis analysisJSON, err := llmClient.Generate(ctx, prompt, gollm.WithJSONSchemaValidation())// Parse the JSON responsevar result AnalysisResult err = json.Unmarshal([]byte(analysisJSON), &result)// Print the structured analysis// ...}
For each topic, it executes the template, generates an analysis, parses the JSON response, and prints the structured analysis.
Demonstrating Additional Features: The example showcases additional gollm package features:
keyPoints, err := gollm.ChainOfThought(ctx, llmClient, fmt.Sprintf("Extract 3 key points from this analysis:\n%s", analysisJSON))
Error Handling and Retries: The example demonstrates error handling by intentionally causing an error:
_, err = gollm.QuestionAnswer(ctx, llmClient, "This is an intentionally long prompt that exceeds the token limit to demonstrate error handling.")
if err !=nil { fmt.Printf("Expected error occurred: %v\n", err)}
In summary, this advanced example demonstrates:
Defining structured output using Go structs
Creating a custom prompt template with specific JSON output format
Analyzing multiple topics using the same template
Parsing and processing structured JSON responses
Using additional gollm features like Summarize and ChainOfThought
Error handling and retry mechanisms
This example is particularly useful for developers who need to work with structured outputs from LLMs, want to create reusable analysis templates, and leverage advanced features of the gollm package for complex NLP tasks.