blib/lib/Langertha/Role/ThinkTag.pm

filter: Statementstmt 100% 61 / 61 Branchbran 86.8% 33 / 38 Conditioncond 84.2% 16 / 19 MC/DCmcdc 80.0% 8 / 10 Subroutinesub 100% 6 / 6 Podpod 100% 1 / 1 totaltotal 92.5% 125 / 135 CC 27 SCAR 23.5
CC
27
Cov
93%
filter_think_content
16.0
__ANON__
7.4
__ANON__
4.2
CRAP 10.5
« blib/lib/Langertha/Plugin/Langfuse.pm ↑ Summary blib/lib/Langertha/ToolCall.pm »
1 package Langertha::Role::ThinkTag;
2 # ABSTRACT: Configurable think tag filtering for reasoning models
3 179 our $VERSION = '0.503';
4 179 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6  
7 179 has think_tag => (
8 is => 'ro',
9 isa => 'Str',
10 default => 'think',
11 );
12  
13  
14 179 has think_tag_filter => (
15 is => 'ro',
16 isa => 'Bool',
17 default => 1,
18 );
19  
20  
21 825 ▶sub filter_think_content {
Subroutine filter_think_content: called CC=16 SCAR=27.7
Pod documented
22 825 my ( $self, $text ) = @_;
23 825 ▶ return ($text, undef) unless $self->think_tag_filter && defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->think_tag_filter and defined $text 6 819 825
Condition100%3/3
$self->think_tag_filter and defined $text
!ll&&!rl&&r
15819
MC/DC100%2/2
$self->think_tag_filter and defined $text
$self->think_tag_filter defined $text
Truth table100%3/3
A and B
A= $self->think_tag_filterB= defined $text
ABresult
0X0
100
111
24 819 my ( $open, $close ) = ( '<' . $self->think_tag . '>', '</' . $self->think_tag . '>' );
25 819 my $first_open = index( $text, $open );
26 819 my $first_close = index( $text, $close );
27 # No tag at all: the text is the model's, byte for byte (karr k302).
28 819 ▶ return ($text, undef) if $first_open < 0 && $first_close < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $first_open < 0 and $first_close < 0 772 47 819
Condition100%3/3
$first_open < 0 and $first_close < 0
!ll&&!rl&&r
3215772
MC/DC100%2/2
$first_open < 0 and $first_close < 0
$first_open < 0 $first_close < 0
Truth table100%3/3
A and B
A= $first_open < 0B= $first_close < 0
ABresult
0X0
100
111
29 47 my ( @thinking, @kept );
30 47 my $rest = $text;
31 # Orphan closing tag: the chat template (DeepSeek-R1, Qwen3 thinking) put
32 # the opening tag into the prompt, so the reply starts inside the thought.
33 47 ▶ if ( $first_close >= 0 && ( $first_open < 0 || $first_close < $first_open ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first_close >= 0 and $first_open < 0 || $first_close < $first_open) 16 31 47
Condition100%6/6
$first_close >= 0 and $first_open < 0 || $first_close < $first_open
!ll&&!rl&&r
22916
$first_open < 0 or $first_close < $first_open
l!l&&r!l&&!r
15129
MC/DC100%3/3
$first_close >= 0 and $first_open < 0 || $first_close < $first_open
$first_close >= 0 $first_open < 0 $first_close < $first_open
Truth table100%4/4
A and B or C
A= $first_close >= 0B= $first_open < 0C= $first_close < $first_open
ABCresult
0XX0
1000
11X1
1011
34 16 my $thought = substr( $rest, 0, $first_close, '' );
35 16 substr( $rest, 0, length $close, '' );
36 16 ▶ push @thinking, $thought if length $thought;
Branch: 1 branch
BranchTrueFalseTotal
if length $thought 15 1 16
37 16 push @kept, '';
38 }
39 47 ▶ while ( ( my $at = index( $rest, $open ) ) >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $at = index($rest, $open)) >= 0) 34 44 78
40 34 push @kept, substr( $rest, 0, $at, '' );
41 34 substr( $rest, 0, length $open, '' );
42 34 my $end = index( $rest, $close );
43 34 ▶ if ( $end < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($end < 0) 3 31 34
44 # Unclosed tag: <think>... (rest of text) — model stopped mid-thought
45 3 ▶ push @thinking, $rest if length $rest;
Branch: 1 branch
BranchTrueFalseTotal
if length $rest 3 0 3
46 3 $rest = '';
47 3 last;
48 }
49 # Matched pair: <think>...</think>
50 31 push @thinking, substr( $rest, 0, $end, '' );
51 31 substr( $rest, 0, length $close, '' );
52 }
53 47 push @kept, $rest;
54 # Only the whitespace a removed block leaves at either end goes; the line
55 # after a leading block keeps its indentation.
56 47 my $filtered = join '', @kept;
57 47 ▶ if ( $kept[0] =~ /\A\s*\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kept[0] =~ /\A\s*\z/) 45 2 47
58 45 ▶ $filtered =~ s/\A\s*\n// or $filtered =~ s/\A\s+//;
Branch: 1 branch
BranchTrueFalseTotal
$filtered =~ s/\A\s*\n// or $filtered =~ s/\A\s+// 3 42 45
59 }
60 47 ▶ $filtered =~ s/\s+\z// if $kept[-1] =~ /\A\s*\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $kept[-1] =~ /\A\s*\z/ 5 42 47
61 47 ▶ my $thinking = @thinking ? join("\n", @thinking) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@thinking ? : 46 1 47
62 47 return ($filtered, $thinking);
63 }
64  
65  
66 703 ▶around 'chat_response' => sub {
Subroutine __ANON__: called CC=7 SCAR=20.0
67 703 my ( $orig, $self, @args ) = @_;
68 703 my $response = $self->$orig(@args);
69 623 ▶ return $response unless $self->think_tag_filter;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->think_tag_filter 1 622 623
70 622 my $content = $response->content;
71 622 my ($filtered, $thinking) = $self->filter_think_content($content);
72 622 ▶ return $response
Branch: 1 branch
BranchTrueFalseTotal
if not defined $thinking and ($filtered // "") eq ($content // "") 599 23 622
Condition57%4/7
not defined $thinking and ($filtered // "") eq ($content // "")
!ll&&!rl&&r
230599
$filtered // ""
l!l
5990
$content // ""
l!l
5990
MC/DC50%1/2
not defined $thinking and ($filtered // "") eq ($content // "")
not defined $thinking $filtered
MC/DC0%0/1
$content // ""
$content
Truth table66%2/3
not(A) and B
A= not defined $thinkingB= $filtered
ABresult
0X0
100
111
Truth table50%1/2
A
A= $content
Aresult
11
00
73 if !defined $thinking && ( $filtered // '' ) eq ( $content // '' );
74 23 ▶ return $response->clone_with(
Branch: 1 branch
BranchTrueFalseTotal
defined $thinking ? : 23 0 23
75 content => $filtered,
76 defined $thinking ? (thinking => $thinking) : (),
77 );
78 179 };
79  
80 # Both streaming entry points carry an aggregated thinking string alongside
81 # content (Role::Chat::aggregate_thinking, filled from the native reasoning
82 # deltas). Two thinking sources can appear and must not both win: a tag-based
83 # model inlines its chain-of-thought in <think> tags in the content, while a
84 # native-reasoning model surfaces it out-of-band as the aggregated string. The
85 # non-stream `around chat_response` resolves this the same way — tag-extracted
86 # thinking overrides the native one only when tags were actually present.
87 4 ▶around 'simple_chat_stream' => sub {
Subroutine __ANON__: called CC=4 SCAR=14.3
88 4 my ( $orig, $self, @args ) = @_;
89 4 my ( $content, $thinking ) = $self->$orig(@args);
90 2 ▶ if ( $self->think_tag_filter ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->think_tag_filter) 2 0 2
91 2 my ( $filtered, $tag_thinking ) = $self->filter_think_content($content);
92 2 $content = $filtered;
93 2 ▶ $thinking = $tag_thinking if defined $tag_thinking;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tag_thinking 0 2 2
94 }
95 2 ▶ return wantarray ? ( $content, $thinking ) : $content;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 2 2
96 179 };
97  
98 211 ▶around 'chat_stream_realtime_f' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
99 211 my ( $orig, $self, @args ) = @_;
100 167 ▶ return $self->$orig(@args)->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
101 167 my ( $content, $chunks, $timing, $thinking ) = @_;
102 167 ▶ return Future->done($content, $chunks, $timing, $thinking)
Branch: 1 branch
BranchTrueFalseTotal
unless $self->think_tag_filter 1 166 167
103 unless $self->think_tag_filter;
104 166 my ($filtered, $tag_thinking) = $self->filter_think_content($content);
105 166 ▶ $thinking = $tag_thinking if defined $tag_thinking;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tag_thinking 10 156 166
106 166 return Future->done($filtered, $chunks, $timing, $thinking);
107 211 });
108 179 };
109  
110  
111 179 1;
112  
113 __END__
114  
115 =pod
116  
117 =encoding UTF-8
118  
119 =head1 NAME
120  
121 Langertha::Role::ThinkTag - Configurable think tag filtering for reasoning models
122  
123 =head1 VERSION
124  
125 version 0.503
126  
127 =head1 SYNOPSIS
128  
129 # Think tag filter is enabled by default on all engines.
130 # <think> tags are automatically stripped and thinking preserved:
131 my $response = $engine->simple_chat('Explain quantum computing');
132 say $response; # clean answer text
133 say $response->thinking; # chain-of-thought (if any)
134  
135 # For APIs with native reasoning (DeepSeek, Anthropic, Gemini),
136 # thinking is extracted from the API response automatically —
137 # no tag filtering needed.
138  
139 # Custom tag name (e.g. for models using <reasoning> tags):
140 my $engine = Langertha::Engine::vLLM->new(
141 url => $vllm_url,
142 model => 'my-reasoning-model',
143 think_tag => 'reasoning',
144 );
145  
146 # Disable filtering if you want raw output:
147 my $engine = Langertha::Engine::OpenAI->new(
148 api_key => $key,
149 think_tag_filter => 0,
150 );
151  
152 =head1 DESCRIPTION
153  
154 This role provides automatic filtering of C<E<lt>thinkE<gt>> tags from LLM
155 responses. Many reasoning models (DeepSeek R1, QwQ, Hermes with reasoning
156 enabled) emit chain-of-thought reasoning wrapped in C<E<lt>thinkE<gt>> tags
157 inline with their response text. This role strips those tags and preserves
158 the thinking content on the L<Langertha::Response/thinking> attribute.
159  
160 Composed into L<Langertha::Role::Chat>, so every engine gets it automatically.
161 The filter handles closed pairs (C<E<lt>thinkE<gt>...E<lt>/thinkE<gt>>),
162 a closing tag whose opening tag the chat template put into the prompt, and
163 unclosed tags where the model stopped mid-thought (see
164 L</filter_think_content>). A response without think tags is left untouched.
165  
166 For APIs that provide reasoning content natively (DeepSeek C<reasoning_content>,
167 Anthropic C<thinking> blocks, Gemini C<thought> parts), the thinking is
168 extracted directly from the API response — no tag filtering needed.
169  
170 =head2 think_tag
171  
172 The XML tag name used for thinking content. Defaults to C<think>.
173 Some models may use different tag names (e.g. C<reasoning>).
174  
175 =head2 think_tag_filter
176  
177 When true, C<E<lt>thinkE<gt>...E<lt>/thinkE<gt>> blocks are stripped from
178 response text. The thinking content is preserved on the
179 L<Langertha::Response/thinking> attribute for inspection. Defaults to C<1>
180 (enabled). Set to C<0> to pass think tags through unmodified.
181  
182 =head2 filter_think_content
183  
184 my ($filtered_text, $thinking) = $engine->filter_think_content($text);
185  
186 Strips C<E<lt>thinkE<gt>...E<lt>/thinkE<gt>> blocks from C<$text>. Handles
187 three shapes:
188  
189 =over
190  
191 =item * closed pairs, anywhere in the text, each one a thinking block;
192  
193 =item * an orphan closing tag: a C<E<lt>/thinkE<gt>> with no opening tag
194 before it. Chat templates of DeepSeek-R1 and Qwen3 thinking models put the
195 opening tag into the prompt, so a server without a reasoning parser returns
196 C<reasoning...E<lt>/thinkE<gt>answer>; everything before that first closing
197 tag is thinking;
198  
199 =item * an unclosed opening tag, where the model stopped mid-thought:
200 everything from it to the end is thinking.
201  
202 =back
203  
204 Nested tags are not balanced (the first closing tag ends a block) and the tag
205 match is case-sensitive.
206  
207 Text without any think tag is returned exactly as given, whitespace included.
208 When blocks were removed, only the whitespace they leave at the start or end
209 of the text is trimmed; after a leading block, the first content line keeps
210 its indentation. Returns the filtered text and the extracted thinking content
211 (or C<undef> if none). Returns the original text unchanged when
212 L</think_tag_filter> is false.
213  
214 Streaming callbacks (C<chunk_callback>) see the raw text, tags included; only
215 the aggregated content and thinking a streaming call returns are filtered.
216  
217 =head1 SEE ALSO
218  
219 =over
220  
221 =item * L<Langertha::Response> - Response object with C<thinking> attribute
222  
223 =item * L<Langertha::Role::Chat> - Chat role that composes this role
224  
225 =item * L<Langertha::Engine::NousResearch> - Engine with C<reasoning> attribute for Hermes models
226  
227 =back
228  
229 =head1 SUPPORT
230  
231 =head2 Issues
232  
233 Please report bugs and feature requests on GitHub at
234 L<https://github.com/Getty/langertha/issues>.
235  
236 =head2 IRC
237  
238 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
239  
240 =head1 CONTRIBUTING
241  
242 Contributions are welcome! Please fork the repository and submit a pull request.
243  
244 =head1 AUTHOR
245  
246 Torsten Raudssus <getty@cpan.org>
247  
248 =head1 COPYRIGHT AND LICENSE
249  
250 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
251  
252 This is free software; you can redistribute it and/or modify it under
253 the same terms as the Perl 5 programming language system itself.
254  
255 =cut
« blib/lib/Langertha/Plugin/Langfuse.pm ↑ Summary blib/lib/Langertha/ToolCall.pm »