PHP code example of jvjvjv / code-talker

1. Go to this page and download the library: Download jvjvjv/code-talker library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jvjvjv / code-talker example snippets


'raw_exchanges' => [
    'enabled' => env('CODE_TALKER_RAW_EXCHANGES_ENABLED', true),
    'providers' => env('CODE_TALKER_RAW_EXCHANGES_PROVIDERS', 'lm-studio'),
    'retention_days' => (int) env('CODE_TALKER_RAW_EXCHANGES_RETENTION_DAYS', 14),
],

'turns' => [
    'queue' => env('CODE_TALKER_TURN_QUEUE'),
    'abandon_after_seconds' => (int) env('CODE_TALKER_TURN_ABANDON_SECONDS', 30),
    'poll_interval_ms' => (int) env('CODE_TALKER_TURN_POLL_MS', 250),
    'max_stream_seconds' => (int) env('CODE_TALKER_TURN_MAX_STREAM_SECONDS', 900),
    'retention_days' => (int) env('CODE_TALKER_TURN_RETENTION_DAYS', 7),
],

use Jvjvjv\CodeTalker\Services\LaravelAi\AgentFactory;
use Jvjvjv\CodeTalker\Models\AiSystem;

// From a specific system record
$agent = app(AgentFactory::class)->forSystem(
    AiSystem::find($id),
    instructions: 'You are a helpful assistant.',
    maxTokens: 2048,
    temperature: 0.7,
);

// From a feature key (resolves the default system for that feature)
$agent = app(AgentFactory::class)->forFeature('my-feature');

$response = $agent->prompt('Hello!');   // Laravel\Ai\Responses\AgentResponse
echo $response->text;

foreach ($agent->stream('Hello!') as $event) {
    // Laravel\Ai\Streaming\Events\* (TextDelta, ToolCall, StreamEnd, ...)
}

$agent = $factory->forSystem($system)->continue((string) $conversation->id, $user);

$agent->withStoredConversation((string) $conversation->id);

use Jvjvjv\CodeTalker\Services\AiPersonaConversationService;
use Jvjvjv\CodeTalker\Services\ChatBot\SseFrameEncoder;

public function message(Request $request, AiPersona $persona,
    AiPersonaConversationService $chat, SseFrameEncoder $encoder)
{
    $validated = $request->validate(['message' => ['ed to
        // it, so keep the script alive past an abort and flush every frame.
        ignore_user_abort(true);

        foreach ($encoder->encode($chat->continueConversation($conversation, $validated['message'])) as $frame) {
            echo $frame;
            ob_get_level() > 0 && ob_flush();
            flush();
        }
    }, headers: [
        'Content-Type' => 'text/event-stream',
        'Cache-Control' => 'no-cache',
        'X-Accel-Buffering' => 'no',
        'X-Chat-Hash' => $conversation->chat_hash,
    ]);
}

// Default: stops when the browser hangs up.
$chat->continueConversation($conversation, $message);

$chat->usingCancellationCheck(fn (): bool => $job->isReleased())
     ->continueConversation($conversation, $message);

// Start it. Returns an AiTurnRun; `public_id` is the handle to put in a URL.
$run = $chat->dispatchTurn($conversation, $request->string('message')->toString());

// Stream it — from the start, or from wherever the browser left off.
foreach ($encoder->encode($chat->resumeTurn($run, $after)) as $frame) {
    echo $frame;
    ob_get_level() > 0 && ob_flush();
    flush();
}

// Stop it early.
$chat->cancelTurn($run);

$presenter->transcript($conversation);              // visible messages, system prompt excluded
                                                    // each row carries `incomplete` — see Interrupted turns
$presenter->totalCostUsd($persona);                 // lifetime cost for a persona
$presenter->conversationsFor($user, $personas);     // an authenticated user's conversations

use Jvjvjv\CodeTalker\Jobs\RunAiOperatorJob;

// From anywhere that knows when this should run — an Eloquent observer, an
// event listener, a console command, your own scheduled job:
dispatch(new RunAiOperatorJob($operator, [
    'order' => $order->toArray(),
]));

// prompt_template: "A new order was placed: {{order.total}} for {{order.customer.email}}."
dispatch(new RunAiOperatorJob($operator, [
    'order' => ['total' => 42, 'customer' => ['email' => '[email protected]']],
]));

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Jvjvjv\CodeTalker\Support\ToolContext;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Attributes\Name;
use Laravel\Mcp\Server\Tool;

#[Name('get-weather')]
#[Description('Returns current weather for a given city.')]
class GetWeatherTool extends Tool
{
    public function __construct(
        private ToolContext $context,
    ) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'city' => $schema->string()->description('City name')->

use Jvjvjv\CodeTalker\CodeTalkerServiceProvider;

public function register(): void
{
    CodeTalkerServiceProvider::addToolDirectory(
        app_path('Services/Mcp/Tools'),
        'App\\Services\\Mcp\\Tools\\'
    );
}

return Response::structured([
    'content' => 'Updated your profile.',
    '_page_reload' => true,
]);

// config/code-talker.php
'tools' => [
    'http_request' => [
        'credentials' => [
            'api.example.com' => ['Authorization' => 'Bearer '.env('EXAMPLE_API_TOKEN')],
        ],
    ],
],

$aiSystemManager->update($system, [
    // ...
    'web_tool_policy' => json_encode([
        'allowed_domains' => ['api.example.com'],
        'credentials' => [
            'api.example.com' => ['Authorization' => 'Bearer '.env('EXAMPLE_API_TOKEN')],
        ],
    ]),
]);

CodeTalkerServiceProvider::registerToolParameterResolver(
    fn (AiConversation $conversation): array => [
        'myService' => app(MyService::class)->forConversation($conversation),
    ]
);

'mcp' => [
    'enabled' => env('CODE_TALKER_MCP_ENABLED', false),

    'web' => [
        'enabled' => true,
        'path' => env('CODE_TALKER_MCP_PATH', 'mcp/code-talker'),
        'middleware' => ['auth:sanctum'],
    ],

    'local' => [
        'enabled' => false,
        'handle' => env('CODE_TALKER_MCP_LOCAL_HANDLE', 'code-talker'),
    ],
],

use Jvjvjv\CodeTalker\Services\Management\AiSystemManager;

public function store(Request $request, AiSystemManager $systems)
{
    $system = $systems->create($request->all());

    return redirect()->route('your.systems.index');
}

public function rules(): array
{
    return AiSystemManager::createRules($this->all());
}

$deactivatedBots = $systems->delete($system);       // bots are deactivated, not deleted
$orphanedSystems = $prompts->delete($prompt);       // systems have their prompt cleared

// config/code-talker.php
'schedule' => false,

// Your app's Console\Kernel or routes/console.php
Schedule::command('ai:sync-conversation-usage')->twiceDaily();
bash
php artisan vendor:publish --tag=code-talker-config
php artisan vendor:publish --tag=code-talker-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=code-talker-config --force